ActivityPub-federated video streaming platform using P2P directly in your web browser
Add channel collaborators feature
Chocobozzz381f8e3b3a25
diff --git a/apps/peertube-runner/src/server/process/shared/process-live.ts b/apps/peertube-runner/src/server/process/shared/process-live.tsindex 3c94e87024..3b054b2cb5 100644--- a/apps/peertube-runner/src/server/process/shared/process-live.ts+++ b/apps/peertube-runner/src/server/process/shared/process-live.ts@@ -23,11 +23,11 @@ import { ConfigManager } from '../../../shared/config-manager.js'import { logger } from '../../../shared/index.js'import { buildFFmpegLive, ProcessOptions } from './common.js'-type CustomLiveRTMPHLSTranscodingUpdatePayload =- Omit<LiveRTMPHLSTranscodingUpdatePayload, 'resolutionPlaylistFile'> & { resolutionPlaylistFile?: [ Buffer, string ] | Blob | string }+type CustomLiveRTMPHLSTranscodingUpdatePayload = Omit<LiveRTMPHLSTranscodingUpdatePayload, 'resolutionPlaylistFile'> & {+ resolutionPlaylistFile?: [Buffer, string] | Blob | string+}export class ProcessLiveRTMPHLSTranscoding {-private readonly outputPath: stringprivate readonly fsWatchers: FSWatcher[] = []@@ -326,7 +326,7 @@ export class ProcessLiveRTMPHLSTranscoding {const p = payloadBuilder().then(p => this.updateWithRetry(p))- if (!sequentialPromises) sequentialPromises = p+ if (sequentialPromises === undefined) sequentialPromises = pelse sequentialPromises = sequentialPromises.then(() => p)}@@ -388,7 +388,7 @@ export class ProcessLiveRTMPHLSTranscoding {return [Buffer.from(this.latestFilteredPlaylistContent[playlistName], 'utf-8'),join(this.outputPath, 'master.m3u8')- ] as [ Buffer, string ]+ ] as [Buffer, string]}// ---------------------------------------------------------------------------diff --git a/client/src/app/+accounts/account-video-channels/account-video-channels.component.ts b/client/src/app/+accounts/account-video-channels/account-video-channels.component.tsindex 46e7b1d7f9..1ec08253bb 100644--- a/client/src/app/+accounts/account-video-channels/account-video-channels.component.ts+++ b/client/src/app/+accounts/account-video-channels/account-video-channels.component.ts@@ -93,7 +93,7 @@ export class AccountVideoChannelsComponent implements OnInit, OnDestroy {sort: '-updatedAt'}- this.videoChannelService.listAccountVideoChannels(options)+ this.videoChannelService.listAccountChannels(options).pipe(tap(res => {this.channelPagination.totalItems = res.totaldiff --git a/client/src/app/+accounts/accounts.component.ts b/client/src/app/+accounts/accounts.component.tsindex f9f3d97a58..c0d012627c 100644--- a/client/src/app/+accounts/accounts.component.ts+++ b/client/src/app/+accounts/accounts.component.ts@@ -95,7 +95,7 @@ export class AccountsComponent implements OnInit, OnDestroy {distinctUntilChanged(),switchMap(accountId => this.accountService.getAccount(accountId)),tap(account => this.onAccount(account)),- switchMap(account => this.videoChannelService.listAccountVideoChannels({ account })),+ switchMap(account => this.videoChannelService.listAccountChannels({ account })),catchError(err =>this.restExtractor.redirectTo404IfNotFound(err, 'other', [HttpStatusCode.BAD_REQUEST_400,diff --git a/client/src/app/+admin/overview/videos/video-list.component.html b/client/src/app/+admin/overview/videos/video-list.component.htmlindex a303ebc35d..b812bb2f38 100644--- a/client/src/app/+admin/overview/videos/video-list.component.html+++ b/client/src/app/+admin/overview/videos/video-list.component.html@@ -75,7 +75,7 @@<ng-template #actionCell let-video><my-video-actions-dropdown- placement="bottom auto" buttonDirection="horizontal" buttonStyled="true" [video]="video" [displayOptions]="videoActionsOptions"+ placement="bottom auto" buttonIcon="more-horizontal" buttonStyled="true" [video]="video" [displayOptions]="videoActionsOptions"(videoRemoved)="table.loadData()" (videoFilesRemoved)="table.loadData()" (transcodingCreated)="table.loadData()"></my-video-actions-dropdown></ng-template>diff --git a/client/src/app/+admin/system/logs/logs.component.html b/client/src/app/+admin/system/logs/logs.component.htmlindex 7afc65e46f..440836c9a2 100644--- a/client/src/app/+admin/system/logs/logs.component.html+++ b/client/src/app/+admin/system/logs/logs.component.html@@ -15,7 +15,7 @@<label i18n for="log-start-date">Start date</label><my-select-options inputId="log-start-date" [items]="timeChoices" [(ngModel)]="startDate" (ngModelChange)="refresh()">- <ng-template ptTemplate="item" let-item>+ <ng-template #selectOption let-item>{{ item.label }} ({{ item.id | ptDate: item.dateFormat }} - <span i18n>now</span>)</ng-template></my-select-options>@@ -25,7 +25,7 @@<label i18n for="log-level">Log level</label><my-select-options inputId="log-level" [items]="levelChoices" [(ngModel)]="level" (ngModelChange)="refresh()">- <ng-template ptTemplate="item" let-item>+ <ng-template #selectOption let-item><span class="level-choice me-1" [ngClass]="item.id">⬤</span> {{ item.label }}</ng-template></my-select-options>diff --git a/client/src/app/+admin/system/logs/logs.component.ts b/client/src/app/+admin/system/logs/logs.component.tsindex 7ed95610be..511cb42ee4 100644--- a/client/src/app/+admin/system/logs/logs.component.ts+++ b/client/src/app/+admin/system/logs/logs.component.ts@@ -4,7 +4,6 @@ import { FormsModule } from '@angular/forms'import { LocalStorageService, Notifier } from '@app/core'import { SelectOptionsComponent } from '@app/shared/shared-forms/select/select-options.component'import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'-import { PeerTubeTemplateDirective } from '@app/shared/shared-main/common/peertube-template.directive'import { ServerLogLevel } from '@peertube/peertube-models'import { SelectTagsComponent } from '../../../shared/shared-forms/select/select-tags.component'import { ButtonComponent } from '../../../shared/shared-main/buttons/button.component'@@ -24,8 +23,7 @@ import { LogsService } from './logs.service'ButtonComponent,PTDatePipe,CopyButtonComponent,- SelectOptionsComponent,- PeerTubeTemplateDirective+ SelectOptionsComponent]})export class LogsComponent implements OnInit {diff --git a/client/src/app/+error-page/error-page.component.ts b/client/src/app/+error-page/error-page.component.tsindex b44a6c4153..2a66dd660b 100644--- a/client/src/app/+error-page/error-page.component.ts+++ b/client/src/app/+error-page/error-page.component.ts@@ -18,6 +18,7 @@ export class ErrorPageComponent implements OnInit {type: 'video' | 'other' = 'other'public constructor () {+ // Keep this in constructor so we getCurrentNavigation() doesn't return nullconst state = this.router.getCurrentNavigation()?.extras.statethis.type = state?.type || this.typethis.status = state?.obj.status || this.statusdiff --git a/client/src/app/+manage/routes.ts b/client/src/app/+manage/routes.tsdeleted file mode 100644index 890452d41b..0000000000--- a/client/src/app/+manage/routes.ts+++ /dev/null@@ -1,27 +0,0 @@-import { Routes } from '@angular/router'-import { VideoChannelCreateComponent } from '@app/shared/standalone-channels/video-channel-create.component'-import { VideoChannelUpdateComponent } from '@app/shared/standalone-channels/video-channel-update.component'--// Keep these routes to have a non "/my-library" URL to manage video channels-// This can be useful for admins/moderators for example--export default [- {- path: 'create',- component: VideoChannelCreateComponent,- data: {- meta: {- title: $localize`Create a new video channel`- }- }- },- {- path: 'update/:videoChannelName',- component: VideoChannelUpdateComponent,- data: {- meta: {- title: $localize`Update video channel`- }- }- }-] satisfies Routesdiff --git a/client/src/app/+my-account/my-account-import-export/my-account-export.component.html b/client/src/app/+my-account/my-account-import-export/my-account-export.component.htmlindex 703fabfcce..cce5ebe551 100644--- a/client/src/app/+my-account/my-account-import-export/my-account-export.component.html+++ b/client/src/app/+my-account/my-account-import-export/my-account-export.component.html@@ -30,6 +30,7 @@<li i18n>A directory containing static files (thumbnails, avatars, video files etc.)</li></ul>+ <p i18n>Videos and playlists from collaborated channels, as well as your channel collaborators, <strong>will not</strong> be included in the archive.</p><p i18n>You can only request one archive at a time.</p>@if (isEmailEnabled()) {diff --git a/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.ts b/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.tsindex 8059fe766c..b113282232 100644--- a/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.ts+++ b/client/src/app/+my-account/my-account-notifications/my-account-notifications.component.ts@@ -32,7 +32,7 @@ export class MyAccountNotificationsComponent {}hasUnreadNotifications () {- return this.userNotification().notifications.filter(n => n.read === false).length !== 0+ return this.userNotification().notifications.filter(n => n.payload.read === false).length !== 0}onChangeSortColumn () {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.htmlnew file mode 100644index 0000000000..08a2b417b3--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.html@@ -0,0 +1,126 @@+<h2 class="form-title">+ <my-global-icon iconName="cog"></my-global-icon>++ <ng-container i18n>General</ng-container>+</h2>++<form id="channel-manage-form" [formGroup]="form">+ <div class="pt-two-cols">+ <div class="title-col">+ <h3 i18n>IMAGES</h3>+ </div>++ <div class="content-col">+ <my-actor-banner-edit+ previewImage="true"+ class="d-block mb-4"+ [bannerUrl]="videoChannelEdit.apiInfo.bannerUrl"+ (bannerChange)="onBannerChange($event)"+ (bannerDelete)="onBannerDelete()"+ ></my-actor-banner-edit>++ <my-actor-avatar-edit+ class="d-block mb-4"+ actorType="channel"+ previewImage="true"+ [avatars]="videoChannelEdit.apiInfo.avatars"+ [username]="mode === 'update' && videoChannelEdit.channel.name"+ [subscribers]="mode === 'update' && videoChannelEdit.apiInfo.followersCount"+ (avatarChange)="onAvatarChange($event)"+ (avatarDelete)="onAvatarDelete()"+ ></my-actor-avatar-edit>+ </div>+ </div>++ <div class="pt-two-cols">+ <div class="title-col">+ <h3 i18n>INFORMATION</h3>+ </div>++ <div class="content-col">+ <div class="form-group" [hidden]="mode !== 'create'">+ <label i18n for="name">Name</label>++ <div class="input-group">+ <input+ type="text"+ id="name"+ i18n-placeholder+ placeholder="Example: my_channel"+ formControlName="name"+ [ngClass]="{ 'input-error': formErrors.name }"+ class="form-control w-auto flex-grow-1 d-block"+ >+ <div class="input-group-text">@{{ instanceHost }}</div>+ </div>++ <div *ngIf="formErrors.name" class="form-error" role="alert">{{ formErrors.name }}</div>+ </div>++ <div class="form-group">+ <label i18n for="displayName">Display name</label>+ <input type="text" id="displayName" class="form-control" formControlName="displayName" [ngClass]="{ 'input-error': formErrors.displayName }">+ <div *ngIf="formErrors.displayName" class="form-error" role="alert">+ {{ formErrors.displayName }}+ </div>+ </div>++ <div class="form-group markdown-block">+ <label i18n for="description">Description</label>++ <my-help helpType="markdownText" supportRelMe="true"></my-help>++ <my-markdown-textarea+ inputId="description"+ formControlName="description"+ markdownType="enhanced"+ [formError]="formErrors.description"+ withEmoji="true"+ withHtml="true"+ ></my-markdown-textarea>+ </div>++ <div class="form-group markdown-block">+ <label i18n for="support">Support</label>++ <div class="form-group-description" i18n>+ This is text that helps people visiting your channel page <strong>understand how to support you</strong>. You can use <my-markdown-hint+ helpType="markdownText"+ >Markdown Language</my-markdown-hint>, including <strong>links to your fundraising tools</strong>.+ </div>++ <my-markdown-textarea+ inputId="support"+ formControlName="support"+ markdownType="enhanced"+ [formError]="formErrors.support"+ withEmoji="true"+ withHtml="true"+ ></my-markdown-textarea>+ </div>++ <div class="form-group" *ngIf="isBulkUpdateVideosDisplayed()">+ <my-peertube-checkbox+ inputName="bulkVideosSupportUpdate"+ formControlName="bulkVideosSupportUpdate"+ i18n-labelText+ labelText="Overwrite support field of all videos of this channel"+ ></my-peertube-checkbox>+ </div>+ </div>+ </div>++ <div class="pt-two-cols">+ <div class="title-col">+ <h3 i18n>VIDEOS</h3>+ </div>++ <div class="content-col">+ <div class="form-group">+ <label i18n for="playerTheme">Player Theme</label>++ <my-select-player-theme formControlName="playerTheme" inputId="playerTheme" mode="channel"> </my-select-player-theme>+ </div>+ </div>+ </div>+</form>diff --git a/client/src/app/shared/standalone-channels/video-channel-edit.component.scss b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.scsssimilarity index 100%rename from client/src/app/shared/standalone-channels/video-channel-edit.component.scssrename to client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.scssdiff --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.tsnew file mode 100644index 0000000000..3ea913fe44--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-edit-general.component.ts@@ -0,0 +1,187 @@+import { CommonModule } from '@angular/common'+import { Component, inject, OnInit } from '@angular/core'+import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'+import {+ BuildFormArgumentTyped,+ FormReactiveErrorsTyped,+ FormReactiveMessagesTyped+} from '@app/shared/form-validators/form-validator.model'+import {+ VIDEO_CHANNEL_DESCRIPTION_VALIDATOR,+ VIDEO_CHANNEL_DISPLAY_NAME_VALIDATOR,+ VIDEO_CHANNEL_NAME_VALIDATOR,+ VIDEO_CHANNEL_SUPPORT_VALIDATOR+} 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 { 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 { HelpComponent } from '@app/shared/shared-main/buttons/help.component'+import { MarkdownHintComponent } from '@app/shared/shared-main/text/markdown-hint.component'+import { 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'++type Form = {+ name: FormControl<string>+ displayName: FormControl<string>+ description: FormControl<string>+ support: FormControl<string>+ playerTheme: FormControl<PlayerChannelSettings['theme']>+ bulkVideosSupportUpdate: FormControl<boolean>+}++@Component({+ selector: 'my-video-channel-edit-general',+ templateUrl: './video-channel-edit-general.component.html',+ styleUrls: [ './video-channel-edit-general.component.scss' ],+ imports: [+ CommonModule,+ FormsModule,+ ReactiveFormsModule,+ ActorBannerEditComponent,+ ActorAvatarEditComponent,+ HelpComponent,+ MarkdownTextareaComponent,+ PeertubeCheckboxComponent,+ MarkdownHintComponent,+ SelectPlayerThemeComponent,+ GlobalIconComponent+ ]+})+export class VideoChannelEditGeneralComponent implements OnInit {+ private formReactiveService = inject(FormReactiveService)+ private editController = inject(VideoChannelEditControllerService)++ form: FormGroup<Form>+ formErrors: FormReactiveErrorsTyped<Form> = {}+ validationMessages: FormReactiveMessagesTyped<Form> = {}+ mode: EditMode+ videoChannelEdit: VideoChannelEdit++ private formSub: Subscription++ get instanceHost () {+ return window.location.host+ }++ ngOnInit () {+ this.mode = this.editController.getMode()++ this.videoChannelEdit = this.editController.getStore()+ this.buildForm()++ this.editController.getStoreChangesObs()+ .subscribe(() => {+ this.videoChannelEdit = this.editController.getStore()++ this.buildForm()+ })++ this.editController.registerSaveHook(() => {+ this.formReactiveService.forceCheck(this.form, this.formErrors, this.validationMessages)++ this.editController.setFormError($localize`General`, 'general', this.formErrors)+ })+ }++ private buildForm () {+ this.formSub?.unsubscribe()++ const obj: BuildFormArgumentTyped<Form> = {+ name: this.mode === 'create'+ ? VIDEO_CHANNEL_NAME_VALIDATOR+ : null,++ displayName: VIDEO_CHANNEL_DISPLAY_NAME_VALIDATOR,+ description: VIDEO_CHANNEL_DESCRIPTION_VALIDATOR,+ support: VIDEO_CHANNEL_SUPPORT_VALIDATOR,+ bulkVideosSupportUpdate: null,+ playerTheme: null+ }++ const defaultValues = {+ name: this.videoChannelEdit.channel.name,+ displayName: this.videoChannelEdit.channel.displayName,+ description: this.videoChannelEdit.channel.description,+ support: this.videoChannelEdit.channel.support,+ playerTheme: this.videoChannelEdit.playerSettings.theme+ }++ const {+ form,+ formErrors,+ validationMessages+ } = this.formReactiveService.buildForm<Form>(obj, defaultValues)++ this.form = form+ this.formErrors = formErrors+ this.validationMessages = validationMessages++ this.subscribeToFormChanges()+ }++ getFormButtonTitle () {+ if (this.mode === 'update') {+ return $localize`Manage ${this.videoChannelEdit.channel.displayName}`+ }++ return $localize`Create your channel`+ }++ // ---------------------------------------------------------------------------++ onAvatarChange (formData: FormData) {+ this.videoChannelEdit.updateAvatarFromGeneralForm(formData)+ }++ onAvatarDelete () {+ this.videoChannelEdit.updateAvatarFromGeneralForm(null)+ }++ onBannerChange (formData: FormData) {+ this.videoChannelEdit.updateBannerFromGeneralForm(formData)+ }++ onBannerDelete () {+ this.videoChannelEdit.updateBannerFromGeneralForm(null)+ }++ // ---------------------------------------------------------------------------++ isBulkUpdateVideosDisplayed () {+ if (this.mode === 'create') return false++ if (this.videoChannelEdit.apiInfo.support === undefined) return false++ return this.videoChannelEdit.apiInfo.support !== this.form.value.support+ }++ subscribeToFormChanges () {+ this.formSub = this.form.valueChanges.subscribe(body => {+ // Reset form errors, we'll re-check them on save+ this.editController.setFormError($localize`General`, 'general', {})++ this.videoChannelEdit.loadFromGeneralForm({+ playerSettings: {+ theme: body.playerTheme+ },++ channel: {+ name: body.name,+ displayName: body.displayName,+ description: body.description || null,+ support: body.support || null,++ bulkVideosSupportUpdate: this.mode === 'update'+ ? body.bulkVideosSupportUpdate || false+ : undefined+ }+ })+ })+ }+}diff --git a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.html b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.htmlnew file mode 100644index 0000000000..b56f1106b2--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.html@@ -0,0 +1,102 @@+<div>+ <h2 class="form-title">+ <my-global-icon iconName="users"></my-global-icon>++ <ng-container i18n>Editors</ng-container>+ </h2>++ <div class="pt-two-cols">+ <div class="title-col">+ <h3 i18n>OWNER</h3>+ </div>++ <div class="content-col">+ <h4 i18>Current owner</h4>++ <div class="collaborator-block">+ <my-actor-avatar [actor]="getOwnerAccount()" actorType="account" size="60"></my-actor-avatar>++ <div>+ <div class="collaborator-display-name mb-1">+ <span class="fw-bold">{{ getOwnerDisplayName() }}</span>++ @if (isOwner()) {+ <span class="d-inline-block ms-1" i18n>(you)</span>+ }+ </div>++ <my-collaborator-state type="owner"></my-collaborator-state>+ </div>+ </div>+ </div>+ </div>++ <div class="pt-two-cols mt-4">+ <div class="title-col">+ <h3 i18n>EDITORS</h3>+ </div>++ <div class="content-col">+ <p i18n>Editors <strong>can:</strong></p>++ <ul>+ <li i18n>Publish videos in this channel</li>+ <li i18n>Manage, update or delete videos, comments, playlists of this channel</li>+ <li i18n>Add or delete channel synchronization</li>+ <li i18n>Update information of this channel (title, description, banner...)</li>+ </ul>++ <p i18n>But editors <strong>cannot:</strong></p>++ <ul>+ <li i18n>Delete the channel</li>+ <li i18n>Add or remove other editors</li>+ </ul>++ <h4 i18n>Current editors</h4>++ <div class="collaborators">+ @for (collaborator of videoChannelEdit.collaborators; track collaborator.id) {+ <div class="collaborator-block">+ <my-actor-avatar [actor]="collaborator.account" actorType="account" size="60"></my-actor-avatar>++ <div>+ <div class="collaborator-display-name fw-bold mb-1" i18>{{ collaborator.account.displayName }}</div>++ <div class="d-flex gap-1">+ <my-collaborator-state [type]="getCollaboratorState(collaborator)"></my-collaborator-state>++ @if (isOwner() || isCollaborator(collaborator)) {+ <my-action-dropdown+ container="body"+ buttonStyled="false"+ buttonIcon="chevron-down"+ buttonSize="small"+ [actions]="collaboratorActions"+ [entry]="collaborator"+ ></my-action-dropdown>+ }+ </div>+ </div>+ </div>+ } @empty {+ <div i18n>No editors at the moment</div>+ }+ </div>++ @if (isOwner()) {+ <div class="mt-4">+ <h4 i18n>New editor</h4>++ <label for="addEditor" i18n>Editor handle</label>++ <div class="d-flex flex-wrap gap-3">+ <my-user-auto-complete inputName="addEditor" [(ngModel)]="newEditorUsername"></my-user-auto-complete>++ <my-button theme="secondary" (click)="addEditor()" i18n [disabled]="!newEditorUsername">Invite</my-button>+ </div>+ </div>+ }+ </div>+ </div>+</div>diff --git a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.scss b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.scssnew file mode 100644index 0000000000..4ae9ea0b54--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.scss@@ -0,0 +1,41 @@+@use "_variables" as *;+@use "_mixins" as *;++h4 {+ margin-bottom: 1rem;+ font-weight: $font-bold;+ color: pvar(--fg-300);++ @include font-size(20px);+}++.collaborators {+ display: flex;+ gap: 1rem;+ flex-wrap: wrap;+}++.collaborator-block {+ display: inline-block;+ padding: 0.5rem 1rem;+ background: pvar(--bg-secondary-400);+ gap: 10px;+ display: flex;+ align-items: center;+ width: fit-content;+ border-radius: 16px;++ my-actor-avatar {+ display: block;+ }+}++my-user-auto-complete {+ display: block;++ @include responsive-width(450px);+}++my-action-dropdown {+ color: pvar(--fg-200);+}diff --git a/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.ts b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.tsnew file mode 100644index 0000000000..a924cd0bd3--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/pages/video-channel-editors.component.ts@@ -0,0 +1,138 @@+import { CommonModule } from '@angular/common'+import { Component, inject, OnInit } from '@angular/core'+import { FormsModule, ReactiveFormsModule } from '@angular/forms'+import { Router } from '@angular/router'+import { AuthService, ConfirmService, Notifier } from '@app/core'+import { ActorAvatarComponent } from '@app/shared/shared-actor-image/actor-avatar.component'+import { UserAutoCompleteComponent } from '@app/shared/shared-forms/user-auto-complete.component'+import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'+import { ActionDropdownComponent, DropdownAction } from '@app/shared/shared-main/buttons/action-dropdown.component'+import { ButtonComponent } from '@app/shared/shared-main/buttons/button.component'+import { CollaboratorStateComponent } from '@app/shared/shared-main/channel/collaborator-state.component'+import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'+import { VideoChannelCollaborator, VideoChannelCollaboratorState } from '@peertube/peertube-models'+import { logger } from '@root-helpers/logger'+import { VideoChannelEditControllerService } from '../video-channel-edit-controller.service'+import { VideoChannelEdit } from '../video-channel-edit.model'++@Component({+ selector: 'my-video-channel-editors',+ templateUrl: './video-channel-editors.component.html',+ styleUrls: [ './video-channel-editors.component.scss' ],+ imports: [+ CommonModule,+ FormsModule,+ ReactiveFormsModule,+ ActorAvatarComponent,+ ButtonComponent,+ ActionDropdownComponent,+ UserAutoCompleteComponent,+ GlobalIconComponent,+ CollaboratorStateComponent+ ]+})+export class VideoChannelEditEditorsComponent implements OnInit {+ private confirmService = inject(ConfirmService)+ private notifier = inject(Notifier)+ private channelService = inject(VideoChannelService)+ private editController = inject(VideoChannelEditControllerService)+ private authService = inject(AuthService)+ private router = inject(Router)++ videoChannelEdit: VideoChannelEdit++ newEditorUsername: string+ collaboratorActions: DropdownAction<VideoChannelCollaborator>[] = []++ ngOnInit () {+ this.videoChannelEdit = this.editController.getStore()++ this.buildActions()+ }++ private buildActions () {+ this.collaboratorActions = [+ {+ label: $localize`Delete`,+ iconName: 'delete',+ handler: async collaborator => {+ const message = collaborator.state.id === VideoChannelCollaboratorState.PENDING+ // eslint-disable-next-line max-len+ ? $localize`Are you sure you want to remove invitation of <strong>${collaborator.account.displayName}</strong> to collaborate on your channel?`+ : $localize`Are you sure you want to remove <strong>${collaborator.account.displayName}</strong> as a collaborator?`++ const res = await this.confirmService.confirm(+ message,+ $localize`Remove collaborator`+ )+ if (!res) return++ this.channelService.removeCollaborator(this.videoChannelEdit.channel.name, collaborator.id)+ .subscribe({+ next: () => {+ this.videoChannelEdit.collaborators = this.videoChannelEdit.collaborators.filter(c => c.id !== collaborator.id)++ if (this.isCollaborator(collaborator)) {+ this.notifier.success(+ $localize`You have been removed as a collaborator from ${this.videoChannelEdit.channel.name} channel`+ )++ this.router.navigate([ '/my-library', 'video-channels' ])+ }+ },++ error: err => this.notifier.error(err.message)+ })+ }+ }+ ]+ }++ // ---------------------------------------------------------------------------++ getOwnerAccount () {+ return this.videoChannelEdit.apiInfo.ownerAccount+ }++ getOwnerDisplayName () {+ return this.getOwnerAccount().displayName+ }++ isOwner () {+ return this.getOwnerAccount().id === this.authService.getUser().account.id+ }++ isCollaborator (collaborator: VideoChannelCollaborator) {+ return collaborator.account.id === this.authService.getUser().account.id+ }++ getCollaboratorState (collaborator: VideoChannelCollaborator) {+ if (collaborator.state.id === VideoChannelCollaboratorState.ACCEPTED) return 'accepted' as const+ if (collaborator.state.id === VideoChannelCollaboratorState.PENDING) return 'invited' as const++ logger.error('Cannot find collaborator state for ' + collaborator.state.id)++ return undefined+ }++ // ---------------------------------------------------------------------------++ async addEditor () {+ const message =+ // eslint-disable-next-line max-len+ $localize`Do you want to send an invitation to <strong>${this.newEditorUsername}</strong> to collaborate on <strong>${this.videoChannelEdit.channel.name}</strong>?`++ const res = await this.confirmService.confirm(message, $localize`Invite new editor`)+ if (!res) return++ this.channelService.inviteCollaborator(this.videoChannelEdit.channel.name, this.newEditorUsername)+ .subscribe({+ next: collaborator => {+ this.videoChannelEdit.collaborators.push(collaborator)+ this.newEditorUsername = ''+ },++ error: err => this.notifier.error(err.message)+ })+ }+}diff --git a/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit-controller.service.ts b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit-controller.service.tsnew file mode 100644index 0000000000..a22e448a0f--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit-controller.service.ts@@ -0,0 +1,94 @@+import { inject, Injectable } from '@angular/core'+import { FormReactiveErrors } from '@app/shared/form-validators/form-validator.model'+import { FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'+import { VideoChannelEdit } from './video-channel-edit.model'+import { Subject } from 'rxjs'++export type EditMode = 'create' | 'update'++@Injectable()+export class VideoChannelEditControllerService {+ private formReactiveService = inject(FormReactiveService)++ private error = ''+ private videoChannelEdit: VideoChannelEdit+ private mode: EditMode++ private formErrors: { page: string, path: string, errors: string[] }[] = []+ private saveHook: () => Promise<any>++ private readonly storeChanges = new Subject<void>()++ setStore (videoChannelEdit: VideoChannelEdit) {+ this.videoChannelEdit = videoChannelEdit++ this.storeChanges.next()+ }++ getStore () {+ return this.videoChannelEdit+ }++ getStoreChangesObs () {+ return this.storeChanges.asObservable()+ }++ // ---------------------------------------------------------------------------++ getMode () {+ return this.mode+ }++ setMode (mode: EditMode) {+ this.mode = mode+ }++ // ---------------------------------------------------------------------------++ setError (error: string) {+ this.error = error+ }++ resetError () {+ this.setError('')+ }++ getError () {+ return this.error+ }++ // ---------------------------------------------------------------------------++ setFormError (page: string, path: string, formErrors: FormReactiveErrors) {+ const errors = this.formReactiveService.grabAllErrors(formErrors)+ this.formErrors = this.formErrors.filter(e => e.page !== page)++ if (errors.length === 0) return++ this.formErrors.push({ page, path, errors })+ }++ getFormErrors () {+ return this.formErrors+ }++ hasFormErrors () {+ return this.formErrors.some(({ errors }) => errors.length !== 0)+ }++ // ---------------------------------------------------------------------------++ registerSaveHook (fn: () => Promise<any> | any) {+ this.saveHook = fn+ }++ unregisterSaveHook () {+ this.saveHook = undefined+ }++ runSaveHook () {+ if (!this.saveHook) return Promise.resolve()++ return this.saveHook()+ }+}diff --git a/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.html b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.htmlnew file mode 100644index 0000000000..43d23ce8ac--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.html@@ -0,0 +1,85 @@+<div class="d-flex">+ <div>+ <my-lateral-menu [config]="menuConfig"></my-lateral-menu>+ </div>++ <div class="w-100 min-width-0">+ <div class="actions-container">+ <div class="actions header-block">+ <my-button class="cancel-button" icon="arrow-left" theme="secondary" i18n [ptRouterLink]="cancelLink()">Cancel</my-button>+++ @if (mode === 'update') {+ <h2>+ <my-action-dropdown+ [label]="videoChannelEdit()?.channel.displayName"+ container="body"+ buttonStyled="false"+ buttonIcon="chevron-down"+ [actions]="switchChannelActions"+ >+ <ng-template #labelExtra>+ @if (user.isEditorOfChannel(videoChannelEdit().apiInfo)) {+ <my-collaborator-state class="d-inline-flex" type="accepted"></my-collaborator-state>+ }++ </ng-template>++ <ng-template #dropdownItemExtra let-action="action">+ @if (action.data.editor) {+ <my-collaborator-state class="d-inline-flex ms-2" small="true" type="accepted"></my-collaborator-state>+ }+ </ng-template>+ </my-action-dropdown>+ </h2>+ } @else {+ <h2 i18n>Create a new channel</h2>+ }++ <div class="go-public-page-save">+ @if (videoChannelEdit()?.apiInfo.id) {+ <my-button class="go-public-page" icon="external-link" theme="secondary" [href]="getChannelPublicUrl()">+ <span i18n class="go-public-page-label">Go to the public page</span>+ </my-button>+ }++ <my-button+ theme="primary" class="save-button"+ icon="circle-tick"+ [disabled]="!canUpdate()" (click)="onSaveClick()"+ form="channel-manage-form"+ i18n+ >+ Save+ </my-button>+ </div>+ </div>++ @if (getError()) {+ <my-alert type="danger" class="d-block mt-2">+ {{ getError() }}+ </my-alert>+ } @else if (displayFormErrorsMsg && hasFormErrors()) {+ <my-alert type="warning" class="d-block mt-2">+ <div i18n>There are errors in your channel settings.</div>++ @for (errorRoot of getAllFormErrors(); track errorRoot) {+ <div class="mt-3">+ <a i18n class="alert-link" [routerLink]="errorRoot.path">{{ errorRoot.page }} page</a>++ <ul class="mb-0">+ @for (error of errorRoot.errors; track error) {+ <li>{{ error }}</li>+ }+ </ul>+ </div>+ }+ </my-alert>+ }+ </div>++ <div class="mt-3">+ <router-outlet></router-outlet>+ </div>+ </div>+</div>diff --git a/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.scss b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.scssnew file mode 100644index 0000000000..b147252094--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.scss@@ -0,0 +1,69 @@+@use "_variables" as *;+@use "_mixins" as *;+@use "_form-mixins" as *;++.header-block {+ border-radius: 14px;+ background-color: pvar(--bg-secondary-350);+}++h2 {+ color: pvar(--fg-300);++ @include font-size(22px);+}++.actions-container {+ position: sticky;+ top: pvar(--header-height);+ background-color: pvar(--bg);+ // On top of input group addons+ z-index: 6;+}++.actions {+ display: flex;+ justify-content: space-between;+ gap: 1rem;+ padding: 1.5rem;++ h2 {+ flex-shrink: 1;+ color: pvar(--fg-350);+ font-weight: $font-bold;+ margin-bottom: 0;+ line-height: normal;++ @include font-size(1.5rem);+ @include ellipsis;+ }++ .go-public-page-save {+ display: flex;+ gap: 1rem;+ }++ @media screen and (max-width: 1200px) {+ flex-direction: column;+ text-align: center;++ .cancel-button {+ display: none;+ }++ .go-public-page-save {+ justify-content: center;+ }+ }++ @include on-small-main-col {+ .watch-button-label {+ display: none;+ }+ }++ @include on-mobile-main-col {+ padding: 0.5rem;+ gap: 0.5rem;+ }+}diff --git a/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.ts b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.tsnew file mode 100644index 0000000000..65265f20c2--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.component.ts@@ -0,0 +1,164 @@+import { CommonModule } from '@angular/common'+import { Component, inject, input, OnDestroy, OnInit } from '@angular/core'+import { FormsModule, ReactiveFormsModule } from '@angular/forms'+import { RouterModule, RouterOutlet } from '@angular/router'+import { AuthService } from '@app/core'+import { ActionDropdownComponent, DropdownAction } from '@app/shared/shared-main/buttons/action-dropdown.component'+import { ButtonComponent } from '@app/shared/shared-main/buttons/button.component'+import { CollaboratorStateComponent } from '@app/shared/shared-main/channel/collaborator-state.component'+import { AlertComponent } from '@app/shared/shared-main/common/alert.component'+import { HorizontalMenuService } from '@app/shared/shared-main/menu/horizontal-menu.service'+import { VideoChannel } from '@peertube/peertube-models'+import { LateralMenuComponent, LateralMenuConfig } from '../../../shared/shared-main/menu/lateral-menu.component'+import { EditMode, VideoChannelEditControllerService } from './video-channel-edit-controller.service'+import { VideoChannelEdit } from './video-channel-edit.model'++@Component({+ selector: 'my-video-channel-edit',+ templateUrl: './video-channel-edit.component.html',+ styleUrls: [ './video-channel-edit.component.scss' ],+ imports: [+ CommonModule,+ FormsModule,+ ReactiveFormsModule,+ LateralMenuComponent,+ RouterOutlet,+ ButtonComponent,+ AlertComponent,+ RouterModule,+ ActionDropdownComponent,+ CollaboratorStateComponent+ ]+})+export class VideoChannelEditComponent implements OnInit, OnDestroy {+ private authService = inject(AuthService)+ private horizontalMenuService = inject(HorizontalMenuService)++ readonly videoChannelEdit = input.required<VideoChannelEdit>()+ readonly saveFn = input.required<() => Promise<any>>()++ private editControllerService = inject(VideoChannelEditControllerService)++ mode: EditMode+ menuConfig: LateralMenuConfig+ displayFormErrorsMsg = false++ switchChannelActions: DropdownAction<void, { editor: boolean }>[] = []++ private isSaving = false++ get user () {+ return this.authService.getUser()+ }++ ngOnInit () {+ this.mode = this.editControllerService.getMode()++ this.menuConfig = {+ title: this.mode === 'create'+ ? $localize`Create channel`+ : $localize`Manage my channel`,++ entries: [+ {+ type: 'link',+ icon: 'channel',+ label: $localize`General`,+ routerLink: 'general'+ },+ {+ type: 'link',+ icon: 'users',+ label: $localize`Editors`,+ routerLink: 'editors',+ isDisplayed: () => this.mode === 'update'+ }+ ]+ }++ this.buildSwitchChannelActions()++ this.editControllerService.setStore(this.videoChannelEdit())++ this.horizontalMenuService.setMenuHidden(true)+ }++ ngOnDestroy () {+ this.horizontalMenuService.setMenuHidden(false)+ }++ private buildSwitchChannelActions () {+ const user = this.authService.getUser()++ const builder = (c: VideoChannel, { editor }: { editor: boolean }) => ({+ label: c.displayName,+ linkBuilder: () => {+ const current = this.videoChannelEdit().channel.name++ const suffix = window.location.pathname.replace(`/my-library/video-channels/manage/${current}/`, '')++ return [ '/my-library/video-channels/manage', c.name, suffix ]+ },+ actorAvatar: {+ actor: c,+ type: 'channel' as const+ },++ data: {+ editor+ }+ })++ this.switchChannelActions = [+ ...user.videoChannels.map(c => builder(c, { editor: false })),+ ...user.videoChannelCollaborations.map(c => builder(c, { editor: true }))+ ]+ }++ // ---------------------------------------------------------------------------++ getError () {+ return this.editControllerService.getError()+ }++ getAllFormErrors () {+ return this.editControllerService.getFormErrors()+ }+ // ---------------------------------------------------------------------------++ getChannelPublicUrl () {+ return '/c/' + this.videoChannelEdit().channel.name+ }++ cancelLink () {+ return '/my-library/video-channels'+ }++ canUpdate () {+ return this.videoChannelEdit().hasChanges() && !this.editControllerService.hasFormErrors()+ }++ hasFormErrors () {+ return this.editControllerService.hasFormErrors()+ }++ async onSaveClick () {+ this.displayFormErrorsMsg = false++ await this.editControllerService.runSaveHook()++ if (this.hasFormErrors()) {+ this.displayFormErrorsMsg = true+ return+ }++ if (this.isSaving) return+ this.isSaving = true++ try {+ await this.saveFn()()+ } finally {+ this.isSaving = false+ }+ }+}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.tsnew file mode 100644index 0000000000..a02998a7dc--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.model.ts@@ -0,0 +1,160 @@+import { AuthUser } from '@app/core'+import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'+import { AccountSummary, ActorImage, PlayerChannelSettings, VideoChannelCollaborator } from '@peertube/peertube-models'++type GeneralFormValue = {+ playerSettings: {+ theme: PlayerChannelSettings['theme']+ }++ channel: {+ name: string+ displayName: string+ description: string+ support: string+ bulkVideosSupportUpdate: boolean+ }+}++export class VideoChannelEdit {+ avatar: FormData+ banner: FormData++ playerSettings: {+ theme: PlayerChannelSettings['theme']+ }++ channel: {+ name: string+ displayName: string+ description: string+ support: string+ bulkVideosSupportUpdate: boolean+ }++ collaborators: VideoChannelCollaborator[]++ apiInfo: {+ id: number+ ownerAccount: AccountSummary+ avatars: VideoChannel['avatars']+ followersCount: VideoChannel['followersCount']+ bannerUrl: string+ support: string+ }++ commonChanged = false+ avatarChanged = false+ bannerChanged = false++ loadFromCreate (options: {+ playerSettings: PlayerChannelSettings+ user: AuthUser+ }) {+ const { playerSettings, user } = options++ this.playerSettings = {+ theme: playerSettings.theme+ }++ this.channel = {+ name: '',+ displayName: '',+ description: '',+ support: '',+ bulkVideosSupportUpdate: false+ }++ this.apiInfo = {+ id: undefined,+ ownerAccount: user.account,+ avatars: [],+ followersCount: 0,+ bannerUrl: undefined,+ support: undefined+ }++ this.collaborators = []+ }++ loadFromAPI (options: {+ channel: VideoChannel+ playerSettings: PlayerChannelSettings+ collaborators: VideoChannelCollaborator[]+ }) {+ const { channel, playerSettings, collaborators } = options++ this.playerSettings = {+ theme: playerSettings.theme+ }++ this.channel = {+ name: channel.name,+ displayName: channel.displayName,+ description: channel.description,+ support: channel.support,+ bulkVideosSupportUpdate: false+ }++ this.collaborators = [ ...collaborators ]++ this.apiInfo = {+ id: channel.id,+ avatars: channel.avatars,+ followersCount: channel.followersCount,+ bannerUrl: channel.bannerUrl,+ support: channel.support,+ ownerAccount: channel.ownerAccount+ }+ }++ hasChanges () {+ return this.commonChanged || this.avatarChanged || this.bannerChanged+ }++ resetChanges () {+ this.commonChanged = false+ this.avatarChanged = false+ this.bannerChanged = false++ this.apiInfo.support = this.channel.support+ }++ loadFromGeneralForm (form: GeneralFormValue) {+ this.playerSettings = form.playerSettings++ this.channel = {+ ...this.channel,+ ...form.channel+ }++ this.commonChanged = true+ }++ updateAvatarFromGeneralForm (formData: FormData) {+ this.avatar = formData+ this.avatarChanged = true+ }++ updateBannerFromGeneralForm (formData: FormData) {+ this.banner = formData+ this.bannerChanged = true+ }++ resetAvatarFromAPI () {+ this.avatar = null+ this.apiInfo.avatars = []+ }++ resetBannerFromAPI () {+ this.apiInfo.bannerUrl = null+ }++ updateAvatarsFromAPI (avatars: ActorImage[]) {+ this.apiInfo.avatars = avatars+ }++ updateBannerUrlFromAPI (bannerUrl: string) {+ this.apiInfo.bannerUrl = bannerUrl+ }+}diff --git a/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.routes.ts b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.routes.tsnew file mode 100644index 0000000000..35f4ebebc5--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/edit/video-channel-edit.routes.ts@@ -0,0 +1,29 @@+import { Routes } from '@angular/router'+import { VideoChannelEditGeneralComponent } from './pages/video-channel-edit-general.component'+import { VideoChannelEditEditorsComponent } from './pages/video-channel-editors.component'++export const videoChannelEditRoutes: Routes = [+ {+ path: '',+ redirectTo: 'general',+ pathMatch: 'full'+ },+ {+ path: 'general',+ component: VideoChannelEditGeneralComponent,+ data: {+ meta: {+ title: $localize`General channel configuration`+ }+ }+ },+ {+ path: 'editors',+ component: VideoChannelEditEditorsComponent,+ data: {+ meta: {+ title: $localize`Channel editors`+ }+ }+ }+]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 4c85429394..e5afb2b92c 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@@ -1,9 +1,17 @@<my-channels-setup-message [hideLink]="true"></my-channels-setup-message>-<div class="video-channels-header d-flex align-items-end gap-2 flex-wrap">+<div class="d-flex align-items-end gap-2 flex-wrap mb-4"><span *ngIf="pagination.totalItems" class="total-items">{{ getTotalTitle() }}</span>- <my-advanced-input-filter class="d-block ms-auto" (search)="onSearch($event)" emitOnInit="true"></my-advanced-input-filter>+ <my-advanced-input-filter class="d-block ms-auto" (search)="onSearch($event)" emitOnInit="true" i18n-placeholder placeholder="Search a channel"></my-advanced-input-filter>++ @if (user.isCollaboratingToChannels()) {+ <div class="d-flex align-items-center">+ <label class="label-inline" for="display-filter" i18n>Filter</label>++ <my-select-options inputId="display-filter" [items]="displayFilterItems" [(ngModel)]="displayFilter" (ngModelChange)="onDisplayFilterChanged()"></my-select-options>+ </div>+ }<a class="peertube-create-button" routerLink="/manage/create"><my-global-icon iconName="add" aria-hidden="true"></my-global-icon>@@ -11,34 +19,46 @@</a></div>-<div class="no-results" i18n *ngIf="this.pagination.totalItems === 0">No channel found.</div>--<div class="video-channels" myInfiniteScroller (nearOfBottom)="onNearOfBottom()" [dataObservable]="onChannelDataSubject.asObservable()">- <div *ngFor="let videoChannel of videoChannels; let i = index" class="video-channel">- <my-actor-avatar [actor]="videoChannel" actorType="channel" [internalHref]="[ '/c', videoChannel.nameWithHost ]" size="80"></my-actor-avatar>-- <div class="video-channel-info">- <a [routerLink]="[ '/c', videoChannel.nameWithHost ]" class="video-channel-names" i18n-title title="Channel page">- <div class="video-channel-display-name">{{ videoChannel.displayName }}</div>- <div class="video-channel-name">{{ videoChannel.nameWithHost }}</div>- </a>-- <a- i18n class="video-channel-followers"- [routerLink]="[ '/my-library', 'followers' ]" [queryParams]="{ search: 'channel:' + videoChannel.name }"- >- {videoChannel.followersCount, plural, =0 {No subscribers} =1 {1 subscriber} other {{{ videoChannel.followersCount }} subscribers}}- </a>-- <div class="channel-videos">- <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>- </div>+<div class="results-container">+ <div class="no-results" i18n *ngIf="this.pagination.totalItems === 0">No channel found.</div>++ <div class="video-channels" myInfiniteScroller (nearOfBottom)="onNearOfBottom()" [dataObservable]="onChannelDataSubject.asObservable()">+ <div *ngFor="let videoChannel of videoChannels; let i = index" class="channel">+ <div class="channel-info">+ <my-actor-avatar [actor]="videoChannel" actorType="channel" [internalHref]="[ '/c', videoChannel.nameWithHost ]" size="120"></my-actor-avatar>++ <div class="metadata">+ <div class="min-width-0 d-flex flex-wrap w-fit-content align-items-center">+ <a class="display-name" [routerLink]="[ '/c', videoChannel.nameWithHost ]" i18n-title title="Channel page">{{ videoChannel.displayName }}</a>++ @if (user.isCollaboratingToChannels() && user.isEditorOfChannel(videoChannel)) {+ <my-collaborator-state class="d-inline-block ms-2" type="accepted"></my-collaborator-state>+ }+ </div>- <div class="video-channel-buttons">- <my-edit-button label [ptRouterLink]="[ '/my-library/video-channels/update', videoChannel.nameWithHost ]"></my-edit-button>- <my-delete-button label (click)="deleteVideoChannel(videoChannel)"></my-delete-button>+ <span class="handle">{{ videoChannel.nameWithHost }}</span>++ <a+ i18n class="followers"+ [routerLink]="[ '/my-library', 'followers' ]" [queryParams]="{ search: 'channel:' + videoChannel.name }"+ >+ {videoChannel.followersCount, plural, =0 {No subscribers} =1 {1 subscriber} other {{{ videoChannel.followersCount }} subscribers}}+ </a>++ <div class="videos-info">+ <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>+ </div>+ </div>++ <div class="buttons">+ <my-edit-button i18n-label label="Manage" [ptRouterLink]="[ '/my-library/video-channels/manage', videoChannel.nameWithHost ]"></my-edit-button>++ @if (isOwned(videoChannel)) {+ <my-delete-button label (click)="deleteVideoChannel(videoChannel)"></my-delete-button>+ }+ </div></div><div *ngIf="!isInSmallView" class="w-100 d-flex justify-content-end chart-container">diff --git a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.scss b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.scssindex 4d4bf57184..e602139a44 100644--- a/client/src/app/+my-library/+my-video-channels/my-video-channels.component.scss+++ b/client/src/app/+my-library/+my-video-channels/my-video-channels.component.scss@@ -1,32 +1,31 @@-@use '_variables' as *;-@use '_mixins' as *;-@use '_form-mixins' as *;+@use "_variables" as *;+@use "_mixins" as *;+@use "_form-mixins" as *;-.sub-title my-global-icon {- position: relative;- top: -3px;+.results-container {+ min-height: 40vh;}-input[type=text] {+input[type="text"] {@include peertube-input-text(300px);}-my-edit-button {- @include margin-right(10px);+.channel {+ margin-bottom: 1.25rem;+ border-bottom: 1px solid pvar(--input-border-color);+ min-height: 130px;}-.video-channel {- padding-bottom: 0;-- @include row-blocks;-- my-actor-avatar {- @include margin-right(10px);- }+.channel-info {+ display: flex;+ gap: 1rem;}-.video-channel-info {- flex-grow: 1;+.metadata {+ display: flex;+ flex-direction: column;+ align-self: flex-start;+ min-width: 1px;}.video-channel-names {@@ -38,26 +37,33 @@ my-edit-button {@include disable-default-a-behaviour;}-.video-channel-display-name {+.display-name {font-weight: $font-semibold;- font-size: 18px;++ @include font-size(18px);}-.video-channel-name {- font-size: 14px;- color: pvar(--fg-300);+.handle,+.followers,+.videos-info {+ @include font-size(14px);+}- @include margin-left(5px);+.handle {+ color: pvar(--fg-300);+ margin-bottom: 0.5rem;}-.video-channel-followers {+.followers {color: pvar(--fg);- text-decoration: none;}-.video-channel-buttons {- margin-top: 10px;- min-width: 190px;+.buttons {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;++ @include margin-left(auto);}.chart-container {@@ -66,41 +72,23 @@ my-edit-button {height: 100px;}-.video-channels-header {- margin-bottom: 30px;-}-@media screen and (max-width: $small-view) {- .video-channel {- padding-bottom: 10px;-- img {- @include margin-right(0);- }-- .video-channel-buttons {- align-self: center;- }- }-- .video-channel-info {- padding-bottom: 10px;+ .channel-info {+ flex-direction: column;+ align-items: center;text-align: center;+ padding-bottom: 1rem;+ align-items: center;}- .video-channel-names {- flex-direction: column;- align-items: center !important;- margin: auto;+ .metadata {+ align-self: normal;+ align-items: center;}- .video-channel-name {- @include margin-left(0 !important);- }-}+ .buttons {+ text-align: center;-@media screen and (min-width: $small-view) {- .video-channel-buttons {- float: right;+ @include margin-left(0);}}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 e2f05315e1..dc0f0c65ba 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@@ -1,23 +1,28 @@-import { NgFor, NgIf } from '@angular/common'-import { Component, inject } from '@angular/core'-import { RouterLink } from '@angular/router'+import { CommonModule } from '@angular/common'+import { Component, OnInit, inject } from '@angular/core'+import { FormsModule } from '@angular/forms'+import { ActivatedRoute, RouterLink } from '@angular/router'import {AuthService,ComponentPagination,ConfirmService,Notifier,+ PeerTubeRouterService,ScreenService,hasMoreItems,resetCurrentPage,updatePaginationOnDelete} from '@app/core'import { formatICU } from '@app/helpers'+import { SelectOptionsComponent } from '@app/shared/shared-forms/select/select-options.component'+import { CollaboratorStateComponent } from '@app/shared/shared-main/channel/collaborator-state.component'import { 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 { ChartData, ChartOptions, TooltipItem, TooltipModel } from 'chart.js'import { ChartModule } from 'primeng/chart'-import { Subject, first, map, switchMap } from 'rxjs'+import { Subject, first, switchMap } from 'rxjs'+import { SelectOptionsItem } from 'src/types'import { ActorAvatarComponent } from '../../shared/shared-actor-image/actor-avatar.component'import { AdvancedInputFilterComponent } from '../../shared/shared-forms/advanced-input-filter.component'import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'@@ -29,32 +34,37 @@ import { InfiniteScrollerDirective } from '../../shared/shared-main/common/infinimport { NumberFormatterPipe } from '../../shared/shared-main/common/number-formatter.pipe'type CustomChartData = ChartData & { startDate: string, total: number }+type DisplayFilter = 'all' | 'owned'@Component({templateUrl: './my-video-channels.component.html',styleUrls: [ './my-video-channels.component.scss' ],imports: [GlobalIconComponent,- NgIf,+ CommonModule,+ FormsModule,RouterLink,ChannelsSetupMessageComponent,AdvancedInputFilterComponent,InfiniteScrollerDirective,- NgFor,ActorAvatarComponent,EditButtonComponent,DeleteButtonComponent,DeferLoadingDirective,ChartModule,- NumberFormatterPipe+ NumberFormatterPipe,+ SelectOptionsComponent,+ CollaboratorStateComponent]})-export class MyVideoChannelsComponent {+export class MyVideoChannelsComponent implements OnInit {private authService = inject(AuthService)private notifier = inject(Notifier)private confirmService = inject(ConfirmService)private videoChannelService = inject(VideoChannelService)private screenService = inject(ScreenService)+ private route = inject(ActivatedRoute)+ private peertubeRouter = inject(PeerTubeRouterService)videoChannels: VideoChannel[] = []@@ -72,15 +82,53 @@ export class MyVideoChannelsComponent {totalItems: null}+ displayFilter: DisplayFilter = 'all'+ displayFilterItems: SelectOptionsItem[] = [+ { id: 'all', label: $localize`All channels` },+ { id: 'owned', label: $localize`Only channels owned by me` }+ ]+private pagesDone = new Set<number>()get isInSmallView () {return this.screenService.isInSmallView()}+ get user () {+ return this.authService.getUser()+ }++ ngOnInit () {+ if (this.route.snapshot.queryParamMap.get('displayFilter') === 'owned') {+ this.displayFilter = 'owned'+ }+ }++ isOwned (channel: VideoChannel) {+ return channel.ownerAccount.id === this.authService.getUser().account.id+ }++ onDisplayFilterChanged () {+ this.peertubeRouter.silentNavigate([], {+ ...this.route.snapshot.queryParams,++ displayFilter: this.displayFilter === 'all'+ ? null+ : this.displayFilter+ })++ this.resetDataAndReload()+ }+onSearch (search: string) {this.search = search+ this.resetDataAndReload()+ }++ // ---------------------------------------------------------------------------++ private resetDataAndReload () {resetCurrentPage(this.pagination)this.videoChannels = []this.pagesDone.clear()@@ -103,7 +151,7 @@ export class MyVideoChannelsComponent {)if (res === false) return- this.videoChannelService.removeVideoChannel(videoChannel)+ this.videoChannelService.remove(videoChannel).subscribe({next: () => {this.videoChannels = this.videoChannels.filter(c => c.id !== videoChannel.id)@@ -131,45 +179,52 @@ export class MyVideoChannelsComponent {return this.authService.userInformationLoaded.pipe(first(),- map(() => ({- account: this.authService.getUser().account,- withStats: true,- search: this.search,- componentPagination: this.pagination,- sort: '-updatedAt'- })),- switchMap(options => this.videoChannelService.listAccountVideoChannels(options))- )- .subscribe(res => {- this.videoChannels = this.videoChannels.concat(res.data)- this.pagination.totalItems = res.total-- // chart data- this.videoChannelsChartData = this.videoChannels.map(v => ({- labels: v.viewsPerDay.map(day => day.date.toLocaleDateString()),- datasets: [- {- label: $localize`Views for the day`,- data: v.viewsPerDay.map(day => day.views),- fill: false,- borderColor: '#c6c6c6'- }- ],-- total: v.viewsPerDay.map(day => day.views)- .reduce((p, c) => p + c, 0),-- startDate: v.viewsPerDay.length !== 0- ? v.viewsPerDay[0].date.toLocaleDateString()- : ''- }))-- this.buildChartOptions()-- this.onChannelDataSubject.next(res.data)+ switchMap(() => {+ return this.videoChannelService.listAccountChannels({+ account: this.authService.getUser().account,+ withStats: true,+ search: this.search,+ componentPagination: this.pagination,+ includeCollaborations: this.displayFilter === 'all',+ sort: '-updatedAt'+ })+ })+ ).subscribe({+ next: res => {+ this.videoChannels = this.videoChannels.concat(res.data)+ this.pagination.totalItems = res.total++ // chart data+ this.videoChannelsChartData = this.videoChannels.map(v => ({+ labels: v.viewsPerDay.map(day => day.date.toLocaleDateString()),+ datasets: [+ {+ label: $localize`Views for the day`,+ data: v.viewsPerDay.map(day => day.views),+ fill: false,+ borderColor: '#c6c6c6'+ }+ ],++ total: v.viewsPerDay.map(day => day.views)+ .reduce((p, c) => p + c, 0),++ startDate: v.viewsPerDay.length !== 0+ ? v.viewsPerDay[0].date.toLocaleDateString()+ : ''+ }))++ this.buildChartOptions()++ this.onChannelDataSubject.next(res.data)+ },++ error: err => this.notifier.error(err.message)})}+ // ---------------------------------------------------------------------------+private buildChartOptions () {const channelsMinimumDailyViews = Math.min(...this.videoChannels.map(v => minBy(v.viewsPerDay, 'views').views))const channelsMaximumDailyViews = Math.max(...this.videoChannels.map(v => maxBy(v.viewsPerDay, 'views').views))@@ -229,6 +284,8 @@ export class MyVideoChannelsComponent {return formatICU($localize`${data.total} {value, plural, =1 {view} other {views}} since ${data.startDate}`, { value: data.total })}+ // ---------------------------------------------------------------------------+getTotalTitle () {return formatICU($localize`${this.pagination.totalItems} {total, plural, =1 {channel} other {channels}}`,diff --git a/client/src/app/+my-library/+my-video-channels/routes.ts b/client/src/app/+my-library/+my-video-channels/routes.tsindex 9c02f9f71b..9bed471fa2 100644--- a/client/src/app/+my-library/+my-video-channels/routes.ts+++ b/client/src/app/+my-library/+my-video-channels/routes.ts@@ -1,8 +1,49 @@-import { Routes } from '@angular/router'-import { VideoChannelCreateComponent } from '@app/shared/standalone-channels/video-channel-create.component'-import { VideoChannelUpdateComponent } from '@app/shared/standalone-channels/video-channel-update.component'+import { inject } from '@angular/core'+import { ActivatedRouteSnapshot, ResolveFn, Router, RouterStateSnapshot, Routes } from '@angular/router'+import { VideoChannelCreateComponent } from '@app/+my-library/+my-video-channels/video-channel-create.component'+import { VideoChannelManageComponent } from '@app/+my-library/+my-video-channels/video-channel-manage.component'+import { CanDeactivateGuard } from '@app/core'+import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'+import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'+import { PlayerSettingsService } from '@app/shared/shared-video/player-settings.service'+import { PlayerChannelSettings, VideoChannelCollaborator } from '@peertube/peertube-models'+import { logger } from '@root-helpers/logger'+import { catchError, forkJoin, map, throwError } from 'rxjs'+import { VideoChannelEditControllerService } from './edit/video-channel-edit-controller.service'+import { videoChannelEditRoutes } from './edit/video-channel-edit.routes'import { MyVideoChannelsComponent } from './my-video-channels.component'+export type ChannelManageResolverData = {+ videoChannel: VideoChannel+ collaborators: VideoChannelCollaborator[]+ rawPlayerSettings: PlayerChannelSettings+}++export const channelManageResolver: ResolveFn<ChannelManageResolverData> = (+ route: ActivatedRouteSnapshot,+ _state: RouterStateSnapshot+) => {+ const videoChannelName = route.params['videoChannelName']++ const videoChannelService = inject(VideoChannelService)+ const router = inject(Router)++ return forkJoin([+ videoChannelService.get(videoChannelName),+ videoChannelService.listCollaborators(videoChannelName).pipe(map(({ data }) => data)),+ inject(PlayerSettingsService).getChannelSettings({ channelHandle: videoChannelName, raw: true })+ ]).pipe(+ map(([ videoChannel, collaborators, rawPlayerSettings ]) => ({ videoChannel, collaborators, rawPlayerSettings })),+ catchError(err => {+ logger.error('Cannot fetch channel information', err)++ router.navigate([ '/401' ], { state: { obj: err }, skipLocationChange: true })++ return throwError(() => err)+ })+ )+}+export default [{path: '',@@ -20,15 +61,28 @@ export default [meta: {title: $localize`Create a new video channel`}- }+ },+ canDeactivate: [ CanDeactivateGuard ],+ providers: [ PlayerSettingsService, VideoChannelEditControllerService ],+ children: videoChannelEditRoutes},{path: 'update/:videoChannelName',- component: VideoChannelUpdateComponent,+ redirectTo: 'manage/:videoChannelName'+ },+ {+ path: 'manage/:videoChannelName',+ canDeactivate: [ CanDeactivateGuard ],+ component: VideoChannelManageComponent,data: {meta: {- title: $localize`Update video channel`+ title: $localize`Manage video channel`}- }+ },+ resolve: {+ data: channelManageResolver+ },+ providers: [ PlayerSettingsService, VideoChannelEditControllerService ],+ children: videoChannelEditRoutes}] satisfies Routesdiff --git a/client/src/app/+my-library/+my-video-channels/video-channel-create.component.ts b/client/src/app/+my-library/+my-video-channels/video-channel-create.component.tsnew file mode 100644index 0000000000..68dab36fe6--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/video-channel-create.component.ts@@ -0,0 +1,108 @@+import { AfterViewInit, Component, inject, OnInit } from '@angular/core'+import { Router } from '@angular/router'+import { AuthService, CanComponentDeactivate, HooksService, Notifier } from '@app/core'+import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'+import { HttpStatusCode } from '@peertube/peertube-models'+import { of } from 'rxjs'+import { switchMap } from 'rxjs/operators'+import { PlayerSettingsService } from '../../shared/shared-video/player-settings.service'+import { VideoChannelEditControllerService } from './edit/video-channel-edit-controller.service'+import { VideoChannelEditComponent } from './edit/video-channel-edit.component'+import { VideoChannelEdit } from './edit/video-channel-edit.model'++@Component({+ template: `+ <my-video-channel-edit [videoChannelEdit]="videoChannelEdit" [saveFn]="saveFn">+ </my-video-channel-edit>+ `,+ imports: [+ VideoChannelEditComponent+ ]+})+export class VideoChannelCreateComponent implements OnInit, AfterViewInit, CanComponentDeactivate {+ private authService = inject(AuthService)+ private notifier = inject(Notifier)+ private videoChannelService = inject(VideoChannelService)+ private hooks = inject(HooksService)+ private playerSettingsService = inject(PlayerSettingsService)+ private editControllerService = inject(VideoChannelEditControllerService)+ private router = inject(Router)++ videoChannelEdit = new VideoChannelEdit()+ saveFn = this.save.bind(this)++ ngOnInit (): void {+ this.videoChannelEdit.loadFromCreate({+ user: this.authService.getUser(),+ playerSettings: {+ theme: 'instance-default'+ }+ })++ this.editControllerService.setStore(this.videoChannelEdit)+ this.editControllerService.setMode('create')+ }++ ngAfterViewInit () {+ this.hooks.runAction('action:video-channel-create.init', 'video-channel')+ }++ canDeactivate () {+ return { canDeactivate: !this.videoChannelEdit.hasChanges() }+ }++ save () {+ this.editControllerService.resetError()++ return new Promise<void>(res => {+ this.videoChannelService.create(this.videoChannelEdit.channel)+ .pipe(+ switchMap(() => {+ return this.playerSettingsService.updateChannelSettings({+ channelHandle: this.videoChannelEdit.channel.name,+ settings: {+ theme: this.videoChannelEdit.playerSettings.theme+ }+ })+ }),+ switchMap(() => this.uploadAvatar(this.videoChannelEdit.channel.name, this.videoChannelEdit.avatar)),+ switchMap(() => this.uploadBanner(this.videoChannelEdit.channel.name, this.videoChannelEdit.banner))+ ).subscribe({+ next: () => {+ this.authService.refreshUserInformation()++ this.notifier.success($localize`Video channel ${this.videoChannelEdit.channel.displayName} created.`)++ this.videoChannelEdit.resetChanges()+ this.router.navigate([ '/my-library/video-channels/manage', this.videoChannelEdit.channel.name ])++ res()+ },++ error: err => {+ let message = err.message++ if (err.status === HttpStatusCode.CONFLICT_409) {+ message = $localize`Channel name "${this.videoChannelEdit.channel.name}" already exists on this platform.`+ }++ this.editControllerService.setError(message)++ res()+ }+ })+ })+ }++ private uploadAvatar (name: string, avatar?: FormData) {+ if (!avatar) return of(undefined)++ return this.videoChannelService.changeImage(name, avatar, 'avatar')+ }++ private uploadBanner (name: string, banner?: FormData) {+ if (!banner) return of(undefined)++ return this.videoChannelService.changeImage(name, banner, 'banner')+ }+}diff --git a/client/src/app/+my-library/+my-video-channels/video-channel-manage.component.ts b/client/src/app/+my-library/+my-video-channels/video-channel-manage.component.tsnew file mode 100644index 0000000000..e1f44ff8ca--- /dev/null+++ b/client/src/app/+my-library/+my-video-channels/video-channel-manage.component.ts@@ -0,0 +1,167 @@+import { AfterViewChecked, Component, inject, OnDestroy, OnInit } from '@angular/core'+import { ActivatedRoute } from '@angular/router'+import { AuthService, CanComponentDeactivate, HooksService, Notifier } from '@app/core'+import { genericUploadErrorHandler } from '@app/helpers'+import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'+import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'+import { VideoChannelUpdate } from '@peertube/peertube-models'+import { catchError, of, Subscription, switchMap, tap, throwError } from 'rxjs'+import { PlayerSettingsService } from '../../shared/shared-video/player-settings.service'+import { VideoChannelEditControllerService } from './edit/video-channel-edit-controller.service'+import { VideoChannelEditComponent } from './edit/video-channel-edit.component'+import { VideoChannelEdit } from './edit/video-channel-edit.model'+import { ChannelManageResolverData } from './routes'++@Component({+ selector: 'my-video-channel-manage',+ template: `+ <my-video-channel-edit [videoChannelEdit]="videoChannelEdit" [saveFn]="saveFn">+ </my-video-channel-edit>`,+ imports: [+ VideoChannelEditComponent+ ]+})+export class VideoChannelManageComponent implements OnInit, OnDestroy, AfterViewChecked, CanComponentDeactivate {+ private authService = inject(AuthService)+ private notifier = inject(Notifier)+ private route = inject(ActivatedRoute)+ private videoChannelService = inject(VideoChannelService)+ private playerSettingsService = inject(PlayerSettingsService)+ private hooks = inject(HooksService)+ private editControllerService = inject(VideoChannelEditControllerService)++ videoChannelEdit: VideoChannelEdit+ saveFn = this.save.bind(this)++ private runChannelInitHook = true+ private routeSub: Subscription++ ngOnInit () {+ this.editControllerService.setMode('update')++ this.routeSub = this.route.data.subscribe(d => {+ const data = d['data'] as ChannelManageResolverData++ this.videoChannelEdit = new VideoChannelEdit()++ this.videoChannelEdit.loadFromAPI({+ channel: data.videoChannel,+ playerSettings: data.rawPlayerSettings,+ collaborators: data.collaborators+ })++ this.editControllerService.setStore(this.videoChannelEdit)++ this.runChannelInitHook = true+ })+ }++ ngOnDestroy () {+ this.routeSub?.unsubscribe()+ }++ ngAfterViewChecked () {+ if (this.runChannelInitHook) {+ this.hooks.runAction('action:video-channel-update.init', 'video-channel')++ this.runChannelInitHook = false+ }+ }++ canDeactivate () {+ return { canDeactivate: !this.videoChannelEdit.hasChanges() }+ }++ save () {+ this.editControllerService.resetError()++ const videoChannelUpdate: VideoChannelUpdate = {+ displayName: this.videoChannelEdit.channel.displayName,+ description: this.videoChannelEdit.channel.description,+ support: this.videoChannelEdit.channel.support,+ bulkVideosSupportUpdate: this.videoChannelEdit.channel.bulkVideosSupportUpdate+ }++ return new Promise<void>(res => {+ this.videoChannelService.update(this.videoChannelEdit.channel.name, videoChannelUpdate)+ .pipe(+ switchMap(() => {+ return this.playerSettingsService.updateChannelSettings({+ channelHandle: this.videoChannelEdit.channel.name,+ settings: {+ theme: this.videoChannelEdit.playerSettings.theme+ }+ })+ }),+ switchMap(() => {+ return this.videoChannelEdit.avatarChanged+ ? this.updateOrDeleteAvatar(this.videoChannelEdit.avatar)+ : of(true)+ }),+ switchMap(() => {+ return this.videoChannelEdit.bannerChanged+ ? this.updateOrDeleteBanner(this.videoChannelEdit.banner)+ : of(true)+ })+ )+ .subscribe({+ next: () => {+ this.authService.refreshUserInformation()+ this.videoChannelEdit.resetChanges()++ this.notifier.success($localize`Video channel ${videoChannelUpdate.displayName} updated.`)++ res()+ },++ error: err => {+ this.editControllerService.setError(err.message)++ res()+ }+ })+ })+ }++ private updateOrDeleteAvatar (avatar: FormData) {+ if (!avatar) {+ return this.videoChannelService.deleteImage(this.videoChannelEdit.channel.name, 'avatar')+ .pipe(tap(() => this.videoChannelEdit.resetAvatarFromAPI()))+ }++ return this.videoChannelService.changeImage(this.videoChannelEdit.channel.name, avatar, 'avatar')+ .pipe(+ tap(data => this.videoChannelEdit.updateAvatarsFromAPI(data.avatars)),+ catchError(err =>+ throwError(() => {+ return new Error(genericUploadErrorHandler({+ err,+ name: $localize`avatar`,+ notifier: this.notifier+ }))+ })+ )+ )+ }++ private updateOrDeleteBanner (banner: FormData) {+ if (!banner) {+ return this.videoChannelService.deleteImage(this.videoChannelEdit.channel.name, 'banner')+ .pipe(tap(() => this.videoChannelEdit.resetBannerFromAPI()))+ }++ return this.videoChannelService.changeImage(this.videoChannelEdit.channel.name, banner, 'banner')+ .pipe(+ tap(data => this.videoChannelEdit.updateBannerUrlFromAPI(VideoChannel.GET_ACTOR_BANNER_URL(data))),+ catchError(err =>+ throwError(() => {+ return new Error(genericUploadErrorHandler({+ err,+ name: $localize`banner`,+ notifier: this.notifier+ }))+ })+ )+ )+ }+}diff --git a/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.html b/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.htmldeleted file mode 100644index b655d7d322..0000000000--- a/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.html+++ /dev/null@@ -1,2 +0,0 @@-<my-video-comment-list-admin-owner mode="user" key="UserVideoCommentList"></my-video-comment-list-admin-owner>-diff --git a/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.ts b/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.tsindex 17841cbf2d..1a2652fc45 100644--- a/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.ts+++ b/client/src/app/+my-library/comments-on-my-videos/comments-on-my-videos.component.ts@@ -3,7 +3,7 @@ import { Component } from '@angular/core'import { VideoCommentListAdminOwnerComponent } from '../../shared/shared-video-comment/video-comment-list-admin-owner.component'@Component({- templateUrl: './comments-on-my-videos.component.html',+ template: `<my-video-comment-list-admin-owner mode="user" key="UserVideoCommentList"></my-video-comment-list-admin-owner>`,imports: [VideoCommentListAdminOwnerComponent]diff --git a/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.ts b/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.tsindex 5d6af8bd7d..27be307c34 100644--- a/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.ts+++ b/client/src/app/+my-library/my-ownership/my-accept-ownership/my-accept-ownership.component.ts@@ -38,7 +38,7 @@ export class MyAcceptOwnershipComponent extends FormReactive implements OnInit {ngOnInit () {this.videoChannels = []- listUserChannelsForSelect(this.authService)+ listUserChannelsForSelect(this.authService, { includeCollaborations: false }).subscribe(channels => this.videoChannels = channels)this.buildForm({diff --git a/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.html b/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.htmlindex c404382b5c..734592df76 100644--- a/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.html+++ b/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.html@@ -28,19 +28,7 @@</td><td>- <a [routerLink]="[ '/c', sync.channel.name ]" i18n-title title="Channel page">- <div class="chip two-lines">- <my-actor-avatar- [actor]="sync.channel" actorType="channel"- [internalHref]="[ '/c', sync.channel.name ]" size="32"- ></my-actor-avatar>-- <div>- <span class="fw-semibold">{{ sync.channel.displayName }}</span>- <span class="muted">{{ sync.channel.name }}</span>- </div>- </div>- </a>+ <my-actor-cell [actor]="sync.channel" actorType="channel"></my-actor-cell></td><td>diff --git a/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.ts b/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.tsindex 9e05844f21..6d940734fb 100644--- a/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.ts+++ b/client/src/app/+my-library/my-video-channel-syncs/my-video-channel-syncs.component.ts@@ -5,9 +5,9 @@ import { AuthService, Notifier, ServerService } from '@app/core'import { VideoChannelSyncService } from '@app/shared/shared-main/channel/video-channel-sync.service'import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'+import { ActorCellComponent } from '@app/shared/shared-tables/actor-cell.component'import { HTMLServerConfig, VideoChannelSync, VideoChannelSyncState, VideoChannelSyncStateType } from '@peertube/peertube-models'import { first, mergeMap } from 'rxjs'-import { ActorAvatarComponent } from '../../shared/shared-actor-image/actor-avatar.component'import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'import { ActionDropdownComponent, DropdownAction } from '../../shared/shared-main/buttons/action-dropdown.component'import { NumberFormatterPipe } from '../../shared/shared-main/common/number-formatter.pipe'@@ -20,10 +20,10 @@ import { DataLoaderOptions, TableColumnInfo, TableComponent } from '../../sharedGlobalIconComponent,RouterLink,ActionDropdownComponent,- ActorAvatarComponent,PTDatePipe,TableComponent,- NumberFormatterPipe+ NumberFormatterPipe,+ ActorCellComponent]})export class MyVideoChannelSyncsComponent implements OnInit {@@ -56,6 +56,10 @@ export class MyVideoChannelSyncsComponent implements OnInit {dataLoader: typeof this._dataLoader+ get user () {+ return this.authService.getUser()+ }+constructor () {this.dataLoader = this._dataLoader.bind(this)}@@ -93,9 +97,10 @@ export class MyVideoChannelSyncsComponent implements OnInit {.pipe(first(),mergeMap(() => {- return this.videoChannelsSyncService.listAccountVideoChannelsSyncs({+ return this.videoChannelsSyncService.listByAccount({sort: options.sort,pagination: options.pagination,+ includeCollaborations: true,account: this.authService.getUser().account})})@@ -107,7 +112,7 @@ export class MyVideoChannelSyncsComponent implements OnInit {}deleteSync (videoChannelSync: VideoChannelSync) {- this.videoChannelsSyncService.deleteSync(videoChannelSync.id)+ this.videoChannelsSyncService.delete(videoChannelSync.id).subscribe({next: () => {this.notifier.success($localize`Synchronization removed successfully for ${videoChannelSync.channel.displayName}.`)diff --git a/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.ts b/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.tsindex cd805b2a98..f0dd49b4bf 100644--- a/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.ts+++ b/client/src/app/+my-library/my-video-channel-syncs/video-channel-sync-edit/video-channel-sync-edit.component.ts@@ -41,7 +41,7 @@ export class VideoChannelSyncEditComponent extends FormReactive implements OnIniexistingVideoStrategy: REQUIRED_VALIDATOR})- listUserChannelsForSelect(this.authService)+ listUserChannelsForSelect(this.authService, { includeCollaborations: true }).subscribe(channels => this.userVideoChannels = channels)}@@ -60,7 +60,7 @@ export class VideoChannelSyncEditComponent extends FormReactive implements OnIniconst importExistingVideos = body['existingVideoStrategy'] === 'import'- this.videoChannelSyncService.createSync(videoChannelSyncCreate)+ this.videoChannelSyncService.create(videoChannelSyncCreate).pipe(mergeMap(({ videoChannelSync }) => {return importExistingVideos? this.videoChannelService.importVideos(videoChannelSync.channel.name, videoChannelSync.externalChannelUrl, videoChannelSync.id)diff --git a/client/src/app/+my-library/my-video-imports/my-video-imports.component.html b/client/src/app/+my-library/my-video-imports/my-video-imports.component.htmlindex d96cc43f53..d7cd122ac4 100644--- a/client/src/app/+my-library/my-video-imports/my-video-imports.component.html+++ b/client/src/app/+my-library/my-video-imports/my-video-imports.component.html@@ -24,6 +24,12 @@}</td>+ <td>+ @if (videoImport.video?.channel) {+ <my-actor-cell [actor]="videoImport.video.channel" actorType="channel"></my-actor-cell>+ }+ </td>+<td>@if (isVideoImportPending(videoImport)) {{{ videoImport.video?.name }}@@ -55,7 +61,7 @@}@if (isVideoImportSuccess(videoImport) && videoImport.video) {- <my-edit-button [ptRouterLink]="getEditVideoUrl(videoImport.video)"></my-edit-button>+ <my-edit-button [ptRouterLink]="getEditVideoUrl(videoImport.video)" i18n-title title="Update the video"></my-edit-button>}</ng-template>diff --git a/client/src/app/+my-library/my-video-imports/my-video-imports.component.ts b/client/src/app/+my-library/my-video-imports/my-video-imports.component.tsindex 71321f6223..139b24fa45 100644--- a/client/src/app/+my-library/my-video-imports/my-video-imports.component.ts+++ b/client/src/app/+my-library/my-video-imports/my-video-imports.component.ts@@ -4,6 +4,7 @@ import { Notifier } from '@app/core'import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'import { VideoImportService } from '@app/shared/shared-main/video/video-import.service'import { Video } from '@app/shared/shared-main/video/video.model'+import { ActorCellComponent } from '@app/shared/shared-tables/actor-cell.component'import { VideoImport, VideoImportState, VideoImportStateType } from '@peertube/peertube-models'import { AdvancedInputFilterComponent } from '../../shared/shared-forms/advanced-input-filter.component'import { ButtonComponent } from '../../shared/shared-main/buttons/button.component'@@ -24,7 +25,8 @@ import { DataLoaderOptions, TableColumnInfo, TableComponent } from '../../sharedNgClass,PTDatePipe,TableComponent,- NumberFormatterPipe+ NumberFormatterPipe,+ ActorCellComponent]})export class MyVideoImportsComponent {@@ -35,6 +37,7 @@ export class MyVideoImportsComponent {columns: TableColumnInfo<string>[] = [{ id: 'target', label: $localize`Target`, sortable: false },+ { id: 'channel', label: $localize`Channel`, sortable: false },{ id: 'video', label: $localize`Video`, sortable: false },{ id: 'state', label: $localize`State`, sortable: false },{ id: 'createdAt', label: $localize`Created`, sortable: true }@@ -108,6 +111,6 @@ export class MyVideoImportsComponent {}private _dataLoader (options: DataLoaderOptions) {- return this.videoImportService.getMyVideoImports(options)+ return this.videoImportService.listMyVideoImports({ ...options, includeCollaborations: true })}}diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.tsindex 2f3e83fa40..9a5dd45b91 100644--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.ts+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-create.component.ts@@ -66,7 +66,7 @@ export class MyVideoPlaylistCreateComponent extends MyVideoPlaylistEdit implemensetPlaylistChannelValidator(this.form.get('videoChannelId'), privacy)})- listUserChannelsForSelect(this.authService)+ listUserChannelsForSelect(this.authService, { includeCollaborations: true }).subscribe(channels => this.userVideoChannels = channels)this.serverService.getVideoPlaylistPrivacies()@@ -122,6 +122,14 @@ export class MyVideoPlaylistCreateComponent extends MyVideoPlaylistEdit implemenreturn true}+ isEditor () {+ return false+ }++ getOwnerAccountDisplayName () {+ return this.authService.getUser().account.displayName+ }+getFormButtonTitle () {return $localize`Create`}diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.html b/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.htmlindex 367279ed0a..816919b065 100644--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.html+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.component.html@@ -64,6 +64,18 @@<div class="form-group"><label for="videoChannelId" i18n>Channel</label>+ @if (isEditor()) {+ <div class="form-group-description">+ <div i18n>+ Only {{ getOwnerAccountDisplayName() }}'s channels are listed+ </div>++ <div i18n>+ Changing the owner of a playlist is not supported+ </div>+ </div>+ }+<my-select-channel inputId="videoChannelId" [items]="userVideoChannels" formControlName="videoChannelId"></my-select-channel><div *ngIf="formErrors['videoChannelId']" class="form-error" role="alert">{{ formErrors['videoChannelId'] }}</div>diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.tsindex 0757b2369b..3543f57482 100644--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.ts+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-edit.ts@@ -11,4 +11,5 @@ export abstract class MyVideoPlaylistEdit extends FormReactive {abstract isCreation (): booleanabstract getFormButtonTitle (): string+ abstract isEditor (): boolean}diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.tsindex 816b598646..0319741f48 100644--- a/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlist-update.component.ts@@ -1,4 +1,4 @@-import { NgClass, NgIf } from '@angular/common'+import { CommonModule, NgClass } from '@angular/common'import { Component, inject, OnDestroy, OnInit } from '@angular/core'import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { ActivatedRoute, Router, RouterLink } from '@angular/router'@@ -29,7 +29,7 @@ import { MyVideoPlaylistEdit } from './my-video-playlist-edit'templateUrl: './my-video-playlist-edit.component.html',styleUrls: [ './my-video-playlist-edit.component.scss' ],imports: [- NgIf,+ CommonModule,RouterLink,FormsModule,ReactiveFormsModule,@@ -69,23 +69,22 @@ export class MyVideoPlaylistUpdateComponent extends MyVideoPlaylistEdit implemensetPlaylistChannelValidator(this.form.get('videoChannelId'), privacy)})- listUserChannelsForSelect(this.authService)- .subscribe(channels => this.userVideoChannels = channels)-this.paramsSub = this.route.params.pipe(map(routeParams => routeParams['videoPlaylistId']),switchMap(videoPlaylistId => {return forkJoin([this.videoPlaylistService.getVideoPlaylist(videoPlaylistId),- this.serverService.getVideoPlaylistPrivacies()+ this.serverService.getVideoPlaylistPrivacies(),+ listUserChannelsForSelect(this.authService, { includeCollaborations: true })])})).subscribe({- next: ([ videoPlaylistToUpdate, videoPlaylistPrivacies ]) => {+ next: ([ videoPlaylistToUpdate, videoPlaylistPrivacies, channels ]) => {this.videoPlaylistToUpdate = videoPlaylistToUpdatethis.videoPlaylistPrivacies = videoPlaylistPrivacies+ this.userVideoChannels = channels.filter(c => c.ownerAccountId === this.videoPlaylistToUpdate.ownerAccount.id)this.hydrateFormFromPlaylist()},@@ -133,6 +132,16 @@ export class MyVideoPlaylistUpdateComponent extends MyVideoPlaylistEdit implemenreturn $localize`Update`}+ isEditor () {+ if (!this.videoPlaylistToUpdate) return false++ return this.videoPlaylistToUpdate?.ownerAccount.id !== this.authService.getUser().account.id+ }++ getOwnerAccountDisplayName () {+ return this.videoPlaylistToUpdate?.ownerAccount.displayName+ }+private hydrateFormFromPlaylist () {this.form.patchValue({displayName: this.videoPlaylistToUpdate.displayName,diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.html b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.htmlindex 7ea5b644b9..47c39d4cf3 100644--- a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.html+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.html@@ -58,9 +58,21 @@</td><td *ngIf="table.isColumnDisplayed('name')">- <a [routerLink]="[ '/my-library/video-playlists', playlist.shortUUID ]" class="name">- {{ playlist.displayName }}- </a>+ <div class="name-container">+ <a [routerLink]="[ '/my-library/video-playlists', playlist.shortUUID ]" class="name">+ {{ playlist.displayName }}+ </a>++ @if (playlist.videoChannel) {+ <a [routerLink]="[ '/c', playlist.videoChannel.name]" class="channel-sub-link-in-cell">+ <span>{{ playlist.videoChannel.displayName }}</span>++ @if (user.isEditorOfChannel(playlist.videoChannel)) {+ <my-collaborator-state class="ms-2" type="accepted" small="true"></my-collaborator-state>+ }+ </a>+ }+ </div></td><td *ngIf="table.isColumnDisplayed('privacy')">diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scss b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scssindex 5387684452..6a5d9a2dcd 100644--- a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scss+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.scss@@ -3,10 +3,6 @@@use "_form-mixins" as *;@use "_actor" as *;-.channel-label {- @include channel-label;-}-.channel-filters {@include channel-filters;}@@ -18,6 +14,12 @@text-decoration: none;}+.name-container {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}+my-video-playlist-miniature {display: block;width: 130px;diff --git a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.ts b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.tsindex 57713d5119..685137ebce 100644--- a/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.ts+++ b/client/src/app/+my-library/my-video-playlists/my-video-playlists.component.ts@@ -6,6 +6,7 @@ import { RouterLink } from '@angular/router'import { AuthService, AuthUser, ConfirmService, Notifier, RestPagination, ScreenService } from '@app/core'import { HeaderService } from '@app/header/header.service'import { Actor } from '@app/shared/shared-main/account/actor.model'+import { CollaboratorStateComponent } from '@app/shared/shared-main/channel/collaborator-state.component'import { TableColumnInfo, TableComponent, TableQueryParams } from '@app/shared/shared-tables/table.component'import { VideoPlaylist } from '@app/shared/shared-video-playlist/video-playlist.model'import { VideoPlaylistService } from '@app/shared/shared-video-playlist/video-playlist.service'@@ -49,7 +50,8 @@ const debugLogger = debug('peertube:my-video-playlists')NumberFormatterPipe,PrivacyBadgeComponent,PTDatePipe,- DragDropModule+ DragDropModule,+ CollaboratorStateComponent]})export class MyVideoPlaylistsComponent implements OnInit, OnDestroy {@@ -112,7 +114,7 @@ export class MyVideoPlaylistsComponent implements OnInit, OnDestroy {private _customParseQueryParams (queryParams: QueryParams) {this.user = this.auth.getUser()- this.channels = this.user.videoChannels.map(c => ({+ this.channels = [ ...this.user.videoChannels, ...this.user.videoChannelCollaborations ].map(c => ({...c,selected: queryParams.channelName === c.name@@ -228,12 +230,14 @@ export class MyVideoPlaylistsComponent implements OnInit, OnDestroy {const obs = channel? this.videoPlaylistService.listChannelPlaylists({videoChannel: { nameWithHost: Actor.CREATE_BY_STRING(channel.name, channel.host) },+ includeCollaborations: true,restPagination: pagination,sort,search}): this.videoPlaylistService.listAccountPlaylists({account: this.user.account,+ includeCollaborations: true,restPagination: pagination,sort,searchdiff --git a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.html b/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.htmlindex 19427a3e04..46cd17138a 100644--- a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.html+++ b/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.html@@ -11,15 +11,9 @@<div class="form-group"><label i18n for="next-ownership-username">Select the next owner</label>- <p-autoComplete- formControlName="username" [suggestions]="usernamePropositions"- (completeMethod)="search($event)" id="next-ownership-username"- fluid="true"- ></p-autoComplete>+ <my-user-auto-complete inputName="next-ownership-username" formControlName="username"></my-user-auto-complete>- <div *ngIf="formErrors.username" class="form-error" role="alert">- {{ formErrors.username }}- </div>+ <div *ngIf="formErrors.username" class="form-error" role="alert">{{ formErrors.username }}</div></div></div>diff --git a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts b/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.tsindex 316b9eb16a..b56cca83f6 100644--- a/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts+++ b/client/src/app/+my-library/my-videos/modals/video-change-ownership.component.ts@@ -1,46 +1,42 @@-import { Component, ElementRef, OnInit, inject, viewChild } from '@angular/core'-import { Notifier, UserService } from '@app/core'+import { CommonModule } from '@angular/common'+import { Component, ElementRef, OnInit, inject, input, output, viewChild } from '@angular/core'+import { 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 { 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 { VideoOwnershipService } from '@app/shared/shared-main/video/video-ownership.service'import { NgbModal } from '@ng-bootstrap/ng-bootstrap'-import { NgIf } from '@angular/common'import { AutoCompleteModule } from 'primeng/autocomplete'-import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { GlobalIconComponent } from '../../../shared/shared-icons/global-icon.component'-import { VideoOwnershipService } from '@app/shared/shared-main/video/video-ownership.service'-import { Video } from '@app/shared/shared-main/video/video.model'@Component({selector: 'my-video-change-ownership',templateUrl: './video-change-ownership.component.html',styleUrls: [ './video-change-ownership.component.scss' ],- imports: [ GlobalIconComponent, FormsModule, ReactiveFormsModule, AutoCompleteModule, NgIf ]+ imports: [ CommonModule, GlobalIconComponent, FormsModule, ReactiveFormsModule, AutoCompleteModule, UserAutoCompleteComponent ]})export class VideoChangeOwnershipComponent extends FormReactive implements OnInit {protected formReactiveService = inject(FormReactiveService)private videoOwnershipService = inject(VideoOwnershipService)private notifier = inject(Notifier)- private userService = inject(UserService)private modalService = inject(NgbModal)- readonly modal = viewChild<ElementRef>('modal')+ videoId = input.required<number>()+ requestSent = output<string>()- usernamePropositions: string[]+ readonly modal = viewChild<ElementRef>('modal')error: string = null- private video: Video | undefined = undefined-ngOnInit () {this.buildForm({username: OWNERSHIP_CHANGE_USERNAME_VALIDATOR})- this.usernamePropositions = []}- show (video: Video) {- this.video = video+ show () {this.modalService.open(this.modal(), { centered: true }).result@@ -48,25 +44,15 @@ export class VideoChangeOwnershipComponent extends FormReactive implements OnIni.catch(_ => _) // Called when closing (cancel) the modal without validating, do nothing}- search (event: { query: string }) {- const query = event.query- this.userService.autocomplete(query)- .subscribe({- next: usernames => {- this.usernamePropositions = usernames- },-- error: err => this.notifier.error(err.message)- })- }-changeOwnership () {const username = this.form.value['username']this.videoOwnershipService- .changeOwnership(this.video.id, username)+ .changeOwnership(this.videoId(), username).subscribe({- next: () => this.notifier.success($localize`Ownership change request sent.`),+ next: () => {+ this.requestSent.emit(username)+ },error: err => this.notifier.error(err.message)})diff --git a/client/src/app/+my-library/my-videos/my-videos.component.html b/client/src/app/+my-library/my-videos/my-videos.component.htmlindex 63d91156b1..4f67c214c1 100644--- a/client/src/app/+my-library/my-videos/my-videos.component.html+++ b/client/src/app/+my-library/my-videos/my-videos.component.html@@ -59,7 +59,7 @@</td><td *ngIf="table.isColumnDisplayed('name')">- <my-video-cell class="video-cell-name" [video]="video" thumbnail="false" title="true"></my-video-cell>+ <my-video-cell class="video-cell-name" [video]="video" thumbnail="false" title="true" displayEditorInfo="true"></my-video-cell></td><td *ngIf="table.isColumnDisplayed('privacy')">@@ -111,8 +111,7 @@<my-button class="me-3" i18n-label label="Manage" [ptRouterLink]="[ '/videos', 'manage', video.shortUUID ]" theme="secondary" icon="film" responsiveLabel="true"></my-button><my-video-actions-dropdown- placement="bottom auto" buttonDirection="horizontal" buttonStyled="true" [video]="video" [displayOptions]="videoActionsOptions"- [moreActions]="moreVideoActions"+ placement="bottom auto" buttonIcon="more-horizontal" buttonStyled="true" [video]="video" [displayOptions]="videoActionsOptions"(videoRemoved)="table.loadData()" (videoFilesRemoved)="table.loadData()" (transcodingCreated)="table.loadData()" (videoExistsInPlaylistChange)="fetchVideosContainedInPlaylists([ video ])"></my-video-actions-dropdown></ng-template>@@ -123,4 +122,3 @@</my-table>-<my-video-change-ownership #videoChangeOwnershipModal></my-video-change-ownership>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 1d9f8482de..c08c7c17ca 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@@ -57,7 +57,6 @@ type QueryParams = TableQueryParams & {VideoCellComponent,RouterLink,NumberFormatterPipe,- VideoChangeOwnershipComponent,VideoStateBadgeComponent,ChannelToggleComponent,SelectCheckboxComponent,@@ -97,8 +96,6 @@ export class MyVideosComponent implements OnInit, OnDestroy {transcoding: false}- moreVideoActions: DropdownAction<{ video: Video }>[][] = []-user: AuthUserchannels: (VideoChannel & { selected: boolean })[] = []@@ -183,7 +180,7 @@ export class MyVideosComponent implements OnInit, OnDestroy {: new Set<string>()this.user = this.auth.getUser()- this.channels = this.user.videoChannels.map(c => ({+ this.channels = [ ...this.user.videoChannels, ...this.user.videoChannelCollaborations ].map(c => ({...c,selected: enabledChannels.has(c.name)@@ -281,6 +278,7 @@ export class MyVideosComponent implements OnInit, OnDestroy {restPagination: pagination,sort,search,+ includeCollaborations: true,channelNameOneOf: channelNameOneOf.length !== 0? channelNameOneOf@@ -327,16 +325,6 @@ export class MyVideosComponent implements OnInit, OnDestroy {}private buildActions () {- this.moreVideoActions = [- [- {- label: $localize`Change ownership`,- handler: ({ video }) => this.videoChangeOwnershipModal().show(video),- iconName: 'ownership-change'- }- ]- ]-this.bulkActions = [[{diff --git a/client/src/app/+video-channels/video-channels.component.ts b/client/src/app/+video-channels/video-channels.component.tsindex 50c68f1acf..e9eb50fdec 100644--- a/client/src/app/+video-channels/video-channels.component.ts+++ b/client/src/app/+video-channels/video-channels.component.ts@@ -72,7 +72,7 @@ export class VideoChannelsComponent implements OnInit, OnDestroy {.pipe(map(params => params['videoChannelName']),distinctUntilChanged(),- switchMap(videoChannelName => this.videoChannelService.getVideoChannel(videoChannelName)),+ switchMap(videoChannelName => this.videoChannelService.get(videoChannelName)),catchError(err =>this.restExtractor.redirectTo404IfNotFound(err, 'other', [HttpStatusCode.BAD_REQUEST_400,diff --git a/client/src/app/+video-watch/shared/action-buttons/action-buttons.component.html b/client/src/app/+video-watch/shared/action-buttons/action-buttons.component.htmlindex 6092a04a14..a37315e56d 100644--- a/client/src/app/+video-watch/shared/action-buttons/action-buttons.component.html+++ b/client/src/app/+video-watch/shared/action-buttons/action-buttons.component.html@@ -50,7 +50,7 @@[video]="video()" [videoCaptions]="videoCaptions()" [transcriptionWidgetOpened]="transcriptionWidgetOpened()"[displayOptions]="videoActionsOptions" (videoRemoved)="onVideoRemoved()"(showTranscriptionWidget)="showTranscriptionWidget.emit()" (hideTranscriptionWidget)="hideTranscriptionWidget.emit()"- placement="bottom auto" buttonDirection="horizontal" buttonStyled="true"+ placement="bottom auto" buttonIcon="more-horizontal" buttonStyled="true"actionAvailabilityHint="true"></my-video-actions-dropdown></div>diff --git a/client/src/app/+video-watch/shared/comment/video-comment.component.scss b/client/src/app/+video-watch/shared/comment/video-comment.component.scssindex 3671843aff..9b2122f5eb 100644--- a/client/src/app/+video-watch/shared/comment/video-comment.component.scss+++ b/client/src/app/+video-watch/shared/comment/video-comment.component.scss@@ -1,5 +1,5 @@-@use '_variables' as *;-@use '_mixins' as *;+@use "_variables" as *;+@use "_mixins" as *;.root-comment {display: flex;@@ -107,7 +107,7 @@// Paragraphs::ng-deep p {- margin-bottom: .3rem;+ margin-bottom: 0.3rem;}&.comment-html-deleted {@@ -120,7 +120,6 @@margin-bottom: 10px;display: flex;- ::ng-deep .dropdown-toggle,.comment-action-reply {color: pvar(--fg-300);cursor: pointer;@@ -134,12 +133,6 @@color: pvar(--fg);}}-- ::ng-deep .action-button {- background-color: transparent;- padding: 0;- font-weight: unset;- }}my-video-comment-add {diff --git a/client/src/app/+video-watch/shared/metadata/index.ts b/client/src/app/+video-watch/shared/metadata/index.tsindex de9abe97e0..e2d5d6ce5d 100644--- a/client/src/app/+video-watch/shared/metadata/index.ts+++ b/client/src/app/+video-watch/shared/metadata/index.ts@@ -1,3 +1,3 @@export * from './video-attributes.component'-export * from './video-avatar-channel.component'+export * from '../../../shared/shared-actor-image/account-on-channel-avatar.component'export * from './video-description.component'diff --git a/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.html b/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.htmldeleted file mode 100644index 502bf474bb..0000000000--- a/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.html+++ /dev/null@@ -1,20 +0,0 @@-<div class="wrapper">- <my-actor-avatar- *ngIf="showChannel()"- class="channel"- [actor]="video().channel" actorType="channel"- [internalHref]="[ '/c', video().byVideoChannel ]"- [title]="channelLinkTitle"- size="35"- ></my-actor-avatar>-- <my-actor-avatar- *ngIf="showAccount()"- class="account"- [class.second-avatar]="showChannel()"- [actor]="video().account" actorType="account"- [internalHref]="[ '/a', video().byAccount ]"- [title]="accountLinkTitle"- size="35">- </my-actor-avatar>-</div>diff --git a/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.ts b/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.tsdeleted file mode 100644index 119e4b94a1..0000000000--- a/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.ts+++ /dev/null@@ -1,26 +0,0 @@-import { NgIf } from '@angular/common'-import { Component, OnInit, input } from '@angular/core'-import { ActorAvatarComponent } from '@app/shared/shared-actor-image/actor-avatar.component'-import { Video } from '@app/shared/shared-main/video/video.model'--@Component({- selector: 'my-video-avatar-channel',- templateUrl: './video-avatar-channel.component.html',- styleUrls: [ './video-avatar-channel.component.scss' ],- imports: [ NgIf, ActorAvatarComponent ]-})-export class VideoAvatarChannelComponent implements OnInit {- readonly video = input<Video>(undefined)- readonly byAccount = input<string>(undefined)-- readonly showAccount = input<boolean>(undefined)- readonly showChannel = input<boolean>(undefined)-- channelLinkTitle = ''- accountLinkTitle = ''-- ngOnInit () {- this.channelLinkTitle = $localize`${this.video().account.name} (channel page)`- this.accountLinkTitle = $localize`${this.video().byAccount} (account page)`- }-}diff --git a/client/src/app/+video-watch/video-watch.component.html b/client/src/app/+video-watch/video-watch.component.htmlindex 0fb189f3a5..a31c4454fb 100644--- a/client/src/app/+video-watch/video-watch.component.html+++ b/client/src/app/+video-watch/video-watch.component.html@@ -76,16 +76,18 @@<div class="pt-3 border-top video-info-channel d-flex"><div class="video-info-channel-left d-flex">- <my-video-avatar-channel [video]="video" [showChannel]="!isChannelDisplayNameGeneric()"></my-video-avatar-channel>+ <my-account-on-channel-avatar+ [account]="video.account"+ [channel]="video.channel"+ [internalHref]="getAccountOrChannelRouterLink()"+ [showChannel]="!isChannelDisplayNameGeneric()"+ ></my-account-on-channel-avatar><div class="video-info-channel-left-links ms-1"><ng-container *ngIf="!isChannelDisplayNameGeneric()">- <a [routerLink]="[ '/c', video.byVideoChannel ]" i18n-title title="Channel page">- {{ video.channel.displayName }}- </a>- <a [routerLink]="[ '/a', video.byAccount ]" i18n-title title="Account page">- <span i18n>By {{ video.byAccount }}</span>- </a>+ <a [routerLink]="[ '/c', video.byVideoChannel ]" i18n-title title="Go to the channel page">{{ video.channel.displayName }}</a>++ <a [routerLink]="[ '/a', video.byAccount ]" i18n-title title="Go to the account page"><span i18n>By {{ video.byAccount }}</span></a></ng-container><ng-container *ngIf="isChannelDisplayNameGeneric()">diff --git a/client/src/app/+video-watch/video-watch.component.ts b/client/src/app/+video-watch/video-watch.component.tsindex 0317985e75..d2ae692a54 100644--- a/client/src/app/+video-watch/video-watch.component.ts+++ b/client/src/app/+video-watch/video-watch.component.ts@@ -1,4 +1,4 @@-import { NgClass, NgIf, NgTemplateOutlet, PlatformLocation } from '@angular/common'+import { CommonModule, NgTemplateOutlet, PlatformLocation } from '@angular/common'import { Component, ElementRef, inject, LOCALE_ID, NgZone, OnDestroy, OnInit, viewChild } from '@angular/core'import { ActivatedRoute, Params, Router, RouterLink } from '@angular/router'import {@@ -63,6 +63,7 @@ import { isP2PEnabled, videoRequiresFileToken, videoRequiresUserAuth } from '@roimport debug from 'debug'import { forkJoin, map, Observable, of, Subscription, switchMap } from 'rxjs'import { environment } from '../../environments/environment'+import { AccountOnChannelAvatarComponent } from '../shared/shared-actor-image/account-on-channel-avatar.component'import { DateToggleComponent } from '../shared/shared-main/date/date-toggle.component'import { PluginPlaceholderComponent } from '../shared/shared-main/plugins/plugin-placeholder.component'import { VideoViewsCounterComponent } from '../shared/shared-video/video-views-counter.component'@@ -72,7 +73,6 @@ import { VideoCommentsComponent } from './shared/comment/video-comments.componenimport { PrivacyConcernsComponent } from './shared/information/privacy-concerns.component'import { VideoAlertComponent } from './shared/information/video-alert.component'import { VideoAttributesComponent } from './shared/metadata/video-attributes.component'-import { VideoAvatarChannelComponent } from './shared/metadata/video-avatar-channel.component'import { VideoDescriptionComponent } from './shared/metadata/video-description.component'import { VideoTranscriptionComponent } from './shared/player-widgets/video-transcription.component'import { VideoWatchPlaylistComponent } from './shared/player-widgets/video-watch-playlist.component'@@ -105,8 +105,7 @@ type URLOptions = {templateUrl: './video-watch.component.html',styleUrls: [ './video-watch.component.scss' ],imports: [- NgClass,- NgIf,+ CommonModule,VideoWatchPlaylistComponent,PluginPlaceholderComponent,VideoAlertComponent,@@ -114,7 +113,7 @@ type URLOptions = {VideoViewsCounterComponent,NgTemplateOutlet,ActionButtonsComponent,- VideoAvatarChannelComponent,+ AccountOnChannelAvatarComponent,RouterLink,SubscribeButtonComponent,VideoDescriptionComponent,@@ -295,6 +294,14 @@ export class VideoWatchComponent implements OnInit, OnDestroy {return genericChannelDisplayName.includes(this.video.channel.displayName)}+ getAccountOrChannelRouterLink () {+ if (!this.isChannelDisplayNameGeneric()) {+ return `/c/${this.video.byVideoChannel}`+ }++ return `/a/${this.video.byAccount}`+ }+displayOtherVideosAsRow () {// Use the same value as in the SASS filereturn this.screenService.getWindowInnerWidth() <= 1100diff --git a/client/src/app/+videos-publish-manage/+video-manage/video-manage.resolver.ts b/client/src/app/+videos-publish-manage/+video-manage/video-manage.resolver.tsindex 45bf1c4c5d..bbd5ef6577 100644--- a/client/src/app/+videos-publish-manage/+video-manage/video-manage.resolver.ts+++ b/client/src/app/+videos-publish-manage/+video-manage/video-manage.resolver.ts@@ -1,5 +1,5 @@import { Injectable, inject } from '@angular/core'-import { ActivatedRouteSnapshot } from '@angular/router'+import { ActivatedRouteSnapshot, Router } from '@angular/router'import { AuthService, ServerService, UserService } from '@app/core'import { listUserChannelsForSelect } from '@app/helpers'import { VideoCaptionService } from '@app/shared/shared-main/video-caption/video-caption.service'@@ -8,6 +8,7 @@ import { VideoDetails } from '@app/shared/shared-main/video/video-details.model'import { VideoPasswordService } from '@app/shared/shared-main/video/video-password.service'import { VideoService } from '@app/shared/shared-main/video/video.service'import { LiveVideoService } from '@app/shared/shared-video-live/live-video.service'+import { PlayerSettingsService } from '@app/shared/shared-video/player-settings.service'import {LiveVideo,PlayerVideoSettings,@@ -20,11 +21,11 @@ import {VideoPrivacyType,VideoSource} from '@peertube/peertube-models'-import { forkJoin, of } from 'rxjs'-import { map, switchMap } from 'rxjs/operators'+import { logger } from '@root-helpers/logger'+import { forkJoin, of, throwError } from 'rxjs'+import { catchError, map, switchMap } from 'rxjs/operators'import { SelectChannelItem } from '../../../types'import { VideoEdit } from '../shared-manage/common/video-edit.model'-import { PlayerSettingsService } from '@app/shared/shared-video/player-settings.service'export type VideoManageResolverData = {video: VideoDetails@@ -42,6 +43,7 @@ export type VideoManageResolverData = {@Injectable()export class VideoManageResolver {+ private router = inject(Router)private videoService = inject(VideoService)private liveVideoService = inject(LiveVideoService)private authService = inject(AuthService)@@ -59,7 +61,18 @@ export class VideoManageResolver {.pipe(switchMap(video => forkJoin(this.buildObservables(video))),switchMap(- async ([ video, videoSource, userChannels, captions, chapters, live, videoPasswords, userQuota, privacies, playerSettings ]) => {+ async ([+ video,+ videoSource,+ allUserChannels,+ captions,+ chapters,+ live,+ videoPasswords,+ userQuota,+ privacies,+ playerSettings+ ]) => {const videoEdit = await VideoEdit.createFromAPI(this.serverService.getHTMLConfig(), {video,captions,@@ -72,7 +85,7 @@ export class VideoManageResolver {return {video,- userChannels,+ userChannels: allUserChannels.filter(c => c.ownerAccountId === video.channel.ownerAccount.id),captions,chapters,videoSource,@@ -84,7 +97,14 @@ export class VideoManageResolver {playerSettings} satisfies VideoManageResolverData}- )+ ),+ catchError(err => {+ logger.error('Cannot fetch video information', err)++ this.router.navigate([ '/401' ], { state: { obj: err }, skipLocationChange: true })++ return throwError(() => err)+ }))}@@ -94,7 +114,7 @@ export class VideoManageResolver {this.videoService.getSource(video.id),- listUserChannelsForSelect(this.authService),+ listUserChannelsForSelect(this.authService, { includeCollaborations: true }),this.videoCaptionService.listCaptions(video.uuid)diff --git a/client/src/app/+videos-publish-manage/+video-publish/import/video-import-torrent.component.ts b/client/src/app/+videos-publish-manage/+video-publish/import/video-import-torrent.component.tsindex 2158ab55ae..f932607f0b 100644--- a/client/src/app/+videos-publish-manage/+video-publish/import/video-import-torrent.component.ts+++ b/client/src/app/+videos-publish-manage/+video-publish/import/video-import-torrent.component.ts@@ -3,7 +3,7 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { ActivatedRoute } from '@angular/router'import { VideoEdit } from '@app/+videos-publish-manage/shared-manage/common/video-edit.model'import { VideoManageController } from '@app/+videos-publish-manage/shared-manage/video-manage-controller.service'-import { CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'+import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'import { AlertComponent } from '@app/shared/shared-main/common/alert.component'import { VideoImportService } from '@app/shared/shared-main/video/video-import.service'import { VideoService } from '@app/shared/shared-main/video/video.service'@@ -41,6 +41,7 @@ const debugLogger = debug('peertube:video-publish')]})export class VideoImportTorrentComponent implements OnInit, AfterViewInit, CanComponentDeactivate {+ private authService = inject(AuthService)private loadingBar = inject(LoadingBarService)private notifier = inject(Notifier)private videoService = inject(VideoService)@@ -121,7 +122,8 @@ export class VideoImportTorrentComponent implements OnInit, AfterViewInit, CanCotorrentfile,magnetUri: this.firstStepMagnetUri,channelId: this.firstStepChannelId,- support: this.userChannels().find(c => c.id === this.firstStepChannelId).support ?? ''+ support: this.userChannels().find(c => c.id === this.firstStepChannelId).support ?? '',+ user: this.authService.getUser()})this.manageController.setConfig({ manageType: 'import-torrent', serverConfig: this.serverService.getHTMLConfig() })this.manageController.setVideoEdit(videoEdit)diff --git a/client/src/app/+videos-publish-manage/+video-publish/import/video-import-url.component.ts b/client/src/app/+videos-publish-manage/+video-publish/import/video-import-url.component.tsindex 6fe9106ffb..6a184eb906 100644--- a/client/src/app/+videos-publish-manage/+video-publish/import/video-import-url.component.ts+++ b/client/src/app/+videos-publish-manage/+video-publish/import/video-import-url.component.ts@@ -4,7 +4,7 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { ActivatedRoute, RouterLink } from '@angular/router'import { VideoEdit } from '@app/+videos-publish-manage/shared-manage/common/video-edit.model'import { VideoManageController } from '@app/+videos-publish-manage/shared-manage/video-manage-controller.service'-import { CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'+import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'import { AlertComponent } from '@app/shared/shared-main/common/alert.component'import { VideoCaptionService } from '@app/shared/shared-main/video-caption/video-caption.service'import { VideoChapterService } from '@app/shared/shared-main/video/video-chapter.service'@@ -40,6 +40,7 @@ const debugLogger = debug('peertube:video-publish')]})export class VideoImportUrlComponent implements OnInit, AfterViewInit, CanComponentDeactivate {+ private authService = inject(AuthService)private loadingBar = inject(LoadingBarService)private notifier = inject(Notifier)private videoService = inject(VideoService)@@ -111,7 +112,8 @@ export class VideoImportUrlComponent implements OnInit, AfterViewInit, CanComponconst videoEdit = VideoEdit.createFromImport(serverConfig, {targetUrl: this.targetUrl,channelId: this.firstStepChannelId,- support: this.userChannels().find(c => c.id === this.firstStepChannelId).support ?? ''+ support: this.userChannels().find(c => c.id === this.firstStepChannelId).support ?? '',+ user: this.authService.getUser()})this.manageController.setConfig({ manageType: 'import-url', serverConfig: this.serverService.getHTMLConfig() })this.manageController.setVideoEdit(videoEdit)diff --git a/client/src/app/+videos-publish-manage/+video-publish/live/video-go-live.component.ts b/client/src/app/+videos-publish-manage/+video-publish/live/video-go-live.component.tsindex e6d75e4f5f..0f72e23a90 100644--- a/client/src/app/+videos-publish-manage/+video-publish/live/video-go-live.component.ts+++ b/client/src/app/+videos-publish-manage/+video-publish/live/video-go-live.component.ts@@ -3,7 +3,7 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'import { ActivatedRoute } from '@angular/router'import { VideoEdit } from '@app/+videos-publish-manage/shared-manage/common/video-edit.model'import { VideoManageController } from '@app/+videos-publish-manage/shared-manage/video-manage-controller.service'-import { CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'+import { AuthService, CanComponentDeactivate, HooksService, Notifier, ServerService } from '@app/core'import { LiveVideoService } from '@app/shared/shared-video-live/live-video.service'import { LiveVideoLatencyMode, PeerTubeProblemDocument, ServerErrorCode, UserVideoQuota, VideoPrivacyType } from '@peertube/peertube-models'import debug from 'debug'@@ -32,6 +32,7 @@ const debugLogger = debug('peertube:video-publish')})export class VideoGoLiveComponent implements OnInit, AfterViewInit, CanComponentDeactivate {private notifier = inject(Notifier)+ private authService = inject(AuthService)private serverService = inject(ServerService)private liveVideoService = inject(LiveVideoService)private hooks = inject(HooksService)@@ -90,7 +91,8 @@ export class VideoGoLiveComponent implements OnInit, AfterViewInit, CanComponentlatencyMode: LiveVideoLatencyMode.DEFAULT,saveReplay: this.isReplayAllowed(),replaySettings: { privacy: this.highestPrivacy() },- schedules: []+ schedules: [],+ user: this.authService.getUser()})this.manageController.setConfig({ manageType: 'go-live', serverConfig: this.serverService.getHTMLConfig() })this.manageController.setVideoEdit(videoEdit)diff --git a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.ts b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.tsindex ba2483e056..082b3528c7 100644--- a/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.ts+++ b/client/src/app/+videos-publish-manage/+video-publish/upload/video-upload.component.ts@@ -5,7 +5,7 @@ import { ActivatedRoute } from '@angular/router'import { VideoEdit } from '@app/+videos-publish-manage/shared-manage/common/video-edit.model'import { VideoUploadService } from '@app/+videos-publish-manage/shared-manage/common/video-upload.service'import { VideoManageController } from '@app/+videos-publish-manage/shared-manage/video-manage-controller.service'-import { CanComponentDeactivate, HooksService, MetaService, Notifier, ServerService } from '@app/core'+import { AuthService, CanComponentDeactivate, HooksService, MetaService, Notifier, ServerService } from '@app/core'import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'import { UserVideoQuota, VideoPrivacyType } from '@peertube/peertube-models'import debug from 'debug'@@ -43,6 +43,7 @@ const debugLogger = debug('peertube:video-publish')})export class VideoUploadComponent implements OnInit, OnDestroy, AfterViewInit, CanComponentDeactivate {private notifier = inject(Notifier)+ private authService = inject(AuthService)private serverService = inject(ServerService)private hooks = inject(HooksService)private metaService = inject(MetaService)@@ -213,7 +214,8 @@ export class VideoUploadComponent implements OnInit, OnDestroy, AfterViewInit, Cthis.videoEdit = VideoEdit.createFromUpload(serverConfig, {name: this.buildVideoFilename(file.name),channelId: this.firstStepChannelId,- support: this.userChannels().find(c => c.id === this.firstStepChannelId).support ?? ''+ support: this.userChannels().find(c => c.id === this.firstStepChannelId).support ?? '',+ user: this.authService.getUser()})this.manageController.setConfig({ manageType: 'upload', serverConfig: this.serverService.getHTMLConfig() })diff --git a/client/src/app/+videos-publish-manage/+video-publish/video-publish.resolver.ts b/client/src/app/+videos-publish-manage/+video-publish/video-publish.resolver.tsindex c3d7eaeae5..30dd951f98 100644--- a/client/src/app/+videos-publish-manage/+video-publish/video-publish.resolver.ts+++ b/client/src/app/+videos-publish-manage/+video-publish/video-publish.resolver.ts@@ -20,7 +20,7 @@ export class VideoPublishResolver {resolve () {return forkJoin([- listUserChannelsForSelect(this.authService),+ listUserChannelsForSelect(this.authService, { includeCollaborations: true }),this.userService.getMyVideoQuotaUsed(),this.serverService.getVideoPrivacies()]).pipe(map(([ videoChannels, userQuota, privacies ]) => ({ videoChannels, userQuota, privacies } as VideoPublishResolverData)))diff --git a/client/src/app/+videos-publish-manage/shared-manage/captions/video-captions.component.html b/client/src/app/+videos-publish-manage/shared-manage/captions/video-captions.component.htmlindex 702f122c32..e5bacad6fd 100644--- a/client/src/app/+videos-publish-manage/shared-manage/captions/video-captions.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/captions/video-captions.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="captions"></my-global-icon><ng-container i18n>Captions</ng-container>diff --git a/client/src/app/+videos-publish-manage/shared-manage/chapters/video-chapters.component.html b/client/src/app/+videos-publish-manage/shared-manage/chapters/video-chapters.component.htmlindex f73932d8b5..44c341897f 100644--- a/client/src/app/+videos-publish-manage/shared-manage/chapters/video-chapters.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/chapters/video-chapters.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="chapters"></my-global-icon><ng-container i18n>Chapters</ng-container>diff --git a/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts b/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.tsindex 6860dc98fc..c90e32c83e 100644--- a/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts+++ b/client/src/app/+videos-publish-manage/shared-manage/common/video-edit.model.ts@@ -28,6 +28,7 @@ import debug from 'debug'import { Jsonify, SharedUnionFieldsDeep } from 'type-fest'import { VideoCaptionWithPathEdit } from './video-caption-edit.model'import { VideoChaptersEdit } from './video-chapters-edit.model'+import { AuthUser } from '@app/core'const debugLogger = debug('peertube:video-manage:video-edit')@@ -71,7 +72,9 @@ type PlayerSettingsForm = PlayerVideoSettingsUpdate// ----------------------------------------------------------------------------type LoadFromPublishOptions = Required<Pick<VideoCreate, 'channelId' | 'support'>> & Partial<Pick<VideoCreate, 'name'>>+type LoadFromPublishOptions = Required<Pick<VideoCreate, 'channelId' | 'support'>> & Partial<Pick<VideoCreate, 'name'>> & {+ user: AuthUser+}type CreateFromUploadOptions = LoadFromPublishOptions & Required<Pick<VideoCreate, 'name'>>@@ -164,6 +167,9 @@ export class VideoEdit {likes: numberblacklisted: boolean+ ownerAccountId: number+ ownerAccountDisplayName: string+live: Pick<LiveVideo, 'rtmpUrl' | 'rtmpsUrl' | 'streamKey'>videoSource: VideoSource}> = {}@@ -183,6 +189,9 @@ export class VideoEdit {blacklisted: boolean+ ownerAccountId: number+ ownerAccountDisplayName: string+live?: Pick<LiveVideo, 'rtmpUrl' | 'rtmpsUrl' | 'streamKey'>}@@ -288,6 +297,9 @@ export class VideoEdit {this.metadata.views = 0this.metadata.likes = 0+ this.metadata.ownerAccountDisplayName = options.user.account.displayName+ this.metadata.ownerAccountId = options.user.account.id+this.updateAfterChange()}@@ -405,6 +417,9 @@ export class VideoEdit {this.metadata.blacklisted = video.blacklistedthis.metadata.isLive = video.isLive++ this.metadata.ownerAccountDisplayName = video.channel.ownerAccount.displayName+ this.metadata.ownerAccountId = video.channel.ownerAccount.id}loadPluginDataDefaults (pluginDefaults: Record<string, string | boolean>) {@@ -1033,6 +1048,9 @@ export class VideoEdit {duration: this.metadata.duration,blacklisted: this.metadata.blacklisted,+ ownerAccountId: this.metadata.ownerAccountId,+ ownerAccountDisplayName: this.metadata.ownerAccountDisplayName,+live: this.metadata.live}}diff --git a/client/src/app/+videos-publish-manage/shared-manage/common/video-manage-page-common.scss b/client/src/app/+videos-publish-manage/shared-manage/common/video-manage-page-common.scssindex 117270a366..e7a4daa3ae 100644--- a/client/src/app/+videos-publish-manage/shared-manage/common/video-manage-page-common.scss+++ b/client/src/app/+videos-publish-manage/shared-manage/common/video-manage-page-common.scss@@ -2,19 +2,7 @@@use "_mixins" as *;@use "_form-mixins" as *;-h2 {- font-weight: $font-bold;- color: pvar(--fg-350);- line-height: 1;-- @include font-size(2rem);- @include rfs(2rem, margin-bottom);-- my-global-icon {- @include global-icon-size(28px);- @include margin-right(0.5rem);- }-+.form-title {@include on-small-main-col {text-align: center;}diff --git a/client/src/app/+videos-publish-manage/shared-manage/customization/video-customization.component.html b/client/src/app/+videos-publish-manage/shared-manage/customization/video-customization.component.htmlindex b571ab0402..3e1c6c36e0 100644--- a/client/src/app/+videos-publish-manage/shared-manage/customization/video-customization.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/customization/video-customization.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="cog"></my-global-icon><ng-container i18n>Customization</ng-container>diff --git a/client/src/app/+videos-publish-manage/shared-manage/live-settings/video-live-settings.component.html b/client/src/app/+videos-publish-manage/shared-manage/live-settings/video-live-settings.component.htmlindex 02652624c7..8e0d856671 100644--- a/client/src/app/+videos-publish-manage/shared-manage/live-settings/video-live-settings.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/live-settings/video-live-settings.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="live"></my-global-icon><ng-container i18n>Live settings</ng-container>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 45c5a0f6a4..e73c51be2b 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@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="film"></my-global-icon><ng-container i18n>Main information</ng-container>@@ -82,6 +82,25 @@<div><div class="form-group"><label i18n for="channel">Channel</label>++ @if (manageType === 'update') {+ @if (isEditor()) {+ <div class="form-group-description">+ <div i18n>+ Only {{ videoEdit.getVideoAttributes().ownerAccountDisplayName }}'s channels are listed+ </div>++ <div i18n>+ You do not have the right to <a href="https://docs.joinpeertube.org/use/library#change-ownership-of-a-video" target="_blank">transfer ownership <my-global-icon iconName="external-link"></my-global-icon></a> of this video but {{ videoEdit.getVideoAttributes().ownerAccountDisplayName }} can do it+ </div>+ </div>+ } @else {+ <div class="form-group-description" i18n>+ You can also <a href="https://docs.joinpeertube.org/use/library#change-ownership-of-a-video" target="_blank">transfer this video <my-global-icon iconName="external-link"></my-global-icon></a> to another account+ </div>+ }+ }+<my-select-channel class="d-block" inputId="channel" [items]="userChannels" formControlName="channelId"></my-select-channel></div>@@ -166,10 +185,31 @@</div></div>-<div *ngIf="canBeDeleted()">+@if (canBeDeletedOrTransferred()) {<div class="danger-zone mt-5"><h3 class="mb-3" i18n>DANGER ZONE</h3>+ @if (!isEditor()) {+ <div class="form-group">+ <label i18n for="deleteVideo">Change ownership of your video</label>+ <div class="form-group-description" i18n>A modal window will open for you to specify the local account to which you want to transfer your video</div>++ <button class="peertube-button danger-button" (click)="showChangeOwnershipModal()" [disabled]="ownershipRequestSent" i18n>Transfer ownership</button>++ @if (ownershipRequestSent) {+ <my-alert class="d-block mt-3" type="success">+ <ng-container i18n>+ <a routerLink="/my-library/ownership">Ownership change request</a> sent to {{ ownershipRequestSent }}</ng-container>+ </my-alert>+ }+ </div>++ <my-video-change-ownership+ #videoChangeOwnershipModal+ [videoId]="videoEdit.getVideoAttributes().id" (requestSent)="onChangeOwnershipRequest($event)"+ ></my-video-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>@@ -177,4 +217,5 @@<button class="peertube-button danger-button" (click)="deleteVideo()" i18n>Delete</button></div></div>-</div>+}+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 a3856c2a1e..26a6222a1d 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@@ -1,8 +1,9 @@import { CommonModule } from '@angular/common'-import { ChangeDetectorRef, Component, inject, NgZone, OnDestroy, OnInit } from '@angular/core'+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 { ConfirmService, HooksService, Notifier, PluginService, ServerService } from '@app/core'+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 {VIDEO_CATEGORY_VALIDATOR,@@ -18,7 +19,7 @@ import {VIDEO_TAGS_ARRAY_VALIDATOR} from '@app/shared/form-validators/video-validators'import { DynamicFormFieldComponent } from '@app/shared/shared-forms/dynamic-form-field.component'-import { FormReactiveErrors, FormReactiveService, FormReactiveMessages } from '@app/shared/shared-forms/form-reactive.service'+import { FormReactiveErrors, FormReactiveMessages, FormReactiveService } from '@app/shared/shared-forms/form-reactive.service'import { FormValidatorService } from '@app/shared/shared-forms/form-validator.service'import { InputTextComponent } from '@app/shared/shared-forms/input-text.component'import { MarkdownTextareaComponent } from '@app/shared/shared-forms/markdown-textarea.component'@@ -26,6 +27,7 @@ import { PeertubeCheckboxComponent } from '@app/shared/shared-forms/peertube-cheimport { SelectChannelComponent } from '@app/shared/shared-forms/select/select-channel.component'import { SelectOptionsComponent } from '@app/shared/shared-forms/select/select-options.component'import { SelectTagsComponent } from '@app/shared/shared-forms/select/select-tags.component'+import { 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 { VideoService } from '@app/shared/shared-main/video/video.service'@@ -99,11 +101,14 @@ type Form = {ThumbnailManagerComponent,GlobalIconComponent,MarkdownHintComponent,- RouterLink+ RouterLink,+ VideoChangeOwnershipComponent,+ AlertComponent]})export class VideoMainInfoComponent implements OnInit, OnDestroy {private formValidatorService = inject(FormValidatorService)+ private authService = inject(AuthService)private formReactiveService = inject(FormReactiveService)private videoService = inject(VideoService)private serverService = inject(ServerService)@@ -118,6 +123,8 @@ export class VideoMainInfoComponent implements OnInit, OnDestroy {private notifier = inject(Notifier)private router = inject(Router)+ readonly videoChangeOwnershipModal = viewChild<VideoChangeOwnershipComponent>('videoChangeOwnershipModal')+form: FormGroup<Form>formErrors: FormReactiveErrors = {}validationMessages: FormReactiveMessages = {}@@ -154,6 +161,8 @@ export class VideoMainInfoComponent implements OnInit, OnDestroy {privacies: VideoPrivacyType[] = []videoEdit: VideoEdit+ ownershipRequestSent: string+private schedulerInterval: anyprivate updatedSub: Subscription@@ -469,7 +478,7 @@ export class VideoMainInfoComponent implements OnInit, OnDestroy {// ---------------------------------------------------------------------------- canBeDeleted () {+ canBeDeletedOrTransferred () {return !!this.videoEdit.getVideoAttributes().id}@@ -491,4 +500,20 @@ export class VideoMainInfoComponent implements OnInit, OnDestroy {error: err => this.notifier.error(err.message)})}++ // ---------------------------------------------------------------------------++ showChangeOwnershipModal () {+ this.videoChangeOwnershipModal().show()+ }++ onChangeOwnershipRequest (username: string) {+ this.ownershipRequestSent = username+ }++ // ---------------------------------------------------------------------------++ isEditor () {+ return this.videoEdit.getVideoAttributes().ownerAccountId !== this.authService.getUser().account.id+ }}diff --git a/client/src/app/+videos-publish-manage/shared-manage/moderation/video-moderation.component.html b/client/src/app/+videos-publish-manage/shared-manage/moderation/video-moderation.component.htmlindex feeb352e70..c63d6e2e82 100644--- a/client/src/app/+videos-publish-manage/shared-manage/moderation/video-moderation.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/moderation/video-moderation.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="moderation"></my-global-icon><ng-container i18n>Moderation</ng-container>diff --git a/client/src/app/+videos-publish-manage/shared-manage/replace-file/video-replace-file.component.html b/client/src/app/+videos-publish-manage/shared-manage/replace-file/video-replace-file.component.htmlindex 6592ad37a8..0ce6f78a56 100644--- a/client/src/app/+videos-publish-manage/shared-manage/replace-file/video-replace-file.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/replace-file/video-replace-file.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="upload"></my-global-icon><ng-container i18n>Replace file</ng-container>diff --git a/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.html b/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.htmlindex f4262f5c6f..b729bcf56d 100644--- a/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/stats/video-stats.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="stats"></my-global-icon><ng-container i18n>Statistics</ng-container>diff --git a/client/src/app/+videos-publish-manage/shared-manage/studio/video-studio.component.html b/client/src/app/+videos-publish-manage/shared-manage/studio/video-studio.component.htmlindex b2e565b394..bb7ce8d5f6 100644--- a/client/src/app/+videos-publish-manage/shared-manage/studio/video-studio.component.html+++ b/client/src/app/+videos-publish-manage/shared-manage/studio/video-studio.component.html@@ -1,4 +1,4 @@-<h2>+<h2 class="form-title"><my-global-icon iconName="studio"></my-global-icon><ng-container i18n>Studio</ng-container>diff --git a/client/src/app/+videos-publish-manage/shared-manage/video-manage-container.component.scss b/client/src/app/+videos-publish-manage/shared-manage/video-manage-container.component.scssindex be0e86e818..15e4925cc0 100644--- a/client/src/app/+videos-publish-manage/shared-manage/video-manage-container.component.scss+++ b/client/src/app/+videos-publish-manage/shared-manage/video-manage-container.component.scss@@ -22,7 +22,7 @@top: pvar(--header-height);background-color: pvar(--bg);// On top of input group addons- z-index: 3;+ z-index: 6;}.video-actions {diff --git a/client/src/app/core/auth/auth-user.model.ts b/client/src/app/core/auth/auth-user.model.tsindex 690d818a2a..f4edd3008f 100644--- a/client/src/app/core/auth/auth-user.model.ts+++ b/client/src/app/core/auth/auth-user.model.ts@@ -1,4 +1,5 @@import { User } from '@app/core/users/user.model'+import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'import { hasUserRight } from '@peertube/peertube-core-utils'import {MyUserSpecialPlaylist,@@ -12,12 +13,14 @@ import { OAuthUserTokens } from '@root-helpers/users'export class AuthUser extends User implements ServerMyUserModel {oauthTokens: OAuthUserTokensspecialPlaylists: MyUserSpecialPlaylist[]+ videoChannelCollaborations?: ServerMyUserModel['videoChannelCollaborations']constructor (userHash: Partial<ServerMyUserModel>, hashTokens: Partial<OAuthUserTokens>) {super(userHash)this.oauthTokens = new OAuthUserTokens(hashTokens)this.specialPlaylists = userHash.specialPlaylists+ this.videoChannelCollaborations = userHash.videoChannelCollaborations}getAccessToken () {@@ -49,4 +52,12 @@ export class AuthUser extends User implements ServerMyUserModel {// I'm a moderator: I can only manage usersreturn user.role.id === UserRole.USER}++ isCollaboratingToChannels () {+ return this.videoChannelCollaborations.length !== 0+ }++ isEditorOfChannel (channel: Pick<VideoChannel, 'id'>) {+ return this.videoChannelCollaborations.some(c => c.id === channel.id)+ }}diff --git a/client/src/app/core/menu/menu.service.ts b/client/src/app/core/menu/menu.service.tsindex b1e73733fd..ee3018f04c 100644--- a/client/src/app/core/menu/menu.service.ts+++ b/client/src/app/core/menu/menu.service.ts@@ -46,7 +46,13 @@ export class MenuService {}private hasMenuCollapsedByUrl (url: string) {- const collapsedBaseUrls = [ '/videos/publish', '/videos/manage/' ]+ const collapsedBaseUrls = [+ '/videos/publish',+ '/videos/manage/',+ '/admin/settings/config',+ '/my-library/video-channels/manage',+ '/my-library/video-channels/create'+ ]for (const collapsedBaseUrl of collapsedBaseUrls) {if (url.startsWith(collapsedBaseUrl)) {diff --git a/client/src/app/core/routing/peertube-router.service.ts b/client/src/app/core/routing/peertube-router.service.tsindex 5ea78bb75c..6308c7ba33 100644--- a/client/src/app/core/routing/peertube-router.service.ts+++ b/client/src/app/core/routing/peertube-router.service.ts@@ -1,7 +1,6 @@import { Injectable, inject } from '@angular/core'import { ActivatedRoute, Event, NavigationEnd, Params, Router, Scroll } from '@angular/router'import { filter } from 'rxjs/operators'-import { ServerService } from '../server'export const enum RouterSetting {NONE = 0,@@ -10,9 +9,7 @@ export const enum RouterSetting {@Injectable()export class PeerTubeRouterService {- private route = inject(ActivatedRoute)private router = inject(Router)- private server = inject(ServerService)getNavigationEndEvents () {return this.router.events.pipe(diff --git a/client/src/app/core/theme/primeng/components/multiselect.ts b/client/src/app/core/theme/primeng/components/multiselect.tsindex 5ad65cf013..8a632d3647 100644--- a/client/src/app/core/theme/primeng/components/multiselect.ts+++ b/client/src/app/core/theme/primeng/components/multiselect.ts@@ -13,7 +13,7 @@ export default {invalidBorderColor: '{form.field.invalid.border.color}',color: '{form.field.color}',disabledColor: '{form.field.disabled.color}',- placeholderColor: '{form.field.placeholder.color}',+ placeholderColor: '{form.field.color}',invalidPlaceholderColor: '{form.field.invalid.placeholder.color}',shadow: '{form.field.shadow}',paddingX: '{form.field.padding.x}',diff --git a/client/src/app/core/users/user.model.ts b/client/src/app/core/users/user.model.tsindex 8fc423bcb0..58cffb9e77 100644--- a/client/src/app/core/users/user.model.ts+++ b/client/src/app/core/users/user.model.ts@@ -4,14 +4,13 @@ import {ActorImage,HTMLServerConfig,NSFWPolicyType,- User as UserServerModel,UserAdminFlag,UserAdminFlagType,UserNotificationSetting,UserRightType,UserRole,UserRoleType,- VideoChannel+ User as UserServerModel} from '@peertube/peertube-models'export class User implements UserServerModel {@@ -61,7 +60,8 @@ export class User implements UserServerModel {account: AccountnotificationSettings?: UserNotificationSetting- videoChannels?: VideoChannel[]++ videoChannels?: UserServerModel['videoChannels']blocked: booleanblockedReason?: stringdiff --git a/client/src/app/header/notification-dropdown.component.html b/client/src/app/header/notification-dropdown.component.htmlindex ec4bb4c348..f1ece7fe67 100644--- a/client/src/app/header/notification-dropdown.component.html+++ b/client/src/app/header/notification-dropdown.component.html@@ -1,6 +1,9 @@<ng-template #notificationNumber>- <div *ngIf="unreadNotifications > 0 && unreadNotifications < 100" class="unread-notifications">{{ unreadNotifications }}</div>- <div *ngIf="unreadNotifications >= 100" class="unread-notifications">99+</div>+ @if (unreadNotifications > 0 && unreadNotifications < 100) {+ <div class="unread-notifications">{{ unreadNotifications }}</div>+ } @else if (unreadNotifications >= 100) {+ <div class="unread-notifications">99+</div>+ }</ng-template><ng-template #notificationIcon>@@ -64,6 +67,7 @@<my-user-notifications[ignoreLoadingBar]="true" [infiniteScroll]="false" [itemsPerPage]="10"[markAllAsReadSubject]="markAllAsReadSubject" (notificationsLoaded)="onNotificationLoaded()"+ [userNotificationReload]="userNotificationReload"></my-user-notifications>}diff --git a/client/src/app/helpers/utils/channel.ts b/client/src/app/helpers/utils/channel.tsindex 3b6e894155..94369ff9c6 100644--- a/client/src/app/helpers/utils/channel.ts+++ b/client/src/app/helpers/utils/channel.ts@@ -1,43 +1,27 @@-import { minBy } from '@peertube/peertube-core-utils'+import { minBy, sortBy } from '@peertube/peertube-core-utils'import { VideoChannel } from '@peertube/peertube-models'import { first, map } from 'rxjs/operators'-import { SelectChannelItem } from 'src/types/select-options-item.model'import { AuthService } from '../../core/auth'-function listUserChannelsForSelect (authService: AuthService) {+export function listUserChannelsForSelect (authService: AuthService, options: { includeCollaborations: boolean }) {return authService.userInformationLoaded.pipe(first(),map(() => {const user = authService.getUser()- if (!user) return undefined- const videoChannels = user.videoChannels- if (Array.isArray(videoChannels) === false) return undefined+ const allChannels = options.includeCollaborations+ ? [+ ...formatChannels(user.videoChannels, { editor: false }),+ ...formatChannels(user.videoChannelCollaborations, { editor: true })+ ]+ : formatChannels(user.videoChannels, { editor: false })- return videoChannels- .sort((a, b) => {- if (a.updatedAt < b.updatedAt) return 1- if (a.updatedAt > b.updatedAt) return -1- return 0- })- .map(c =>- ({- id: c.id,- name: c.name,- label: c.displayName,- support: c.support,- avatarPath: getAvatarPath(c)- }) as SelectChannelItem- )+ return sortBy(allChannels, 'updatedAt').reverse()}))}-export {- listUserChannelsForSelect-}-// ---------------------------------------------------------------------------function getAvatarPath (c: VideoChannel) {@@ -45,3 +29,17 @@ function getAvatarPath (c: VideoChannel) {return minBy(c.avatars, 'width')?.path || c.avatars[0].path}++function formatChannels (channel: (VideoChannel & { ownerAccountId?: number })[], { editor }: { editor: boolean }) {+ return channel+ .map(c => ({+ id: c.id,+ name: c.name,+ label: c.displayName,+ support: c.support,+ editor,+ avatarPath: getAvatarPath(c),+ ownerAccountId: c.ownerAccountId,+ updatedAt: c.updatedAt+ }))+}diff --git a/client/src/app/menu/menu.component.scss b/client/src/app/menu/menu.component.scssindex ce4ce3d6ee..b324c91686 100644--- a/client/src/app/menu/menu.component.scss+++ b/client/src/app/menu/menu.component.scss@@ -133,7 +133,7 @@&:hover,&:focus-visible {opacity: 1;- background-color: pvar(--menu-bg-550);+ background-color: pvar(--menu-bg-450);}my-global-icon {diff --git a/client/src/app/shared/form-validators/form-validator.model.ts b/client/src/app/shared/form-validators/form-validator.model.tsindex aaa642b71e..035b4a9865 100644--- a/client/src/app/shared/form-validators/form-validator.model.ts+++ b/client/src/app/shared/form-validators/form-validator.model.ts@@ -23,7 +23,7 @@ export type FormDefaultTyped<Form> = Partial<UnwrapForm<Form>>// ---------------------------------------------------------------------------export type FormReactiveMessages = {- [id: string]: { [name: string]: string } | FormReactiveMessages | FormReactiveMessages[]+ [id: string]: { [name: string]: string } | FormReactiveMessages | FormReactiveMessages[] | string}export type FormReactiveMessagesTyped<Form> = Partial<ReplaceForm<Form, string>>diff --git a/client/src/app/shared/form-validators/video-channel-validators.ts b/client/src/app/shared/form-validators/video-channel-validators.tsindex b12b3caafb..e022162140 100644--- a/client/src/app/shared/form-validators/video-channel-validators.ts+++ b/client/src/app/shared/form-validators/video-channel-validators.ts@@ -3,7 +3,7 @@ import { BuildFormValidator } from './form-validator.model'import { USER_USERNAME_VALIDATOR } from './user-validators'export const VIDEO_CHANNEL_NAME_VALIDATOR: BuildFormValidator = {- // Use the same constraints than user usernmae+ // Use the same constraints than user usernameVALIDATORS: USER_USERNAME_VALIDATOR.VALIDATORS,MESSAGES: {diff --git a/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.ts b/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.tsindex f481a71a4b..3e1d4dd467 100644--- a/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.ts+++ b/client/src/app/shared/shared-actor-image-edit/actor-banner-edit.component.ts@@ -1,5 +1,5 @@import { CommonModule, NgTemplateOutlet } from '@angular/common'-import { Component, ElementRef, OnInit, booleanAttribute, inject, input, output, viewChild } from '@angular/core'+import { Component, ElementRef, OnChanges, OnInit, booleanAttribute, inject, input, output, viewChild } from '@angular/core'import { SafeResourceUrl } from '@angular/platform-browser'import { Notifier, ServerService } from '@app/core'import { NgbDropdownModule, NgbPopover, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'@@ -16,7 +16,7 @@ import { GlobalIconComponent } from '../shared-icons/global-icon.component'],imports: [ CommonModule, NgbTooltipModule, NgTemplateOutlet, NgbDropdownModule, GlobalIconComponent ]})-export class ActorBannerEditComponent implements OnInit {+export class ActorBannerEditComponent implements OnInit, OnChanges {private serverService = inject(ServerService)private notifier = inject(Notifier)@@ -45,6 +45,10 @@ export class ActorBannerEditComponent implements OnInit {}, extensions: ${this.bannerExtensions}`}+ ngOnChanges () {+ this.preview = undefined+ }+onBannerChange () {const bannerfile = this.bannerfileInput().nativeElement.files[0]if (bannerfile.size > this.maxBannerSize) {diff --git a/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.html b/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.htmlnew file mode 100644index 0000000000..9a9f5b491c--- /dev/null+++ b/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.html@@ -0,0 +1,23 @@+<div class="root ">+ @if (showChannel()) {+ <my-actor-avatar+ class="channel"+ [actor]="channel()" actorType="channel"+ [size]="size()"+ [title]="linkTitle"+ [internalHref]="internalHref()"+ ></my-actor-avatar>+ }++ @if (showAccount()) {+ <my-actor-avatar+ class="account"+ [class.second-avatar]="showChannel()"+ [actor]="account()" actorType="account"+ [size]="getAccountSize()"+ [title]="linkTitle"+ [internalHref]="internalHref()"+ >+ </my-actor-avatar>+ }+</div>diff --git a/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.scss b/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.scsssimilarity index 75%rename from client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.scssrename to client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.scssindex 88496685f6..ab22034288 100644--- a/client/src/app/+video-watch/shared/metadata/video-avatar-channel.component.scss+++ b/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.scss@@ -1,14 +1,12 @@-@use '_mixins' as *;+@use "_mixins" as *;-.wrapper {+.root {position: relative;margin-bottom: 5px;@include margin-right(5px);.second-avatar {- height: 60%;- width: 60%;position: absolute;bottom: -5px;right: -5px;diff --git a/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.ts b/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.tsnew file mode 100644index 0000000000..4913662f73--- /dev/null+++ b/client/src/app/shared/shared-actor-image/account-on-channel-avatar.component.ts@@ -0,0 +1,38 @@+import { CommonModule } from '@angular/common'+import { Component, OnInit, input, numberAttribute } from '@angular/core'+import { ActorAvatarComponent, ActorAvatarInput } from '@app/shared/shared-actor-image/actor-avatar.component'++@Component({+ selector: 'my-account-on-channel-avatar',+ templateUrl: './account-on-channel-avatar.component.html',+ styleUrls: [ './account-on-channel-avatar.component.scss' ],+ imports: [ CommonModule, ActorAvatarComponent ]+})+export class AccountOnChannelAvatarComponent implements OnInit {+ readonly account = input.required<ActorAvatarInput>()+ readonly channel = input.required<ActorAvatarInput>()+ readonly internalHref = input<string | any[]>(undefined)++ readonly showAccount = input(true)+ readonly showChannel = input(true)++ readonly size = input(35, { transform: numberAttribute })++ linkTitle = ''++ ngOnInit () {+ if (this.internalHref()) {+ if (this.showChannel()) {+ this.linkTitle = $localize`Go to ${this.channel().name} channel page`+ } else if (this.showAccount()) {+ this.linkTitle = $localize`Go to ${this.account().name} account page`+ }+ }+ }++ getAccountSize () {+ return this.showChannel()+ ? Math.round(this.size() * 0.6)+ : this.size()+ }+}diff --git a/client/src/app/shared/shared-actor-image/actor-avatar.component.html b/client/src/app/shared/shared-actor-image/actor-avatar.component.htmlindex 7cddb9bd82..77cee2b26a 100644--- a/client/src/app/shared/shared-actor-image/actor-avatar.component.html+++ b/client/src/app/shared/shared-actor-image/actor-avatar.component.html@@ -1,21 +1,23 @@<ng-template #img>- <img #avatarEl *ngIf="displayImage()" [ngClass]="classes" [src]="previewImage() || avatarUrl || defaultAvatarUrl" alt="" />-- <div #avatarEl *ngIf="displayActorInitial()" [ngClass]="classes">- <span>{{ getActorInitial() }}</span>- </div>-- <div #avatarEl *ngIf="displayPlaceholder()" [ngClass]="classes"></div>+ @if (displayImage()) {+ <img #avatarEl [ngClass]="classes" [src]="previewImage() || avatarUrl || defaultAvatarUrl" alt="" />+ } @else if (displayActorInitial()) {+ <div #avatarEl [ngClass]="classes">+ <span>{{ getActorInitial() }}</span>+ </div>+ } @else if (displayPlaceholder()) {+ <div #avatarEl [ngClass]="classes"></div>+ }</ng-template>-<a *ngIf="actor() && href()" [href]="href()" target="_blank" rel="noopener noreferrer" [title]="getTitle()">- <ng-template *ngTemplateOutlet="img"></ng-template>-</a>--<a *ngIf="actor() && internalHref()" [routerLink]="internalHref()" [title]="getTitle()">- <ng-template *ngTemplateOutlet="img"></ng-template>-</a>--<ng-container *ngIf="!actor() || (!href() && !internalHref())">+@if (actor() && href()) {+ <a [href]="href()" target="_blank" rel="noopener noreferrer" [title]="getTitle()">+ <ng-template *ngTemplateOutlet="img"></ng-template>+ </a>+} @else if (actor() && internalHref()) {+ <a [routerLink]="internalHref()" [title]="getTitle()">+ <ng-template *ngTemplateOutlet="img"></ng-template>+ </a>+} @else {<ng-template *ngTemplateOutlet="img"></ng-template>-</ng-container>+}diff --git a/client/src/app/shared/shared-actor-image/actor-avatar.component.scss b/client/src/app/shared/shared-actor-image/actor-avatar.component.scssindex 922bab361e..349a7b7daf 100644--- a/client/src/app/shared/shared-actor-image/actor-avatar.component.scss+++ b/client/src/app/shared/shared-actor-image/actor-avatar.component.scss@@ -1,5 +1,5 @@-@use '_variables' as *;-@use '_mixins' as *;+@use "_variables" as *;+@use "_mixins" as *;.avatar {// Defined in component@@ -34,6 +34,7 @@ a {justify-content: center;// Defined in componentfont-size: var(--co-font-size);+ line-height: var(--co-avatar-size);&.blue {background-color: #009FD4;diff --git a/client/src/app/shared/shared-actor-image/actor-avatar.component.ts b/client/src/app/shared/shared-actor-image/actor-avatar.component.tsindex 980bb55118..9eaf7552ec 100644--- a/client/src/app/shared/shared-actor-image/actor-avatar.component.ts+++ b/client/src/app/shared/shared-actor-image/actor-avatar.component.ts@@ -1,4 +1,4 @@-import { NgClass, NgIf, NgTemplateOutlet } from '@angular/common'+import { CommonModule, NgTemplateOutlet } from '@angular/common'import { Component, ElementRef, OnChanges, OnInit, booleanAttribute, inject, input, numberAttribute, viewChild } from '@angular/core'import { RouterLink } from '@angular/router'import { objectKeysTyped } from '@peertube/peertube-core-utils'@@ -11,19 +11,21 @@ export type ActorAvatarInput = {avatars: { width: number, url?: string, path: string }[]}+export type ActorAvatarType = 'channel' | 'account' | 'instance' | 'unlogged'+@Component({selector: 'my-actor-avatar',styleUrls: [ './actor-avatar.component.scss' ],templateUrl: './actor-avatar.component.html',- imports: [ NgIf, NgClass, NgTemplateOutlet, RouterLink ]+ imports: [ CommonModule, NgTemplateOutlet, RouterLink ]})export class ActorAvatarComponent implements OnInit, OnChanges {private el = inject(ElementRef)readonly avatarEl = viewChild<ElementRef>('avatarEl')- readonly actor = input<ActorAvatarInput>(undefined)- readonly actorType = input<'channel' | 'account' | 'instance' | 'unlogged'>(undefined)+ readonly actor = input.required<ActorAvatarInput>()+ readonly actorType = input.required<ActorAvatarType>()readonly previewImage = input<string>(undefined)diff --git a/client/src/app/shared/shared-forms/advanced-input-filter.component.ts b/client/src/app/shared/shared-forms/advanced-input-filter.component.tsindex d70ebbf964..677f157b60 100644--- a/client/src/app/shared/shared-forms/advanced-input-filter.component.ts+++ b/client/src/app/shared/shared-forms/advanced-input-filter.component.ts@@ -152,7 +152,7 @@ export class AdvancedInputFilterComponent implements OnInit, AfterViewInit {private setQueryParams (search: string) {const searchParams = search? { search: search.trim() }- : {}+ : { search: undefined }this.router.navigate([ '.' ], { relativeTo: this.route, queryParams: { ...this.route.snapshot.queryParams, ...searchParams } })}diff --git a/client/src/app/shared/shared-forms/select/select-channel.component.ts b/client/src/app/shared/shared-forms/select/select-channel.component.tsindex bb34df038a..e4ef64503e 100644--- a/client/src/app/shared/shared-forms/select/select-channel.component.ts+++ b/client/src/app/shared/shared-forms/select/select-channel.component.ts@@ -4,6 +4,7 @@ import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/fimport { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'import { SelectChannelItem, SelectOptionsItem } from '../../../../types/select-options-item.model'import { SelectOptionsComponent } from './select-options.component'+import { CollaboratorStateComponent } from '@app/shared/shared-main/channel/collaborator-state.component'@Component({selector: 'my-select-channel',@@ -17,7 +18,13 @@ import { SelectOptionsComponent } from './select-options.component'(ngModelChange)="onModelChange()"[filter]="channels && channels.length > 5"- ></my-select-options>+ >+ <ng-template #itemExtra let-item>+ @if (item.editor) {+ <my-collaborator-state class="lh-1 ms-2" type="accepted" disableTooltip="true"></my-collaborator-state>+ }+ </ng-template>+ </my-select-options>`,providers: [{@@ -26,7 +33,7 @@ import { SelectOptionsComponent } from './select-options.component'multi: true}],- imports: [ FormsModule, CommonModule, SelectOptionsComponent ]+ imports: [ FormsModule, CommonModule, SelectOptionsComponent, CollaboratorStateComponent ]})export class SelectChannelComponent implements ControlValueAccessor, OnChanges {readonly inputId = input.required<string>()diff --git a/client/src/app/shared/shared-forms/select/select-options.component.html b/client/src/app/shared/shared-forms/select/select-options.component.htmlindex 536cd9757c..4588d1762e 100644--- a/client/src/app/shared/shared-forms/select/select-options.component.html+++ b/client/src/app/shared/shared-forms/select/select-options.component.html@@ -23,14 +23,22 @@fluid="true"><ng-template #itemTemplate let-item let-description="description">- @if (customItemTemplate) {- <ng-template [ngTemplateOutlet]="customItemTemplate" [ngTemplateOutletContext]="{ $implicit: item }"></ng-template>+ @if (selectOptionTemplate) {+ <ng-template [ngTemplateOutlet]="selectOptionTemplate" [ngTemplateOutletContext]="{ $implicit: item }"></ng-template>++ @if (itemExtraTemplate) {+ <ng-template [ngTemplateOutlet]="itemExtraTemplate" [ngTemplateOutletContext]="{ $implicit: item }"></ng-template>+ }} @else {<div><div class="d-flex align-items-center item-label custom-item"><img *ngIf="item.imageUrl" alt="" class="me-2" [src]="item.imageUrl" /><span class="ellipsis" [ngClass]="item.classes">{{ item.label }}</span>++ @if (itemExtraTemplate) {+ <ng-template [ngTemplateOutlet]="itemExtraTemplate" [ngTemplateOutletContext]="{ $implicit: item }"></ng-template>+ }</div><span *ngIf="description" class="muted">{{ description }}</span>diff --git a/client/src/app/shared/shared-forms/select/select-options.component.ts b/client/src/app/shared/shared-forms/select/select-options.component.tsindex 0c2039a250..0b500f9dd3 100644--- a/client/src/app/shared/shared-forms/select/select-options.component.ts+++ b/client/src/app/shared/shared-forms/select/select-options.component.ts@@ -1,10 +1,9 @@import { CommonModule } from '@angular/common'import {- AfterContentInit,booleanAttribute,ChangeDetectorRef,Component,- contentChildren,+ ContentChild,forwardRef,HostListener,inject,@@ -13,7 +12,6 @@ import {TemplateRef} from '@angular/core'import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'-import { PeerTubeTemplateDirective } from '@app/shared/shared-main/common/peertube-template.directive'import { SelectModule } from 'primeng/select'import { SelectOptionsItem } from '../../../../types/select-options-item.model'@@ -32,7 +30,7 @@ import { SelectOptionsItem } from '../../../../types/select-options-item.model'],imports: [ SelectModule, FormsModule, CommonModule ]})-export class SelectOptionsComponent implements AfterContentInit, ControlValueAccessor {+export class SelectOptionsComponent implements ControlValueAccessor {private cd = inject(ChangeDetectorRef)readonly items = input<SelectOptionsItem[]>([])@@ -45,22 +43,17 @@ export class SelectOptionsComponent implements AfterContentInit, ControlValueAccreadonly virtualScroll = input(false, { transform: booleanAttribute })readonly virtualScrollItemSize = input(39, { transform: numberAttribute })- readonly templates = contentChildren(PeerTubeTemplateDirective)+ @ContentChild('selectOption', { descendants: false })+ selectOptionTemplate: TemplateRef<any>- customItemTemplate: TemplateRef<any>+ @ContentChild('itemExtra', { descendants: false })+ itemExtraTemplate: TemplateRef<any>selectedId: number | stringdisabled = falsewroteValue: number | string- ngAfterContentInit () {- {- const t = this.templates().find(t => t.name() === 'item')- if (t) this.customItemTemplate = t.template- }- }-propagateChange = (_: any) => {// empty}diff --git a/client/src/app/shared/shared-forms/user-auto-complete.component.html b/client/src/app/shared/shared-forms/user-auto-complete.component.htmlnew file mode 100644index 0000000000..40b399538f--- /dev/null+++ b/client/src/app/shared/shared-forms/user-auto-complete.component.html@@ -0,0 +1,4 @@+<p-autoComplete+ [inputId]="inputName()" [suggestions]="suggestions" (completeMethod)="completeMethod($event)" fluid="true"+ [(ngModel)]="value" (ngModelChange)="propagateChange($event)"+></p-autoComplete>diff --git a/client/src/app/shared/shared-forms/user-auto-complete.component.ts b/client/src/app/shared/shared-forms/user-auto-complete.component.tsnew file mode 100644index 0000000000..ad43e17432--- /dev/null+++ b/client/src/app/shared/shared-forms/user-auto-complete.component.ts@@ -0,0 +1,56 @@+import { CommonModule } from '@angular/common'+import { Component, forwardRef, inject, input, model } from '@angular/core'+import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms'+import { Notifier, UserService } from '@app/core'+import { AutoCompleteModule } from 'primeng/autocomplete'+import { InputMaskModule } from 'primeng/inputmask'++@Component({+ selector: 'my-user-auto-complete',+ templateUrl: './user-auto-complete.component.html',+ providers: [+ {+ provide: NG_VALUE_ACCESSOR,+ useExisting: forwardRef(() => UserAutoCompleteComponent),+ multi: true+ }+ ],+ imports: [ CommonModule, InputMaskModule, FormsModule, AutoCompleteModule ]+})+export class UserAutoCompleteComponent implements ControlValueAccessor {+ private userService = inject(UserService)+ private notifier = inject(Notifier)++ readonly inputName = input<string>(undefined)++ readonly value = model('')++ suggestions: string[] = []++ propagateChange = (_: any) => {+ // empty+ }++ writeValue (value: string) {+ this.value.set(value)+ }++ registerOnChange (fn: (_: any) => void) {+ this.propagateChange = fn+ }++ registerOnTouched () {+ // Unused+ }++ completeMethod (event: { query: string }) {+ const query = event.query++ this.userService.autocomplete(query)+ .subscribe({+ next: usernames => this.suggestions = usernames,++ error: err => this.notifier.error(err.message)+ })+ }+}diff --git a/client/src/app/shared/shared-main/buttons/action-dropdown.component.html b/client/src/app/shared/shared-main/buttons/action-dropdown.component.htmlindex afe1d8d4a0..b368ef67a8 100644--- a/client/src/app/shared/shared-main/buttons/action-dropdown.component.html+++ b/client/src/app/shared/shared-main/buttons/action-dropdown.component.html@@ -1,74 +1,109 @@<div- *ngIf="areActionsDisplayed(actions(), entry())" class="dropdown-root"- ngbDropdown (openChange)="openChange.emit($event)" [placement]="placement()" [container]="container()"+ *ngIf="areActionsDisplayed(actions(), entry())"+ class="dropdown-root"+ ngbDropdown+ (openChange)="openChange.emit($event)"+ [placement]="placement()"+ [container]="container()"><button- class="action-button peertube-button border-0"- [ngClass]="{ 'icon-only': !label(), 'peertube-button-small': buttonSize() === 'small', 'secondary-button': buttonStyled() && theme() === 'secondary', 'primary-button': buttonStyled() && theme() === 'primary' }"- ngbDropdownToggle aria-label="Open actions" i18n-aria-label+ class="action-button border-0"+ [ngClass]="buttonClasses"+ ngbDropdownToggle+ aria-label="Open actions"+ i18n-aria-label>@if (label()) {- <span class="dropdown-toggle">{{ label() }}</span>- } @else if (buttonDirection() === 'horizontal') {+ <span class="dropdown-toggle me-2">+ <span class="d-inline-flex align-items-center gap-2">+ {{ label() }}++ @if (labelExtra) {+ <ng-template *ngTemplateOutlet="labelExtra"></ng-template>+ }+ </span>+ </span>++ <div class="chevron-down"></div>+ } @else if (buttonIcon() === 'more-horizontal') {<my-global-icon class="more-icon" iconName="more-horizontal"></my-global-icon>- } @else if (buttonDirection() === 'vertical') {+ } @else if (buttonIcon() === 'more-vertical') {<my-global-icon class="more-icon" iconName="more-vertical"></my-global-icon>+ } @else if (buttonIcon() === 'chevron-down') {+ <div class="chevron-down"></div>}</button><div ngbDropdownMenu class="dropdown-menu">- <ng-container *ngFor="let actions of getActions()">-- <ng-container *ngFor="let action of actions">- <div [ngClass]="action.class" *ngIf="isBlockDisplayed(actions, action, entry())">+ @for (actions of getActions(); track $index) {+ @for (action of actions; track action.label) {+ @if (isBlockDisplayed(actions, action, entry())) {+ <div [ngClass]="action.class">+ <ng-template #templateActionLabel let-action>+ @if (action.iconName) {+ <my-global-icon [iconName]="action.iconName" [ngClass]="'icon-' + action.iconName" aria-hidden="true"></my-global-icon>+ } @else if (action.actorAvatar) {+ <my-actor-avatar size="24" [actor]="action.actorAvatar.actor" [actorType]="action.actorAvatar.type"></my-actor-avatar>+ }- <ng-template #templateActionLabel let-action>- <my-global-icon *ngIf="action.iconName" [iconName]="action.iconName" [ngClass]="'icon-' + action.iconName" aria-hidden="true"></my-global-icon>+ <div class="item-label">+ <span class="d-inline-flex align-items-center">+ {{ action.label }}- <div class="item-label">- <span>- {{ action.label }}+ @if (dropdownItemExtra) {+ <ng-template *ngTemplateOutlet="dropdownItemExtra; context: { action }"></ng-template>+ }- <my-global-icon- *ngIf="action.ownerOrModeratorPrivilege && action.ownerOrModeratorPrivilege()" iconName="shield"- class="owner-moderator-privilege"- [ngbTooltip]="action.ownerOrModeratorPrivilege()"- ></my-global-icon>- </span>+ <my-global-icon+ *ngIf="action.ownerOrModeratorPrivilege && action.ownerOrModeratorPrivilege()"+ iconName="shield"+ class="owner-moderator-privilege"+ [ngbTooltip]="action.ownerOrModeratorPrivilege()"+ ></my-global-icon>+ </span>- <small class="muted" *ngIf="action.description">{{ action.description }}</small>- </div>- </ng-template>+ <small class="muted action-description" *ngIf="action.description">{{ action.description }}</small>+ </div>+ </ng-template>- @if (action.linkBuilder) {- @if (!action.isHeader) {- <a- [ngClass]="{ 'with-icon': !!action.iconName }"- class="dropdown-item" [routerLink]="action.linkBuilder(entry())" [queryParams]="getQueryParams(action, entry())" [title]="action.title || ''"- >- <ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>- </a>+ @if (action.linkBuilder) {+ @if (!action.isHeader) {+ <a+ [ngClass]="{ 'with-icon': !!action.iconName || !!action.actorAvatar }"+ class="dropdown-item"+ [routerLink]="action.linkBuilder(entry())"+ [queryParams]="getQueryParams(action, entry())"+ [title]="action.title || ''"+ >+ <ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>+ </a>+ }+ } @else {+ @if (!action.isHeader) {+ <span+ [ngClass]="{ 'with-icon': !!action.iconName || !!action.actorAvatar }"+ class="custom-action dropdown-item"+ tabindex="0"+ role="button"+ [title]="action.title || ''"+ (click)="action.handler(entry())"+ (keyup.enter)="action.handler(entry())"+ >+ <ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>+ </span>+ } @else if (areActionsDisplayed(actions, entry())) {+ <h6 [ngClass]="{ 'with-icon': !!action.iconName || !!action.actorAvatar }" class="dropdown-header" [title]="action.title || ''">+ <ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>+ </h6>+ }}- } @else {- @if (!action.isHeader) {- <span- [ngClass]="{ 'with-icon': !!action.iconName }"- class="custom-action dropdown-item" tabindex="0" role="button" [title]="action.title || ''"- (click)="action.handler(entry())" (keyup.enter)="action.handler(entry())"- >- <ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>- </span>- } @else if (areActionsDisplayed(actions, entry())) {- <h6 [ngClass]="{ 'with-icon': !!action.iconName }" class="dropdown-header" [title]="action.title || ''">- <ng-container *ngTemplateOutlet="templateActionLabel; context:{ $implicit: action }"></ng-container>- </h6>- }- }- </div>- </ng-container>+ </div>+ }+ }- <div *ngIf="areActionsDisplayed(actions, entry())" class="dropdown-divider"></div>-- </ng-container>+ @if (areActionsDisplayed(actions, entry())) {+ <div class="dropdown-divider"></div>+ }+ }</div></div>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 a74d8009f7..83df387ee8 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@@ -1,6 +1,6 @@-@use '_variables' as *;-@use '_mixins' as *;-@use '_button-mixins' as *;+@use "_variables" as *;+@use "_mixins" as *;+@use "_button-mixins" as *;.dropdown-divider:last-child {display: none;@@ -18,9 +18,28 @@}}-.dropdown-toggle::after {- position: relative;- top: 1px;+// So we can style the chevron color+button {+ color: inherit;+}++.chevron-down {+ color: inherit;+}++.dropdown-toggle {+ color: pvar(--fg-300);++ &:hover,+ &:active,+ &:focus,+ &:focus-visible {+ color: pvar(--fg);+ }++ &::after {+ display: none;+ }}.dropdown-menu {@@ -54,10 +73,11 @@display: flex;flex-direction: column;min-width: 1px;+}- > * {- @include ellipsis;- }+.action-description {+ max-width: 300px;+ white-space: normal;}.owner-moderator-privilege {diff --git a/client/src/app/shared/shared-main/buttons/action-dropdown.component.ts b/client/src/app/shared/shared-main/buttons/action-dropdown.component.tsindex 55ba604184..635f474aa8 100644--- a/client/src/app/shared/shared-main/buttons/action-dropdown.component.ts+++ b/client/src/app/shared/shared-main/buttons/action-dropdown.component.ts@@ -1,13 +1,23 @@-import { ChangeDetectionStrategy, Component, input, output } from '@angular/core'+import { CommonModule, NgTemplateOutlet } from '@angular/common'+import { booleanAttribute, ChangeDetectionStrategy, Component, ContentChild, input, OnChanges, output, TemplateRef } from '@angular/core'import { Params, RouterLink } from '@angular/router'+import { ActorAvatarComponent, ActorAvatarInput, ActorAvatarType } from '@app/shared/shared-actor-image/actor-avatar.component'import { GlobalIconName } from '@app/shared/shared-icons/global-icon.component'+import { NgbDropdownMenu, NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'import { GlobalIconComponent } from '../../shared-icons/global-icon.component'-import { NgbDropdown, NgbDropdownToggle, NgbDropdownMenu, NgbTooltip } from '@ng-bootstrap/ng-bootstrap'-import { NgIf, NgClass, NgFor, NgTemplateOutlet } from '@angular/common'+import { CollaboratorStateType } from '../channel/collaborator-state.component'++export type DropdownAction<T, D = never> = {+ label: string-export type DropdownAction<T> = {- label?: stringiconName?: GlobalIconName++ actorAvatar?: {+ actor: ActorAvatarInput+ type: ActorAvatarType+ }+ collaboratorBadge?: CollaboratorStateType+description?: stringtitle?: stringhandler?: (a: T) => any@@ -21,11 +31,13 @@ export type DropdownAction<T> = {isHeader?: booleanownerOrModeratorPrivilege?: () => string++ data?: D}export type DropdownButtonSize = 'normal' | 'small'export type DropdownTheme = 'primary' | 'secondary'-export type DropdownDirection = 'horizontal' | 'vertical'+export type DropdownButtonIcon = 'more-horizontal' | 'more-vertical' | 'chevron-down'@Component({selector: 'my-action-dropdown',@@ -33,48 +45,65 @@ export type DropdownDirection = 'horizontal' | 'vertical'templateUrl: './action-dropdown.component.html',changeDetection: ChangeDetectionStrategy.OnPush,imports: [- NgIf,- NgbTooltip,- NgbDropdown,- NgbDropdownToggle,- NgClass,+ CommonModule,+ NgbTooltipModule,+ NgbDropdownModule,GlobalIconComponent,NgbDropdownMenu,- NgFor,RouterLink,- NgTemplateOutlet+ NgTemplateOutlet,+ ActorAvatarComponent]})-export class ActionDropdownComponent<T> {- readonly actions = input<DropdownAction<T>[] | DropdownAction<T>[][]>([])+export class ActionDropdownComponent<T, D = never> implements OnChanges {+ readonly actions = input<DropdownAction<T, D>[] | DropdownAction<T, D>[][]>([])readonly entry = input<T>(undefined)readonly placement = input('bottom-left auto')readonly container = input<null | 'body'>(undefined)readonly buttonSize = input<DropdownButtonSize>('normal')- readonly buttonDirection = input<DropdownDirection>('horizontal')- readonly buttonStyled = input(true)+ readonly buttonIcon = input<DropdownButtonIcon>('more-horizontal')+ readonly buttonStyled = input(true, { transform: booleanAttribute })readonly label = input<string>(undefined)readonly theme = input<DropdownTheme>('secondary')readonly openChange = output<boolean>()- getActions (): DropdownAction<T>[][] {+ @ContentChild('dropdownItemExtra', { descendants: false })+ dropdownItemExtra: TemplateRef<any>++ @ContentChild('labelExtra', { descendants: false })+ labelExtra: TemplateRef<any>++ buttonClasses: Record<string, boolean> = {}++ ngOnChanges () {+ this.buttonClasses = {+ 'icon-only': !this.label(),+ 'peertube-button': this.buttonStyled(),+ 'peertube-button-small': this.buttonSize() === 'small',+ 'secondary-button': this.buttonStyled() && this.theme() === 'secondary',+ 'primary-button': this.buttonStyled() && this.theme() === 'primary',+ 'button-unstyle': !this.buttonStyled()+ }+ }++ getActions (): DropdownAction<T, D>[][] {const actions = this.actions()- if (actions.length !== 0 && Array.isArray(actions[0])) return actions as DropdownAction<T>[][]+ if (actions.length !== 0 && Array.isArray(actions[0])) return actions as DropdownAction<T, D>[][]- return [ actions as DropdownAction<T>[] ]+ return [ actions as DropdownAction<T, D>[] ]}- getQueryParams (action: DropdownAction<T>, entry: T) {+ getQueryParams (action: DropdownAction<T, D>, entry: T) {if (action.queryParamsBuilder) return action.queryParamsBuilder(entry)return {}}- areActionsDisplayed (actions: (DropdownAction<T> | DropdownAction<T>[])[], entry: T): boolean {+ areActionsDisplayed (actions: (DropdownAction<T, D> | DropdownAction<T, D>[])[], entry: T): boolean {return actions.some(a => {if (Array.isArray(a)) return this.areActionsDisplayed(a, entry)@@ -82,7 +111,7 @@ export class ActionDropdownComponent<T> {})}- isBlockDisplayed (allActions: (DropdownAction<T> | DropdownAction<T>[])[], action: DropdownAction<T>, entry: T) {+ isBlockDisplayed (allActions: (DropdownAction<T, D> | DropdownAction<T, D>[])[], action: DropdownAction<T, D>, entry: T) {// Do not display only the headerif (action.isHeader && !this.areActionsDisplayed(allActions, entry)) return falsediff --git a/client/src/app/shared/shared-main/buttons/button.component.scss b/client/src/app/shared/shared-main/buttons/button.component.scssindex 94e3e2195b..2bef6fe197 100644--- a/client/src/app/shared/shared-main/buttons/button.component.scss+++ b/client/src/app/shared/shared-main/buttons/button.component.scss@@ -30,7 +30,7 @@&:not(.rounded-icon-button) {&.has-icon {- @include button-with-icon(24px, 0);+ @include button-with-icon(24px, 0, 0);}}diff --git a/client/src/app/shared/shared-main/channel/channels-setup-message.component.ts b/client/src/app/shared/shared-main/channel/channels-setup-message.component.tsindex 7b66ef98a1..2db57534f9 100644--- a/client/src/app/shared/shared-main/channel/channels-setup-message.component.ts+++ b/client/src/app/shared/shared-main/channel/channels-setup-message.component.ts@@ -1,16 +1,15 @@-import { NgIf } from '@angular/common'+import { CommonModule } from '@angular/common'import { Component, OnInit, inject, input } from '@angular/core'import { RouterLink } from '@angular/router'import { AuthService, User } from '@app/core'import { GlobalIconComponent } from '../../shared-icons/global-icon.component'import { AlertComponent } from '../common/alert.component'-import { VideoChannel } from './video-channel.model'@Component({selector: 'my-channels-setup-message',templateUrl: './channels-setup-message.component.html',styleUrls: [ './channels-setup-message.component.scss' ],- imports: [ NgIf, GlobalIconComponent, RouterLink, AlertComponent ]+ imports: [ CommonModule, GlobalIconComponent, RouterLink, AlertComponent ]})export class ChannelsSetupMessageComponent implements OnInit {private authService = inject(AuthService)@@ -22,7 +21,7 @@ export class ChannelsSetupMessageComponent implements OnInit {hasChannelNotConfigured () {if (!this.user.videoChannels) return false- return this.user.videoChannels.filter((channel: VideoChannel) => (channel.avatars.length === 0 || !channel.description)).length > 0+ return this.user.videoChannels.filter(c => (c.avatars.length === 0 || !c.description)).length > 0}ngOnInit () {diff --git a/client/src/app/shared/shared-main/channel/collaborator-state.component.html b/client/src/app/shared/shared-main/channel/collaborator-state.component.htmlnew file mode 100644index 0000000000..524d8ccb7e--- /dev/null+++ b/client/src/app/shared/shared-main/channel/collaborator-state.component.html@@ -0,0 +1,13 @@+@if (type() === 'owner') {+ <span class="collaborator-role collaborator-role-owner" [ngClass]="{ small: small() }" [ngbTooltip]="ownerTooltip" i18n>+ Owner+ </span>+} @else if (type() === 'accepted') {+ <span class="collaborator-role collaborator-role-editor" [ngClass]="{ small: small() }" [ngbTooltip]="editorTooltip" i18n>+ Editor+ </span>+} @else if (type() === 'invited') {+ <span class="collaborator-role collaborator-role-invited" [ngClass]="{ small: small() }" [ngbTooltip]="invitationTooltip" i18n>+ Invitation sent+ </span>+}diff --git a/client/src/app/shared/shared-main/channel/collaborator-state.component.scss b/client/src/app/shared/shared-main/channel/collaborator-state.component.scssnew file mode 100644index 0000000000..a55cbc3c33--- /dev/null+++ b/client/src/app/shared/shared-main/channel/collaborator-state.component.scss@@ -0,0 +1,30 @@+@use "_variables" as *;+@use "_mixins" as *;++.collaborator-role {+ border-radius: 4px;+ padding: 2px 6px;+ width: fit-content;+ line-height: normal;+ border: 1px solid;++ @include font-size(12px);++ &.small {+ padding: 1px 6px;++ @include font-size(10px);+ }+}++.collaborator-role-owner {+ color: pvar(--bg-secondary-400);+ background-color: pvar(--fg-200);+ border-color: pvar(--fg-200);+}++.collaborator-role-editor,+.collaborator-role-invited {+ color: pvar(--fg-300);+ border-color: pvar(--secondary-icon-color);+}diff --git a/client/src/app/shared/shared-main/channel/collaborator-state.component.ts b/client/src/app/shared/shared-main/channel/collaborator-state.component.tsnew file mode 100644index 0000000000..83e2bb8559--- /dev/null+++ b/client/src/app/shared/shared-main/channel/collaborator-state.component.ts@@ -0,0 +1,35 @@+import { CommonModule } from '@angular/common'+import { booleanAttribute, Component, input, OnInit } from '@angular/core'+import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'++export type CollaboratorStateType = 'owner' | 'accepted' | 'invited'++@Component({+ selector: 'my-collaborator-state',+ templateUrl: './collaborator-state.component.html',+ styleUrls: [ './collaborator-state.component.scss' ],+ imports: [ CommonModule, NgbTooltipModule ]+})+export class CollaboratorStateComponent implements OnInit {+ readonly type = input.required<CollaboratorStateType>()+ readonly small = input(false, { transform: booleanAttribute })+ readonly disableTooltip = input(false, { transform: booleanAttribute })++ editorTooltip: string+ ownerTooltip: string+ invitationTooltip: string++ ngOnInit () {+ this.editorTooltip = this.disableTooltip()+ ? null+ : $localize`You are an editor of this channel`++ this.ownerTooltip = this.disableTooltip()+ ? null+ : $localize`You are the owner of this channel`++ this.invitationTooltip = this.disableTooltip()+ ? null+ : $localize`You have been invited to be an editor of this channel`+ }+}diff --git a/client/src/app/shared/shared-main/channel/video-channel-sync.service.ts b/client/src/app/shared/shared-main/channel/video-channel-sync.service.tsindex f23480d254..66efbbf66c 100644--- a/client/src/app/shared/shared-main/channel/video-channel-sync.service.ts+++ b/client/src/app/shared/shared-main/channel/video-channel-sync.service.ts@@ -18,29 +18,34 @@ export class VideoChannelSyncService {static BASE_VIDEO_CHANNEL_URL = environment.apiUrl + '/api/v1/video-channel-syncs'- listAccountVideoChannelsSyncs (parameters: {+ listByAccount (parameters: {sort: SortMetapagination: RestPaginationaccount: Account+ includeCollaborations: boolean}): Observable<ResultList<VideoChannelSync>> {- const { pagination, sort, account } = parameters+ const { pagination, sort, account, includeCollaborations } = parameterslet params = new HttpParams()params = this.restService.addRestGetParams(params, pagination, sort)+ if (includeCollaborations) {+ params = params.append('includeCollaborations', 'true')+ }+const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-channel-syncs'return this.authHttp.get<ResultList<VideoChannelSync>>(url, { params }).pipe(catchError(err => this.restExtractor.handleError(err)))}- createSync (body: VideoChannelSyncCreate) {+ create (body: VideoChannelSyncCreate) {return this.authHttp.post<{ videoChannelSync: VideoChannelSync }>(VideoChannelSyncService.BASE_VIDEO_CHANNEL_URL, body).pipe(catchError(err => this.restExtractor.handleError(err)))}- deleteSync (videoChannelsSyncId: number) {- const url = `${VideoChannelSyncService.BASE_VIDEO_CHANNEL_URL}/${videoChannelsSyncId}`+ delete (syncId: number) {+ const url = `${VideoChannelSyncService.BASE_VIDEO_CHANNEL_URL}/${syncId}`return this.authHttp.delete(url).pipe(catchError(err => this.restExtractor.handleError(err)))diff --git a/client/src/app/shared/shared-main/channel/video-channel.model.ts b/client/src/app/shared/shared-main/channel/video-channel.model.tsindex 348ada8eb0..e383abdde9 100644--- a/client/src/app/shared/shared-main/channel/video-channel.model.ts+++ b/client/src/app/shared/shared-main/channel/video-channel.model.ts@@ -34,8 +34,8 @@ export class VideoChannel extends Actor implements ServerVideoChannel {return Actor.GET_ACTOR_AVATAR_URL(actor, size)}- static GET_ACTOR_BANNER_URL (channel: ServerVideoChannel) {- if (!channel || channel.banners.length === 0) {+ static GET_ACTOR_BANNER_URL (channel: Partial<Pick<ServerVideoChannel, 'banners'>>) {+ if (!channel || !Array.isArray(channel.banners) || channel.banners.length === 0) {return ''}@@ -93,26 +93,6 @@ export class VideoChannel extends Actor implements ServerVideoChannel {this.updateComputedAttributes()}- updateAvatar (newAvatars: ActorImage[]) {- this.avatars = newAvatars-- this.updateComputedAttributes()- }-- resetAvatar () {- this.updateAvatar([])- }-- updateBanner (newBanners: ActorImage[]) {- this.banners = newBanners-- this.updateComputedAttributes()- }-- resetBanner () {- this.updateBanner([])- }-updateComputedAttributes () {this.bannerUrl = VideoChannel.GET_ACTOR_BANNER_URL(this)}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 23b3153ebc..fac3bd513e 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,20 +1,21 @@-import { Observable, ReplaySubject } from 'rxjs'-import { catchError, map, tap } from 'rxjs/operators'import { HttpClient, HttpParams } from '@angular/common/http'import { Injectable, inject } from '@angular/core'import { ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'import {ActorImage,ResultList,- VideoChannel as VideoChannelServer,+ VideoChannelCollaborator,VideoChannelCreate,+ VideoChannel as VideoChannelServer,VideoChannelUpdate,VideosImportInChannelCreate} from '@peertube/peertube-models'+import { Observable, ReplaySubject } from 'rxjs'+import { catchError, map, tap } from 'rxjs/operators'import { environment } from '../../../../environments/environment'+import { Account } from '../account/account.model'import { AccountService } from '../account/account.service'import { VideoChannel } from './video-channel.model'-import { Account } from '../account/account.model'@Injectable({ providedIn: 'root' })export class VideoChannelService {@@ -37,8 +38,8 @@ export class VideoChannelService {return { data: videoChannels, total: result.total }}- getVideoChannel (videoChannelName: string) {- return this.authHttp.get<VideoChannel>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName)+ get (name: string) {+ return this.authHttp.get<VideoChannel>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + name).pipe(map(videoChannelHash => new VideoChannel(videoChannelHash)),tap(videoChannel => this.videoChannelLoaded.next(videoChannel)),@@ -46,14 +47,15 @@ export class VideoChannelService {)}- listAccountVideoChannels (options: {+ listAccountChannels (options: {account: AccountcomponentPagination?: ComponentPaginationLightwithStats?: booleansort?: stringsearch?: string+ includeCollaborations?: boolean}): Observable<ResultList<VideoChannel>> {- const { account, componentPagination, withStats = false, sort, search } = options+ const { account, componentPagination, withStats = false, sort, search, includeCollaborations = false } = optionsconst defaultCount = Math.min(this.serverService.getHTMLConfig().videoChannels.maxPerUser, 100) // 100 is the max count on server side@@ -66,6 +68,7 @@ export class VideoChannelService {params = params.set('withStats', withStats + '')if (search) params = params.set('search', search)+ if (includeCollaborations) params = params.set('includeCollaborations', 'true')const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-channels'return this.authHttp.get<ResultList<VideoChannelServer>>(url, { params })@@ -75,37 +78,41 @@ export class VideoChannelService {)}- createVideoChannel (videoChannel: VideoChannelCreate) {- return this.authHttp.post(VideoChannelService.BASE_VIDEO_CHANNEL_URL, videoChannel)+ create (channel: VideoChannelCreate) {+ return this.authHttp.post(VideoChannelService.BASE_VIDEO_CHANNEL_URL, channel).pipe(catchError(err => this.restExtractor.handleError(err)))}- updateVideoChannel (videoChannelName: string, videoChannel: VideoChannelUpdate) {- return this.authHttp.put(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName, videoChannel)+ update (name: string, channel: VideoChannelUpdate) {+ return this.authHttp.put(VideoChannelService.BASE_VIDEO_CHANNEL_URL + name, channel).pipe(catchError(err => this.restExtractor.handleError(err)))}- changeVideoChannelImage (videoChannelName: string, avatarForm: FormData, type: 'avatar' | 'banner') {- const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName + '/' + type + '/pick'+ remove (channel: VideoChannel) {+ return this.authHttp.delete(VideoChannelService.BASE_VIDEO_CHANNEL_URL + channel.nameWithHost)+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }++ // ---------------------------------------------------------------------------++ changeImage (name: string, avatarForm: FormData, type: 'avatar' | 'banner') {+ const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + name + '/' + type + '/pick'return this.authHttp.post<{ avatars?: ActorImage[], banners?: ActorImage[] }>(url, avatarForm).pipe(catchError(err => this.restExtractor.handleError(err)))}- deleteVideoChannelImage (videoChannelName: string, type: 'avatar' | 'banner') {- const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName + '/' + type+ deleteImage (name: string, type: 'avatar' | 'banner') {+ const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + name + '/' + typereturn this.authHttp.delete(url).pipe(catchError(err => this.restExtractor.handleError(err)))}- removeVideoChannel (videoChannel: VideoChannel) {- return this.authHttp.delete(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost)- .pipe(catchError(err => this.restExtractor.handleError(err)))- }+ // ---------------------------------------------------------------------------- importVideos (videoChannelName: string, externalChannelUrl: string, syncId?: number) {- const path = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannelName + '/import-videos'+ importVideos (name: string, externalChannelUrl: string, syncId?: number) {+ const path = VideoChannelService.BASE_VIDEO_CHANNEL_URL + name + '/import-videos'const body: VideosImportInChannelCreate = {externalChannelUrl,@@ -115,4 +122,44 @@ export class VideoChannelService {return this.authHttp.post(path, body).pipe(catchError(err => this.restExtractor.handleError(err)))}++ // ---------------------------------------------------------------------------++ listCollaborators (channelName: string) {+ const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + channelName + '/collaborators'++ return this.authHttp.get<ResultList<VideoChannelCollaborator>>(url)+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }++ inviteCollaborator (channelName: string, collaboratorUsername: string) {+ const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + channelName + '/collaborators/invite'++ return this.authHttp.post<{ collaborator: VideoChannelCollaborator }>(url, { accountHandle: collaboratorUsername })+ .pipe(+ map(({ collaborator }) => collaborator),+ catchError(err => this.restExtractor.handleError(err))+ )+ }++ acceptCollaboratorInvitation (channelName: string, collaboratorId: number) {+ const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + channelName + '/collaborators/' + collaboratorId + '/accept'++ return this.authHttp.post(url, {})+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }++ rejectCollaboratorInvitation (channelName: string, collaboratorId: number) {+ const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + channelName + '/collaborators/' + collaboratorId + '/reject'++ return this.authHttp.post(url, {})+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }++ removeCollaborator (channelName: string, collaboratorId: number) {+ const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + channelName + '/collaborators/' + collaboratorId++ return this.authHttp.delete(url)+ .pipe(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 8ba0f08660..e5e4c9a654 100644--- a/client/src/app/shared/shared-main/main-providers.ts+++ b/client/src/app/shared/shared-main/main-providers.ts@@ -6,6 +6,7 @@ import { CustomPageService } from './custom-page/custom-page.service'import { FromNowPipe } from './date/from-now.pipe'import { AUTH_INTERCEPTOR_PROVIDER } from './http/auth-interceptor.service'import { InstanceService } from './instance/instance.service'+import { HorizontalMenuService } from './menu/horizontal-menu.service'import { ActorRedirectGuard } from './router/actor-redirect-guard.service'import { UserHistoryService } from './users/user-history.service'import { UserNotificationService } from './users/user-notification.service'@@ -40,6 +41,7 @@ export function getMainProviders () {CustomPageService,ActorRedirectGuard,InstanceService,- VideoChannelSyncService+ VideoChannelSyncService,+ HorizontalMenuService]}diff --git a/client/src/app/shared/shared-main/menu/horizontal-menu.component.html b/client/src/app/shared/shared-main/menu/horizontal-menu.component.htmlindex ed882a0b63..9a1193058c 100644--- a/client/src/app/shared/shared-main/menu/horizontal-menu.component.html+++ b/client/src/app/shared/shared-main/menu/horizontal-menu.component.html@@ -1,4 +1,4 @@-<div class="root" [ngClass]="{ 'with-mb': withMarginBottom() }">+<div class="root" [ngClass]="{ 'with-mb': withMarginBottom() }" [hidden]="isHidden()"><h1 *ngIf="h1()"><my-global-icon *ngIf="h1Icon()" [iconName]="h1Icon()"></my-global-icon>diff --git a/client/src/app/shared/shared-main/menu/horizontal-menu.component.ts b/client/src/app/shared/shared-main/menu/horizontal-menu.component.tsindex 0c7711fce6..e8d120e9f9 100644--- a/client/src/app/shared/shared-main/menu/horizontal-menu.component.ts+++ b/client/src/app/shared/shared-main/menu/horizontal-menu.component.ts@@ -7,6 +7,7 @@ import { filter, Subscription } from 'rxjs'import { PluginSelectorDirective } from '../plugins/plugin-selector.directive'import { ListOverflowComponent } from './list-overflow.component'import { NgbModal } from '@ng-bootstrap/ng-bootstrap'+import { HorizontalMenuService } from './horizontal-menu.service'export type HorizontalMenuEntry = {label: string@@ -41,6 +42,7 @@ export type HorizontalMenuEntry = {]})export class HorizontalMenuComponent implements OnInit, OnChanges, OnDestroy {+ private horizontalMenuService = inject(HorizontalMenuService)private router = inject(Router)private route = inject(ActivatedRoute)private modal = inject(NgbModal)@@ -78,6 +80,10 @@ export class HorizontalMenuComponent implements OnInit, OnChanges, OnDestroy {}}+ isHidden () {+ return this.horizontalMenuService.isMenuHidden()+ }+private buildChildren () {this.children = []this.activeParent = undefineddiff --git a/client/src/app/shared/shared-main/menu/horizontal-menu.service.ts b/client/src/app/shared/shared-main/menu/horizontal-menu.service.tsnew file mode 100644index 0000000000..18febc9148--- /dev/null+++ b/client/src/app/shared/shared-main/menu/horizontal-menu.service.ts@@ -0,0 +1,14 @@+import { Injectable } from '@angular/core'++@Injectable()+export class HorizontalMenuService {+ private menuHidden = false++ isMenuHidden () {+ return this.menuHidden+ }++ setMenuHidden (hidden: boolean) {+ this.menuHidden = hidden+ }+}diff --git a/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts b/client/src/app/shared/shared-main/router/actor-redirect-guard.service.tsindex 4a6efad135..483c7f13d6 100644--- a/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts+++ b/client/src/app/shared/shared-main/router/actor-redirect-guard.service.ts@@ -16,7 +16,7 @@ export class ActorRedirectGuard {return forkJoin([this.accountService.getAccount(actorName).pipe(this.orUndefined()),- this.channelService.getVideoChannel(actorName).pipe(this.orUndefined())+ this.channelService.get(actorName).pipe(this.orUndefined())]).pipe(map(([ account, channel ]) => {if (account) {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 b82c02c614..0742e4ba5d 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@@ -1,309 +1,190 @@import { AuthUser } from '@app/core'-import { Account } from '@app/shared/shared-main/account/account.model'import { Actor } from '@app/shared/shared-main/account/actor.model'-import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'import {- AbuseStateType,- ActorInfo,- FollowState,- PluginType_Type,UserNotification as UserNotificationServer,UserNotificationType,- UserNotificationType_Type,UserRight,- VideoConstant,- VideoInfo+ VideoChannelCollaboratorState} from '@peertube/peertube-models'import { logger } from '@root-helpers/logger'import { Video } from '../video/video.model'-export class UserNotification implements UserNotificationServer {- id: number- type: UserNotificationType_Type- read: boolean+export class UserNotification {+ payload: UserNotificationServer- video?: VideoInfo & {- channel: ActorInfo & { avatarUrl?: string }- }-- videoImport?: {- id: number- video?: VideoInfo- torrentName?: string- magnetUri?: string- targetUrl?: string- }-- comment?: {- id: number- threadId: number- heldForReview: boolean- account: ActorInfo & { avatarUrl?: string }- video: VideoInfo- }-- abuse?: {- id: number- state: AbuseStateType-- video?: VideoInfo-- comment?: {- threadId: number-- video: VideoInfo- }-- account?: ActorInfo- }-- videoBlacklist?: {- id: number- video: VideoInfo- }-- account?: ActorInfo & { avatarUrl?: string }-- actorFollow?: {- id: number- state: FollowState- follower: ActorInfo & { avatarUrl?: string }- following: {- type: 'account' | 'channel' | 'instance'- name: string- displayName: string- host: string- }- }-- plugin?: {- name: string- type: PluginType_Type- latestVersion: string- }-- peertube?: {- latestVersion: string- }-- registration?: {- id: number- username: string- }-- videoCaption?: {- id: number- language: VideoConstant<string>- video: VideoInfo- }-- createdAt: string- updatedAt: string-- // Additional fields- videoUrl?: string- commentUrl?: any[]-- commentReviewUrl?: string- commentReviewQueryParams?: { [id: string]: string } = {}-- abuseUrl?: string- abuseQueryParams?: { [id: string]: string } = {}-- videoAutoBlacklistUrl?: string-- accountUrl?: string-- registrationsUrl?: string+ // Default notification URL+ url: string | any[]+ queryParams?: { [id: string]: string } = {}- videoImportIdentifier?: string- videoImportUrl?: string+ externalUrl: string- instanceFollowUrl?: string+ videoImportIdentifier: string+ followingHandle: string+ followerHandle: string- peertubeVersionLink?: string-- pluginUrl?: string- pluginQueryParams?: { [id: string]: string } = {}-- constructor (hash: UserNotificationServer, user: AuthUser) {- this.id = hash.id- this.type = hash.type- this.read = hash.read+ constructor (payload: UserNotificationServer, user: AuthUser) {+ this.payload = payload// We assume that some fields exist// To prevent a notification popup crash in case of bug, wrap it inside a try/catchtry {- this.video = hash.video- if (this.video) this.setVideoChannelAvatarUrl(this.video.channel)-- this.videoImport = hash.videoImport-- this.comment = hash.comment- if (this.comment) this.setAccountAvatarUrl(this.comment.account)-- this.abuse = hash.abuse-- this.videoBlacklist = hash.videoBlacklist-- this.account = hash.account- if (this.account) this.setAccountAvatarUrl(this.account)-- this.actorFollow = hash.actorFollow- if (this.actorFollow) this.setAccountAvatarUrl(this.actorFollow.follower)-- this.plugin = hash.plugin- this.peertube = hash.peertube- this.registration = hash.registration-- this.videoCaption = hash.videoCaption-- this.createdAt = hash.createdAt- this.updatedAt = hash.updatedAt-- switch (this.type) {+ switch (payload.type) {case UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION:case UserNotificationType.NEW_LIVE_FROM_SUBSCRIPTION:- this.videoUrl = this.buildVideoUrl(this.video)+ this.url = this.buildVideoUrl(payload.video)+ break++ case UserNotificationType.BLACKLIST_ON_MY_VIDEO:+ this.url = this.buildVideoUrl(payload.videoBlacklist.video)breakcase UserNotificationType.UNBLACKLIST_ON_MY_VIDEO:- this.videoUrl = this.buildVideoUrl(this.video)+ this.url = this.buildVideoUrl(payload.video)breakcase UserNotificationType.NEW_COMMENT_ON_MY_VIDEO:case UserNotificationType.COMMENT_MENTION:- if (!this.comment) break- this.accountUrl = this.buildAccountUrl(this.comment.account)- this.commentUrl = this.buildCommentUrl(this.comment)+ if (!payload.comment) break++ if (payload.comment.heldForReview) {+ this.url = '/my-account/videos/comments'+ this.queryParams.search = 'heldForReview:true'+ } else {+ this.url = this.buildCommentUrl(payload.comment)+ }- this.commentReviewUrl = '/my-account/videos/comments'- this.commentReviewQueryParams.search = 'heldForReview:true'breakcase UserNotificationType.NEW_ABUSE_FOR_MODERATORS:- this.abuseUrl = '/admin/moderation/abuses/list'- this.abuseQueryParams.search = '#' + this.abuse.id-- if (this.abuse.video) this.videoUrl = this.buildVideoUrl(this.abuse.video)- else if (this.abuse.comment) this.commentUrl = this.buildCommentUrl(this.abuse.comment)- else if (this.abuse.account) this.accountUrl = this.buildAccountUrl(this.abuse.account)+ this.url = '/admin/moderation/abuses/list'+ this.queryParams.search = '#' + payload.abuse.idbreakcase UserNotificationType.ABUSE_STATE_CHANGE:- this.abuseUrl = '/my-account/abuses'- this.abuseQueryParams.search = '#' + this.abuse.id+ this.url = '/my-account/abuses'+ this.queryParams.search = '#' + payload.abuse.idbreakcase UserNotificationType.ABUSE_NEW_MESSAGE:- this.abuseUrl = user.hasRight(UserRight.MANAGE_ABUSES)+ this.url = user.hasRight(UserRight.MANAGE_ABUSES)? '/admin/moderation/abuses/list': '/my-account/abuses'- this.abuseQueryParams.search = '#' + this.abuse.id+ this.queryParams.search = '#' + payload.abuse.idbreakcase UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS:- this.videoAutoBlacklistUrl = '/admin/moderation/video-auto-blacklist/list'// Backward compatibility where we did not assign videoBlacklist to this type of notification before- if (!this.videoBlacklist) this.videoBlacklist = { id: null, video: this.video }-- this.videoUrl = this.buildVideoUrl(this.videoBlacklist.video)- break+ if (!this.payload.videoBlacklist) this.payload.videoBlacklist = { id: null, video: payload.video }- case UserNotificationType.BLACKLIST_ON_MY_VIDEO:- this.videoUrl = this.buildVideoUrl(this.videoBlacklist.video)+ this.url = '/admin/moderation/video-auto-blacklist/list'breakcase UserNotificationType.MY_VIDEO_PUBLISHED:- this.videoUrl = this.buildVideoUrl(this.video)+ this.url = this.buildVideoUrl(payload.video)breakcase UserNotificationType.MY_VIDEO_IMPORT_SUCCESS:- this.videoImportUrl = this.buildVideoImportUrl()- this.videoImportIdentifier = this.buildVideoImportIdentifier(this.videoImport)-- if (this.videoImport.video) this.videoUrl = this.buildVideoUrl(this.videoImport.video)+ this.videoImportIdentifier = this.buildVideoImportIdentifier(payload.videoImport)+ this.url = payload.video+ ? this.buildVideoUrl(payload.video)+ : this.buildVideoImportUrl()breakcase UserNotificationType.MY_VIDEO_IMPORT_ERROR:- this.videoImportUrl = this.buildVideoImportUrl()- this.videoImportIdentifier = this.buildVideoImportIdentifier(this.videoImport)+ this.videoImportIdentifier = this.buildVideoImportIdentifier(payload.videoImport)+ this.url = this.buildVideoImportUrl()breakcase UserNotificationType.NEW_USER_REGISTRATION:- this.accountUrl = this.buildAccountUrl(this.account)+ this.url = this.buildAccountUrl(payload.account)breakcase UserNotificationType.NEW_USER_REGISTRATION_REQUEST:- this.registrationsUrl = '/admin/moderation/registrations/list'+ this.url = '/admin/moderation/registrations/list'breakcase UserNotificationType.NEW_FOLLOW:- this.accountUrl = this.buildAccountUrl(this.actorFollow.follower)+ this.url = this.buildAccountUrl(payload.actorFollow.follower)break- case UserNotificationType.NEW_INSTANCE_FOLLOWER:- this.instanceFollowUrl = '/admin/settings/follows/followers-list'+ case UserNotificationType.NEW_INSTANCE_FOLLOWER: {+ const follower = payload.actorFollow.follower+ this.followerHandle = follower.name === 'peertube'+ ? follower.host+ : `${follower.name} @ ${follower.host}`++ this.url = '/admin/settings/follows/followers-list'break+ }++ case UserNotificationType.AUTO_INSTANCE_FOLLOWING: {+ const following = payload.actorFollow.following++ this.followingHandle = following.name === 'peertube'+ ? following.host+ : `${following.name} @ ${following.host}`++ this.url = '/admin/settings/follows/following-list'- case UserNotificationType.AUTO_INSTANCE_FOLLOWING:- this.instanceFollowUrl = '/admin/settings/follows/following-list'break+ }case UserNotificationType.NEW_PEERTUBE_VERSION:- this.peertubeVersionLink = 'https://joinpeertube.org/news'+ this.externalUrl = 'https://joinpeertube.org/news'breakcase UserNotificationType.NEW_PLUGIN_VERSION:- this.pluginUrl = `/admin/settings/plugins/list-installed`- this.pluginQueryParams.pluginType = this.plugin.type + ''+ this.url = `/admin/settings/plugins/list-installed`+ this.queryParams.pluginType = payload.plugin.type + ''breakcase UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED:- this.videoUrl = this.buildVideoUrl(this.videoCaption.video)+ this.url = this.buildVideoUrl(payload.videoCaption.video)breakcase UserNotificationType.MY_VIDEO_STUDIO_EDITION_FINISHED:- this.videoUrl = this.buildVideoUrl(this.video)+ this.url = this.buildVideoUrl(payload.video)+ break++ case UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL:+ if (payload.videoChannelCollaborator.state.id === VideoChannelCollaboratorState.ACCEPTED) {+ this.url = this.buildChannelEditorsUrl(payload.videoChannelCollaborator.channel)+ } // Else, no URL: we have buttons instead to accept/decline the invitation++ break++ case UserNotificationType.ACCEPTED_TO_COLLABORATE_TO_CHANNEL:+ case UserNotificationType.REFUSED_TO_COLLABORATE_TO_CHANNEL:+ this.url = this.buildChannelEditorsUrl(payload.videoChannelCollaborator.channel)break}} catch (err) {- this.type = null+ this.payload.type = nulllogger.error(err)}}- private buildVideoUrl (video: { uuid: string }) {+ buildVideoUrl (video: { uuid: string }) {return Video.buildWatchUrl(video)}- private buildAccountUrl (account: { name: string, host: string }) {+ buildAccountUrl (account: { name: string, host: string }) {return '/a/' + Actor.CREATE_BY_STRING(account.name, account.host)}- private buildVideoImportUrl () {+ buildVideoImportUrl () {return '/my-library/video-imports'}- private buildVideoImportIdentifier (videoImport: UserNotification['videoImport']) {+ buildVideoImportIdentifier (videoImport: UserNotificationServer['videoImport']) {return videoImport.video?.name || videoImport.targetUrl || videoImport.magnetUri || videoImport.torrentName}- private buildCommentUrl (comment: { video: { uuid: string }, threadId: number }) {+ buildCommentUrl (comment: { video: { uuid: string }, threadId: number }) {return [ this.buildVideoUrl(comment.video), { threadId: comment.threadId } ]}- private setAccountAvatarUrl (actor: {- avatarUrl?: string- avatars: { width: number, fileUrl?: string, url?: string, path: string }[]- }) {- actor.avatarUrl = VideoChannel.GET_ACTOR_AVATAR_URL(actor, 48) || Account.GET_DEFAULT_AVATAR_URL(48)- }-- private setVideoChannelAvatarUrl (actor: {- avatarUrl?: string- avatars: { width: number, fileUrl?: string, url?: string, path: string }[]- }) {- actor.avatarUrl = VideoChannel.GET_ACTOR_AVATAR_URL(actor, 48) || VideoChannel.GET_DEFAULT_AVATAR_URL(48)+ buildChannelEditorsUrl (channel: { name: string }) {+ return [ '/my-library', 'video-channels', 'manage', channel.name, 'editors' ]}}diff --git a/client/src/app/shared/shared-main/users/user-notification.service.ts b/client/src/app/shared/shared-main/users/user-notification.service.tsindex c3e433464d..735553ec5c 100644--- a/client/src/app/shared/shared-main/users/user-notification.service.ts+++ b/client/src/app/shared/shared-main/users/user-notification.service.ts@@ -36,7 +36,7 @@ export class UserNotificationService {? new HttpContext().set(NGX_LOADING_BAR_IGNORED, true): undefined- return this.authHttp.get<ResultList<UserNotification>>(UserNotificationService.BASE_NOTIFICATIONS_URL, { params, context })+ return this.authHttp.get<ResultList<UserNotificationServer>>(UserNotificationService.BASE_NOTIFICATIONS_URL, { params, context }).pipe(map(res => this.restExtractor.applyToResultListData(res, this.formatNotification.bind(this))),catchError(err => this.restExtractor.handleError(err))@@ -51,7 +51,7 @@ export class UserNotificationService {markAsRead (notification: UserNotification) {const url = UserNotificationService.BASE_NOTIFICATIONS_URL + '/read'- const body = { ids: [ notification.id ] }+ const body = { ids: [ notification.payload.id ] }const context = new HttpContext().set(NGX_LOADING_BAR_IGNORED, true)return this.authHttp.post(url, body, { context })diff --git a/client/src/app/shared/shared-main/video/video-import.service.ts b/client/src/app/shared/shared-main/video/video-import.service.tsindex f1587ebeed..92e5a02b4f 100644--- a/client/src/app/shared/shared-main/video/video-import.service.ts+++ b/client/src/app/shared/shared-main/video/video-import.service.ts@@ -26,16 +26,19 @@ export class VideoImportService {.pipe(catchError(res => this.restExtractor.handleError(res)))}- getMyVideoImports (options: {+ listMyVideoImports (options: {pagination: RestPaginationsort: SortMeta+ includeCollaborations: booleansearch?: string}): Observable<ResultList<VideoImport>> {- const { pagination, sort, search } = options+ const { pagination, sort, search, includeCollaborations } = optionslet params = new HttpParams()params = this.restService.addRestGetParams(params, pagination, sort)+ if (includeCollaborations) params = params.append('includeCollaborations', 'true')+if (search) {const filters = this.restService.parseQueryStringFilter(search, {videoChannelSyncId: {diff --git a/client/src/app/shared/shared-main/video/video.service.ts b/client/src/app/shared/shared-main/video/video.service.tsindex d4c72f6f8e..59b195a167 100644--- a/client/src/app/shared/shared-main/video/video.service.ts+++ b/client/src/app/shared/shared-main/video/video.service.ts@@ -124,12 +124,14 @@ export class VideoService {sort: VideoSortField | SortMetauserChannels?: VideoChannelServerModel[]+ includeCollaborations?: boolean+isLive?: booleanprivacyOneOf?: VideoPrivacyType[]channelNameOneOf: string[]search?: string}): Observable<ResultList<Video>> {- const { videoPagination, restPagination, sort, channelNameOneOf, privacyOneOf, search } = options+ const { videoPagination, restPagination, sort, channelNameOneOf, privacyOneOf, search, includeCollaborations } = optionsconst pagination = videoPagination? this.restService.componentToRestPagination(videoPagination)@@ -150,6 +152,8 @@ export class VideoService {params = this.restService.addArrayParams(params, 'channelNameOneOf', channelNameOneOf)}+ if (includeCollaborations) params = params.set('includeCollaborations', 'true')+return this.authHttp.get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params }).pipe(diff --git a/client/src/app/shared/shared-tables/actor-cell.component.html b/client/src/app/shared/shared-tables/actor-cell.component.htmlnew file mode 100644index 0000000000..83e8aa1afe--- /dev/null+++ b/client/src/app/shared/shared-tables/actor-cell.component.html@@ -0,0 +1,18 @@+<a [routerLink]="routerLink" [title]="linkTitle">+ <div class="chip two-lines">+ @if (displayAvatar()) {+ <my-actor-avatar [actor]="actor()" [actorType]="actorType()" size="32"></my-actor-avatar>+ }++ <div class="information">+ <span class="fw-semibold">{{ actor().displayName }}</span>+ @if (displayUsername()) {+ <span class="muted">{{ actor().name }}</span>+ }+ </div>++ @if (isEditorOfChannel()) {+ <my-collaborator-state class="ms-2" type="accepted" small="true"></my-collaborator-state>+ }+ </div>+</a>diff --git a/client/src/app/shared/shared-tables/actor-cell.component.scss b/client/src/app/shared/shared-tables/actor-cell.component.scssnew file mode 100644index 0000000000..84a11aad18--- /dev/null+++ b/client/src/app/shared/shared-tables/actor-cell.component.scss@@ -0,0 +1,10 @@+@use "_variables" as *;+@use "_mixins" as *;++a:hover {+ opacity: 1;++ .information {+ opacity: 0.8;+ }+}diff --git a/client/src/app/shared/shared-tables/actor-cell.component.ts b/client/src/app/shared/shared-tables/actor-cell.component.tsnew file mode 100644index 0000000000..0549e9135d--- /dev/null+++ b/client/src/app/shared/shared-tables/actor-cell.component.ts@@ -0,0 +1,47 @@+import { CommonModule } from '@angular/common'+import { booleanAttribute, Component, inject, input, OnInit } from '@angular/core'+import { RouterModule } from '@angular/router'+import { AuthService } from '@app/core'+import { ActorAvatarComponent, ActorAvatarInput } from '../shared-actor-image/actor-avatar.component'+import { CollaboratorStateComponent } from '../shared-main/channel/collaborator-state.component'++@Component({+ selector: 'my-actor-cell',+ templateUrl: './actor-cell.component.html',+ styleUrls: [ './actor-cell.component.scss' ],+ imports: [+ CommonModule,+ RouterModule,+ CollaboratorStateComponent,+ ActorAvatarComponent+ ]+})+export class ActorCellComponent implements OnInit {+ private authService = inject(AuthService)++ actor = input.required<ActorAvatarInput & { id: number, displayName: string }>()+ actorType = input.required<'channel' | 'account'>()+ displayAvatar = input(true, { transform: booleanAttribute })+ displayUsername = input(true, { transform: booleanAttribute })++ routerLink: string[]+ linkTitle: string++ ngOnInit (): void {+ if (this.actorType() === 'channel') {+ this.routerLink = [ '/c', this.actor().name ]+ this.linkTitle = $localize`Go to the channel page of ${this.actor().displayName}`+ } else {+ this.routerLink = [ '/a', this.actor().name ]+ this.linkTitle = $localize`Go to the account page of ${this.actor().displayName}`+ }+ }++ isEditorOfChannel (): boolean {+ const actor = this.actor()++ if (this.actorType() !== 'channel') return false++ return this.authService.getUser().isEditorOfChannel(actor)+ }+}diff --git a/client/src/app/shared/shared-tables/table-expander-icon.component copy.ts b/client/src/app/shared/shared-tables/table-expander-icon.component copy.tsdeleted file mode 100644index ebe2da1d18..0000000000--- a/client/src/app/shared/shared-tables/table-expander-icon.component copy.ts+++ /dev/null@@ -1,16 +0,0 @@-import { Component, input } from '@angular/core'-import { NgClass } from '@angular/common'-import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'--@Component({- selector: 'my-table-expander-icon',- template: `-<button type="button" class="expander border-0 p-0" [ngbTooltip]="tooltip()" [ariaLabel]="tooltip()">- <i [ngClass]="expanded() ? 'chevron-down' : 'chevron-right'"></i>-</button>`,- imports: [ NgbTooltip, NgClass ]-})-export class TableExpanderIconComponent {- readonly expanded = input<boolean>(undefined)- readonly tooltip = input($localize`Get more information`)-}diff --git a/client/src/app/shared/shared-tables/table.component.html b/client/src/app/shared/shared-tables/table.component.htmlindex 2dec7bac0c..9ae12c70fb 100644--- a/client/src/app/shared/shared-tables/table.component.html+++ b/client/src/app/shared/shared-tables/table.component.html@@ -109,7 +109,7 @@<div class="form-group"><div class="muted small mb-2" i18n>Column displayed:</div>- @for (column of columns; track column) {+ @for (column of columns; track column.id) {<div class="ms-1 mb-1"><my-peertube-checkbox[inputName]="'column-' + column.id"diff --git a/client/src/app/shared/shared-tables/table.component.ts b/client/src/app/shared/shared-tables/table.component.tsindex 174c73a8d8..93313834d6 100644--- a/client/src/app/shared/shared-tables/table.component.ts+++ b/client/src/app/shared/shared-tables/table.component.ts@@ -10,6 +10,7 @@ import {OnDestroy,OnInit,output,+ SimpleChanges,TemplateRef} from '@angular/core'import { FormsModule } from '@angular/forms'@@ -189,19 +190,21 @@ export class TableComponent<Data, ColumnName = string, QueryParams extends Tablethis.routeSubscription?.unsubscribe()}- ngOnChanges () {- this.columns = this.defaultColumns().map(c => ({- id: c.id,+ ngOnChanges (changes: SimpleChanges) {+ if (changes['defaultColumns']) {+ this.columns = this.defaultColumns().map(c => ({+ id: c.id,- label: c.label,- labelSmall: c.labelSmall,- sortable: c.sortable,+ label: c.label,+ labelSmall: c.labelSmall,+ sortable: c.sortable,- class: c.class || '',- selected: c.selected ?? true,- sortKey: c.sortKey || c.id as string,- isDisplayed: c.isDisplayed || (() => true)- }))+ class: c.class || '',+ selected: c.selected ?? true,+ sortKey: c.sortKey || c.id as string,+ isDisplayed: c.isDisplayed || (() => true)+ }))+ }}// ---------------------------------------------------------------------------diff --git a/client/src/app/shared/shared-tables/video-cell.component.html b/client/src/app/shared/shared-tables/video-cell.component.htmlindex 4dbc97f41b..dd1e49526c 100644--- a/client/src/app/shared/shared-tables/video-cell.component.html+++ b/client/src/app/shared/shared-tables/video-cell.component.html@@ -15,11 +15,11 @@</div><a *ngIf="video().channel" [routerLink]="getChannelUrl()" class="channel" [ngClass]="{ ellipsis: ellipsis }">- {{ video().channel?.displayName }}+ <span>{{ video().channel?.displayName }}</span>- <ng-container *ngIf="hostInfo()" i18n>- on {{ video().channel?.host }}- </ng-container>+ @if (displayEditorInfo() && user.isEditorOfChannel(video().channel)) {+ <my-collaborator-state class="ms-2" type="accepted" small="true"></my-collaborator-state>+ }</a></div>diff --git a/client/src/app/shared/shared-tables/video-cell.component.scss b/client/src/app/shared/shared-tables/video-cell.component.scssindex b24f29d51f..c67a7ba2ad 100644--- a/client/src/app/shared/shared-tables/video-cell.component.scss+++ b/client/src/app/shared/shared-tables/video-cell.component.scss@@ -40,6 +40,14 @@ my-video-thumbnail {.channel {color: pvar(--fg-200);text-decoration: none;+ display: inline-flex;+ align-items: center;+ margin-top: 0.25rem;@include font-size(14px);++ &:hover {+ opacity: 1;+ color: pvar(--fg-300);+ }}diff --git a/client/src/app/shared/shared-tables/video-cell.component.ts b/client/src/app/shared/shared-tables/video-cell.component.tsindex d519ec6aba..fdadf65835 100644--- a/client/src/app/shared/shared-tables/video-cell.component.ts+++ b/client/src/app/shared/shared-tables/video-cell.component.ts@@ -1,7 +1,8 @@import { CommonModule } from '@angular/common'import { booleanAttribute, Component, inject, input, OnInit } from '@angular/core'import { RouterLink } from '@angular/router'-import { ScreenService } from '@app/core'+import { AuthService, ScreenService } from '@app/core'+import { CollaboratorStateComponent } from '../shared-main/channel/collaborator-state.component'import { VideoChannel } from '../shared-main/channel/video-channel.model'import { Video } from '../shared-main/video/video.model'import { VideoThumbnailComponent } from '../shared-thumbnail/video-thumbnail.component'@@ -14,20 +15,26 @@ import { VideoThumbnailComponent } from '../shared-thumbnail/video-thumbnail.comimports: [CommonModule,RouterLink,- VideoThumbnailComponent+ VideoThumbnailComponent,+ CollaboratorStateComponent]})export class VideoCellComponent implements OnInit {private readonly screenService = inject(ScreenService)+ private readonly authService = inject(AuthService)readonly video = input.required<Video>()readonly size = input<'small' | 'normal'>('normal')- readonly thumbnail = input<boolean, boolean | string>(true, { transform: booleanAttribute })- readonly title = input<boolean, boolean | string>(true, { transform: booleanAttribute })- readonly hostInfo = input<boolean, boolean | string>(true, { transform: booleanAttribute })+ readonly thumbnail = input(true, { transform: booleanAttribute })+ readonly title = input(true, { transform: booleanAttribute })+ readonly displayEditorInfo = input(false, { transform: booleanAttribute })ellipsis: boolean+ get user () {+ return this.authService.getUser()+ }+ngOnInit () {this.ellipsis = !this.screenService.isInMobileView()}diff --git a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.html b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.htmlindex 1e4b112944..f0a2c1bcbd 100644--- a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.html+++ b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.html@@ -20,6 +20,27 @@</ng-template><ng-template #tableCells let-comment>++ <td *ngIf="table.isColumnDisplayed('video')">+ <div class="video">+ <a [href]="comment.localUrl" target="_blank" rel="noopener noreferrer" class="text-decoration-none d-inline-flex align-items-baseline">+ <span class="video-name">{{ comment.video.name }}</span>++ <my-global-icon iconName="external-link"></my-global-icon>+ </a>++ @if (comment.video.channel) {+ <a [routerLink]="[ '/c', comment.video.channel.name]" class="channel-sub-link-in-cell">+ <span>{{ comment.video.channel.displayName }}</span>++ @if (mode() === 'user' && user.isEditorOfChannel(comment.video.channel)) {+ <my-collaborator-state class="ms-2" type="accepted" small="true"></my-collaborator-state>+ }+ </a>+ }+ </div>+ </td>+<td *ngIf="table.isColumnDisplayed('account')"><a [href]="comment.account.localUrl" i18n-title title="Open account in a new tab" target="_blank" rel="noopener noreferrer"><div class="chip two-lines">@@ -32,12 +53,6 @@</a></td>- <td *ngIf="table.isColumnDisplayed('video')" class="video">- <em i18n>Commented video</em>-- <a [href]="comment.localUrl" target="_blank" rel="noopener noreferrer" class="text-decoration-none">{{ comment.video.name }}</a>- </td>-<td *ngIf="table.isColumnDisplayed('comment')" class="comment-content-cell"><span *ngIf="comment.heldForReview" class="pt-badge badge-red float-start me-2" i18n>Pending review</span>diff --git a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.scss b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.scssindex b0d3808404..7dfc3dccf7 100644--- a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.scss+++ b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.scss@@ -4,16 +4,13 @@.video {display: flex;flex-direction: column;+ justify-content: center;+}- em {- font-size: 11px;- }-- a {- color: pvar(--fg);+.video-name {+ max-width: 300px;- @include ellipsis;- }+ @include ellipsis;}.comment-content-cell {@@ -37,9 +34,3 @@}}}--@media screen and (max-width: $medium-view) {- .video {- align-items: flex-start !important;- }-}diff --git a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.ts b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.tsindex 806ee6eb01..552b6ae14d 100644--- a/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.ts+++ b/client/src/app/shared/shared-video-comment/video-comment-list-admin-owner.component.ts@@ -6,12 +6,14 @@ import { formatICU } from '@app/helpers'import { BulkService } from '@app/shared/shared-moderation/bulk.service'import { VideoCommentForAdminOrUser } from '@app/shared/shared-video-comment/video-comment.model'import { VideoCommentService } from '@app/shared/shared-video-comment/video-comment.service'-import { UserRight } from '@peertube/peertube-models'+import { BulkRemoveCommentsOfBody, UserRight } from '@peertube/peertube-models'import { switchMap } from 'rxjs'import { ActorAvatarComponent } from '../shared-actor-image/actor-avatar.component'import { AdvancedInputFilter, AdvancedInputFilterComponent } from '../shared-forms/advanced-input-filter.component'+import { GlobalIconComponent } from '../shared-icons/global-icon.component'import { ActionDropdownComponent, DropdownAction } from '../shared-main/buttons/action-dropdown.component'import { ButtonComponent } from '../shared-main/buttons/button.component'+import { CollaboratorStateComponent } from '../shared-main/channel/collaborator-state.component'import { PTDatePipe } from '../shared-main/common/date.pipe'import { NumberFormatterPipe } from '../shared-main/common/number-formatter.pipe'import { DataLoaderOptions, TableColumnInfo, TableComponent } from '../shared-tables/table.component'@@ -36,7 +38,9 @@ type ColumnName =PTDatePipe,RouterLink,TableComponent,- NumberFormatterPipe+ NumberFormatterPipe,+ GlobalIconComponent,+ CollaboratorStateComponent]})export class VideoCommentListAdminOwnerComponent implements OnInit, OnDestroy {@@ -60,8 +64,8 @@ export class VideoCommentListAdminOwnerComponent implements OnInit, OnDestroy {inputFilters: AdvancedInputFilter[] = []columns: TableColumnInfo<ColumnName>[] = [+ { id: 'video', label: $localize`Commented video`, sortable: false },{ id: 'account', label: $localize`Account`, sortable: false },- { id: 'video', label: $localize`Video`, sortable: false },{ id: 'comment', label: $localize`Comment`, sortable: false },{ id: 'autoTags', label: $localize`Auto tags`, sortable: false },{ id: 'createdAt', label: $localize`Date`, sortable: true }@@ -73,7 +77,7 @@ export class VideoCommentListAdminOwnerComponent implements OnInit, OnDestroy {this.dataLoader = this._dataLoader.bind(this)}- get authUser () {+ get user () {return this.auth.getUser()}@@ -100,13 +104,23 @@ export class VideoCommentListAdminOwnerComponent implements OnInit, OnDestroy {{label: $localize`Delete this comment`,handler: comment => this.removeComment(comment),- isDisplayed: () => this.mode() === 'user' || this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)+ isDisplayed: () => this.mode() === 'user' || this.user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)},{label: $localize`Delete all comments of this account`,- description: $localize`Comments are deleted after a few minutes`,++ description: this.mode() === 'user'+ ? this.user.isCollaboratingToChannels()+ ? $localize`Whether they're from channels you own or channels for which you're an editor`+ : $localize`This will delete comments on all your videos`+ : $localize`This will delete comments on all videos from your platform`,+handler: comment => this.removeCommentsOfAccount(comment),- isDisplayed: () => this.mode() === 'admin' && this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)+ isDisplayed: () => {+ if (this.mode() === 'user') return true++ return this.mode() === 'admin' && this.user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)+ }}],[@@ -128,7 +142,7 @@ export class VideoCommentListAdminOwnerComponent implements OnInit, OnDestroy {{label: $localize`Delete`,handler: comments => this.removeComments(comments),- isDisplayed: () => this.mode() === 'user' || this.authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT),+ isDisplayed: () => this.mode() === 'user' || this.user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT),iconName: 'delete'},{@@ -267,13 +281,15 @@ export class VideoCommentListAdminOwnerComponent implements OnInit, OnDestroy {}private async removeCommentsOfAccount (comment: VideoCommentForAdminOrUser) {- const message = $localize`Do you really want to delete all comments of ${comment.by}?`+ const message = $localize`Do you really want to delete all comments of ${comment.by}? Comments are deleted after a few minutes.`const res = await this.confirmService.confirm(message, $localize`Delete`)if (res === false) return- const options = {+ const options: BulkRemoveCommentsOfBody = {accountName: comment.by,- scope: 'instance' as 'instance'+ scope: this.mode() === 'admin'+ ? 'instance'+ : 'my-videos-and-collaborations'}this.bulkService.removeCommentsOf(options)diff --git a/client/src/app/shared/shared-video-comment/video-comment.model.ts b/client/src/app/shared/shared-video-comment/video-comment.model.tsindex 6a5d8e6aca..b1c2f40691 100644--- a/client/src/app/shared/shared-video-comment/video-comment.model.ts+++ b/client/src/app/shared/shared-video-comment/video-comment.model.ts@@ -1,6 +1,7 @@import { getBackendHost } from '@app/helpers'import {Account as AccountInterface,+ VideoChannelSummary,VideoCommentForAdminOrUser as VideoCommentForAdminOrUserServerModel,VideoComment as VideoCommentServerModel} from '@peertube/peertube-models'@@ -70,6 +71,8 @@ export class VideoCommentForAdminOrUser implements VideoCommentForAdminOrUserSeruuid: stringname: stringlocalUrl: string++ channel: VideoChannelSummary}heldForReview: boolean@@ -98,7 +101,9 @@ export class VideoCommentForAdminOrUser implements VideoCommentForAdminOrUserSerid: hash.video.id,uuid: hash.video.uuid,name: hash.video.name,- localUrl: Video.buildWatchUrl(hash.video)+ localUrl: Video.buildWatchUrl(hash.video),++ channel: hash.video.channel}this.localUrl = this.video.localUrl + ';threadId=' + this.threadIddiff --git a/client/src/app/shared/shared-video-comment/video-comment.service.ts b/client/src/app/shared/shared-video-comment/video-comment.service.tsindex ed85b5cf58..83d932dbb7 100644--- a/client/src/app/shared/shared-video-comment/video-comment.service.ts+++ b/client/src/app/shared/shared-video-comment/video-comment.service.ts@@ -86,6 +86,7 @@ export class VideoCommentService {let params = new HttpParams()params = this.restService.addRestGetParams(params, pagination, sort)+ params = params.set('includeCollaborations', 'true')if (search) {params = this.buildParamsFromSearch(search, params)diff --git a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.html b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.htmlindex 3006bd8781..ebf640963e 100644--- a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.html+++ b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.html@@ -17,7 +17,7 @@<my-action-dropdown[actions]="videoActions" [label]="label()" [entry]="{ video: video() }"- [buttonSize]="buttonSize()" [placement]="placement()" [buttonDirection]="buttonDirection()" [buttonStyled]="buttonStyled()"+ [buttonSize]="buttonSize()" [placement]="placement()" [buttonIcon]="buttonIcon()" [buttonStyled]="buttonStyled()"container="body" (openChange)="dropdownOpened = true"></my-action-dropdown>diff --git a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.tsindex d10a561167..0239076e0f 100644--- a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts+++ b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts@@ -8,8 +8,8 @@ import { Actor } from '../shared-main/account/actor.model'import {ActionDropdownComponent,DropdownAction,- DropdownButtonSize,- DropdownDirection+ DropdownButtonIcon,+ DropdownButtonSize} from '../shared-main/buttons/action-dropdown.component'import { VideoCaptionService } from '../shared-main/video-caption/video-caption.service'import { RedundancyService } from '../shared-main/video/redundancy.service'@@ -102,7 +102,7 @@ export class VideoActionsDropdownComponent implements OnChanges {readonly buttonStyled = input(false, { transform: booleanAttribute })readonly buttonSize = input<DropdownButtonSize>('normal')- readonly buttonDirection = input<DropdownDirection>('vertical')+ readonly buttonIcon = input<DropdownButtonIcon>('more-vertical')readonly transcriptionWidgetOpened = input<boolean>(undefined)diff --git a/client/src/app/shared/shared-video-miniature/video-miniature.component.scss b/client/src/app/shared/shared-video-miniature/video-miniature.component.scssindex 7e90ff1e80..58f6c58bab 100644--- a/client/src/app/shared/shared-video-miniature/video-miniature.component.scss+++ b/client/src/app/shared/shared-video-miniature/video-miniature.component.scss@@ -1,8 +1,8 @@-@use '_variables' as *;-@use '_mixins' as *;-@use '_miniature' as *;+@use "_variables" as *;+@use "_mixins" as *;+@use "_miniature" as *;-$more-button-width: 40px;+$more-button-width: 30px;.video-miniature {--co-fs-small: #{$miniature-fs-small};@@ -70,6 +70,7 @@ my-actor-host {.video-actions {width: $more-button-width;+ text-align: end;::ng-deep .dropdown-root:not(.show) {opacity: 0;@@ -107,7 +108,7 @@ my-actor-host {my-video-thumbnail {margin-bottom: 0.35rem;- @include block-ratio($selector: '::ng-deep .video-thumbnail');+ @include block-ratio($selector: "::ng-deep .video-thumbnail");}&.has-avatar .video-info {@@ -123,11 +124,11 @@ my-actor-host {@include left(-2px);- &[actorType=account] {+ &[actorType="account"] {border-radius: $account-avatar-radius;}- &[actorType=channel] {+ &[actorType="channel"] {border-radius: $channel-avatar-radius;}diff --git a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scss b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scssindex bd8831d843..b8ba0c5205 100644--- a/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scss+++ b/client/src/app/shared/shared-video-playlist/video-playlist-miniature.component.scss@@ -1,10 +1,11 @@-@use '_variables' as *;-@use '_mixins' as *;-@use '_miniature' as *;+@use "_variables" as *;+@use "_mixins" as *;+@use "_miniature" as *;.miniature {display: inline-block;width: 100%;+ vertical-align: middle;&.no-videos:not(.to-manage) {a {@@ -42,8 +43,12 @@}.miniature-info {+ display: flex;+ flex-direction: column;.miniature-name {+ display: inline-block;+@include miniature-name;}@@ -55,7 +60,6 @@}.privacy-date {- margin-top: 5px;color: pvar(--fg-200);font-size: $miniature-fs-small;@@ -63,7 +67,7 @@font-weight: $font-semibold;&::after {- content: '-';+ content: "-";margin: 0 3px;}}@@ -78,17 +82,13 @@}.miniature:not(.display-as-row) {-.miniature-name {+ margin-top: 0.5rem;font-size: $miniature-fs-big;- margin-top: 10px;- margin-bottom: 5px;}.miniature-thumbnail {- margin-bottom: 5px;-- @include block-ratio($selector: '::ng-deep a');+ @include block-ratio($selector: "::ng-deep a");}}@@ -104,6 +104,7 @@.privacy-date {font-size: $miniature-fs-row-small;+ margin-top: 0.25rem;}.miniature-thumbnail {diff --git a/client/src/app/shared/shared-video-playlist/video-playlist.service.ts b/client/src/app/shared/shared-video-playlist/video-playlist.service.tsindex dbc45dd44f..7df2c6c4ec 100644--- a/client/src/app/shared/shared-video-playlist/video-playlist.service.ts+++ b/client/src/app/shared/shared-video-playlist/video-playlist.service.ts@@ -80,6 +80,7 @@ export class VideoPlaylistService {componentPagination?: ComponentPaginationLightrestPagination?: RestPaginationsearch?: string+ includeCollaborations?: boolean}): Observable<ResultList<VideoPlaylist>> {const { videoChannel } = options@@ -93,6 +94,7 @@ export class VideoPlaylistService {sort: SortMeta | stringrestPagination?: RestPaginationsearch?: string+ includeCollaborations?: boolean}): Observable<ResultList<VideoPlaylist>> {const { account } = options@@ -107,8 +109,9 @@ export class VideoPlaylistService {componentPagination?: ComponentPaginationLightrestPagination?: RestPaginationsearch?: string+ includeCollaborations?: boolean}) {- const { url, sort, search } = options+ const { url, sort, search, includeCollaborations } = optionslet params = new HttpParams()@@ -119,6 +122,7 @@ export class VideoPlaylistService {params = this.restService.addRestGetParams(params, restPagination, sort)+ if (includeCollaborations) params = params.append('includeCollaborations', 'true')if (search) params = this.restService.addObjectParams(params, { search })return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })diff --git a/client/src/app/shared/standalone-channels/channel-toggle.component.html b/client/src/app/shared/standalone-channels/channel-toggle.component.htmlindex 796c548ae0..8c50ac834c 100644--- a/client/src/app/shared/standalone-channels/channel-toggle.component.html+++ b/client/src/app/shared/standalone-channels/channel-toggle.component.html@@ -1,5 +1,15 @@<button class="root button-unstyle" [ngClass]="{ active: checked() }" [title]="label()" (click)="toggle()"><my-actor-avatar [actor]="channel()" actorType="channel" size="34"></my-actor-avatar>- <div class="name">{{ channel().displayName }}</div>+ <div class="info" [ngClass]="{ 'has-collaborator-state': user.isCollaboratingToChannels() }">+ <div class="name">{{ channel().displayName }}</div>++ @if (user.isCollaboratingToChannels()) {+ @if (user.isEditorOfChannel(channel())) {+ <my-collaborator-state small="true" type="accepted"></my-collaborator-state>+ } @else {+ <my-collaborator-state small="true" type="owner"></my-collaborator-state>+ }+ }+ </div></button>diff --git a/client/src/app/shared/standalone-channels/channel-toggle.component.scss b/client/src/app/shared/standalone-channels/channel-toggle.component.scssindex 4da52d131c..7429948246 100644--- a/client/src/app/shared/standalone-channels/channel-toggle.component.scss+++ b/client/src/app/shared/standalone-channels/channel-toggle.component.scss@@ -1,10 +1,13 @@-@use '_variables' as *;-@use '_mixins' as *;+@use "_variables" as *;+@use "_mixins" as *;.root {position: relative;display: flex;align-items: center;+ text-align: start;++ line-height: 1.2;// Don't use mixin, we need the exact valuepadding-inline-start: 17px;@@ -14,18 +17,28 @@}}-.name {+.info {border-radius: 4px;- color: pvar(--fg-400);background-color: pvar(--bg-secondary-400);- max-width: 130px;+ max-width: 150px;+padding-top: 0.75rem;padding-bottom: 0.75rem;+ padding-inline-start: 25px; // Don't use a mixin that would use rfs, we need the exact value here++ @include padding-right(1rem);++ .name {+ color: pvar(--fg-400);++ @include ellipsis;+ @include font-size(14px);+ }- @include padding-right(0.5rem);- @include padding-left(24px);- @include font-size(14px);- @include ellipsis;+ &.has-collaborator-state {+ padding-top: 0.5rem;+ padding-bottom: 0.5rem;+ }}my-actor-avatar {@@ -36,9 +49,12 @@ my-actor-avatar {}.root.active {+ .info {+ background-color: pvar(--bg-secondary-450);+ }+.name {font-weight: $font-bold;- background-color: pvar(--bg-secondary-450);}my-actor-avatar {diff --git a/client/src/app/shared/standalone-channels/channel-toggle.component.ts b/client/src/app/shared/standalone-channels/channel-toggle.component.tsindex a715c0fc9a..709ee17bb4 100644--- a/client/src/app/shared/standalone-channels/channel-toggle.component.ts+++ b/client/src/app/shared/standalone-channels/channel-toggle.component.ts@@ -1,8 +1,10 @@import { CommonModule } from '@angular/common'-import { Component, forwardRef, input, model } from '@angular/core'+import { Component, forwardRef, inject, input, model } from '@angular/core'import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'+import { AuthService } from '@app/core'import { VideoChannel } from '@peertube/peertube-models'import { ActorAvatarComponent } from '../shared-actor-image/actor-avatar.component'+import { CollaboratorStateComponent } from '../shared-main/channel/collaborator-state.component'@Component({selector: 'my-channel-toggle',@@ -18,15 +20,22 @@ import { ActorAvatarComponent } from '../shared-actor-image/actor-avatar.componestandalone: true,imports: [CommonModule,- ActorAvatarComponent+ ActorAvatarComponent,+ CollaboratorStateComponent]})export class ChannelToggleComponent implements ControlValueAccessor {+ private authService = inject(AuthService)+readonly checked = model(false)readonly channel = input.required<VideoChannel>()readonly inputName = input<string>(undefined)readonly label = input($localize`Toggle this channel`)+ get user () {+ return this.authService.getUser()+ }+propagateChange = (_: any) => {// empty}diff --git a/client/src/app/shared/standalone-channels/video-channel-create.component.ts b/client/src/app/shared/standalone-channels/video-channel-create.component.tsdeleted file mode 100644index 9ce6178e6b..0000000000--- a/client/src/app/shared/standalone-channels/video-channel-create.component.ts+++ /dev/null@@ -1,98 +0,0 @@-import { AfterViewInit, Component, inject } from '@angular/core'-import { Router } from '@angular/router'-import { AuthService, HooksService, Notifier } from '@app/core'-import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'-import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'-import { HttpStatusCode, PlayerChannelSettings, VideoChannelCreate } from '@peertube/peertube-models'-import { of } from 'rxjs'-import { switchMap } from 'rxjs/operators'-import { PlayerSettingsService } from '../shared-video/player-settings.service'-import { FormValidatedOutput, VideoChannelEditComponent } from './video-channel-edit.component'--@Component({- template: `- <my-video-channel-edit- mode="create" [channel]="channel" [rawPlayerSettings]="rawPlayerSettings" [error]="error"- (formValidated)="onFormValidated($event)"- >- </my-video-channel-edit>- `,- imports: [- VideoChannelEditComponent- ],- providers: [- PlayerSettingsService- ]-})-export class VideoChannelCreateComponent implements AfterViewInit {- private authService = inject(AuthService)- private notifier = inject(Notifier)- private router = inject(Router)- private videoChannelService = inject(VideoChannelService)- private hooks = inject(HooksService)- private playerSettingsService = inject(PlayerSettingsService)-- error: string- channel = new VideoChannel({})- rawPlayerSettings: PlayerChannelSettings = {- theme: 'instance-default'- }-- ngAfterViewInit () {- this.hooks.runAction('action:video-channel-create.init', 'video-channel')- }-- onFormValidated (output: FormValidatedOutput) {- this.error = undefined-- const channelCreate: VideoChannelCreate = {- name: output.channel.name,- displayName: output.channel.displayName,- description: output.channel.description,- support: output.channel.support- }-- this.videoChannelService.createVideoChannel(channelCreate)- .pipe(- switchMap(() => {- return this.playerSettingsService.updateChannelSettings({- channelHandle: output.channel.name,- settings: {- theme: output.playerSettings.theme- }- })- }),- switchMap(() => this.uploadAvatar(output.channel.name, output.avatar)),- switchMap(() => this.uploadBanner(output.channel.name, output.banner))- ).subscribe({- next: () => {- this.authService.refreshUserInformation()-- this.notifier.success($localize`Video channel ${channelCreate.displayName} created.`)- this.router.navigate([ '/my-library', 'video-channels' ])- },-- error: err => {- let message = err.message-- if (err.status === HttpStatusCode.CONFLICT_409) {- message = $localize`Channel name "${channelCreate.name}" already exists on this platform.`- }-- this.notifier.error(message)- }- })- }-- private uploadAvatar (username: string, avatar?: FormData) {- if (!avatar) return of(undefined)-- return this.videoChannelService.changeVideoChannelImage(username, avatar, 'avatar')- }-- private uploadBanner (username: string, banner?: FormData) {- if (!banner) return of(undefined)-- return this.videoChannelService.changeVideoChannelImage(username, banner, 'banner')- }-}diff --git a/client/src/app/shared/standalone-channels/video-channel-edit.component.html b/client/src/app/shared/standalone-channels/video-channel-edit.component.htmldeleted file mode 100644index 5582c43f9b..0000000000--- a/client/src/app/shared/standalone-channels/video-channel-edit.component.html+++ /dev/null@@ -1,100 +0,0 @@-<my-alert *ngIf="error()" type="danger">{{ error() }}</my-alert>--<div class="pt-4">- <form (ngSubmit)="onFormValidated()" [formGroup]="form">-- <div class="pt-two-cols"> <!-- channel grid -->- <div class="title-col">- @if (mode() === 'create') {- <h2 i18n>NEW CHANNEL</h2>- } @else {- <h2 i18n>UPDATE CHANNEL</h2>- }- </div>-- <div class="content-col">- <my-actor-banner-edit- *ngIf="channel()" previewImage="true" class="d-block mb-4"- [bannerUrl]="channel()?.bannerUrl" (bannerChange)="onBannerChange($event)" (bannerDelete)="onBannerDelete()"- ></my-actor-banner-edit>-- <my-actor-avatar-edit- *ngIf="channel()" class="d-block mb-4" actorType="channel"- [displayName]="channel().displayName" previewImage="true" [avatars]="channel().avatars"- [username]="mode() === 'update' && channel().name" [subscribers]="mode() === 'update' && channel().followersCount"- (avatarChange)="onAvatarChange($event)" (avatarDelete)="onAvatarDelete()"- ></my-actor-avatar-edit>-- <div class="form-group" *ngIf="mode() === 'create'">- <label i18n for="name">Name</label>-- <div class="input-group">- <input- type="text" id="name" i18n-placeholder placeholder="Example: my_channel"- formControlName="name" [ngClass]="{ 'input-error': formErrors.name }" class="form-control w-auto flex-grow-1 d-block"- >- <div class="input-group-text">@{{ instanceHost }}</div>- </div>- <div *ngIf="formErrors.name" class="form-error" role="alert">- {{ formErrors.name }}- </div>- </div>-- <div class="form-group">- <label i18n for="displayName">Display name</label>- <input- type="text" id="displayName" class="form-control"- formControlName="displayName" [ngClass]="{ 'input-error': formErrors.displayName }"- >- <div *ngIf="formErrors.displayName" class="form-error" role="alert">- {{ formErrors.displayName }}- </div>- </div>-- <div class="form-group markdown-block">- <label i18n for="description">Description</label>-- <my-help helpType="markdownText" supportRelMe="true"></my-help>-- <my-markdown-textarea- inputId="description" formControlName="description"- markdownType="enhanced" [formError]="formErrors.description" withEmoji="true" withHtml="true"- ></my-markdown-textarea>-- <div *ngIf="formErrors.description" class="form-error" role="alert">- {{ formErrors.description }}- </div>- </div>-- <div class="form-group markdown-block">- <label i18n for="support">Support</label>-- <div class="form-group-description" i18n>- This is text that helps people visiting your channel page <strong>understand how to support you</strong>. You can use <my-markdown-hint helpType="markdownText">Markdown Language</my-markdown-hint>, including <strong>links to your fundraising tools</strong>.- </div>-- <my-markdown-textarea- inputId="support" formControlName="support"- markdownType="enhanced" [formError]="formErrors.support" withEmoji="true" withHtml="true"- ></my-markdown-textarea>- </div>-- <div class="form-group" *ngIf="isBulkUpdateVideosDisplayed()">- <my-peertube-checkbox- inputName="bulkVideosSupportUpdate" formControlName="bulkVideosSupportUpdate"- i18n-labelText labelText="Overwrite support field of all videos of this channel"- ></my-peertube-checkbox>- </div>-- <div class="form-group">- <label i18n for="playerTheme">Player Theme</label>-- <my-select-player-theme formControlName="playerTheme" inputId="playerTheme" mode="channel">- </my-select-player-theme>- </div>-- <input type="submit" class="peertube-button primary-button mt-4" value="{{ getFormButtonTitle() }}" [disabled]="!form.valid">- </div>- </div>- </form>-</div>diff --git a/client/src/app/shared/standalone-channels/video-channel-edit.component.ts b/client/src/app/shared/standalone-channels/video-channel-edit.component.tsdeleted file mode 100644index 687d55556e..0000000000--- a/client/src/app/shared/standalone-channels/video-channel-edit.component.ts+++ /dev/null@@ -1,178 +0,0 @@-import { CommonModule } from '@angular/common'-import { Component, inject, input, OnInit, output } from '@angular/core'-import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'-import { VideoChannel } from '@app/shared/shared-main/channel/video-channel.model'-import { PlayerChannelSettings } from '@peertube/peertube-models'-import { BuildFormArgumentTyped, FormReactiveErrorsTyped, FormReactiveMessagesTyped } from '../form-validators/form-validator.model'-import {- VIDEO_CHANNEL_DESCRIPTION_VALIDATOR,- VIDEO_CHANNEL_DISPLAY_NAME_VALIDATOR,- VIDEO_CHANNEL_NAME_VALIDATOR,- VIDEO_CHANNEL_SUPPORT_VALIDATOR-} from '../form-validators/video-channel-validators'-import { ActorAvatarEditComponent } from '../shared-actor-image-edit/actor-avatar-edit.component'-import { ActorBannerEditComponent } from '../shared-actor-image-edit/actor-banner-edit.component'-import { FormReactiveService } from '../shared-forms/form-reactive.service'-import { MarkdownTextareaComponent } from '../shared-forms/markdown-textarea.component'-import { PeertubeCheckboxComponent } from '../shared-forms/peertube-checkbox.component'-import { SelectPlayerThemeComponent } from '../shared-forms/select/select-player-theme.component'-import { HelpComponent } from '../shared-main/buttons/help.component'-import { AlertComponent } from '../shared-main/common/alert.component'-import { MarkdownHintComponent } from '../shared-main/text/markdown-hint.component'--type Form = {- name: FormControl<string>- displayName: FormControl<string>- description: FormControl<string>- support: FormControl<string>- playerTheme: FormControl<PlayerChannelSettings['theme']>- bulkVideosSupportUpdate: FormControl<boolean>-}--export type FormValidatedOutput = {- avatar: FormData- banner: FormData-- playerSettings: {- theme: PlayerChannelSettings['theme']- }-- channel: {- name: string- displayName: string- description: string- support: string- bulkVideosSupportUpdate: boolean- }-}--@Component({- selector: 'my-video-channel-edit',- templateUrl: './video-channel-edit.component.html',- styleUrls: [ './video-channel-edit.component.scss' ],- imports: [- CommonModule,- FormsModule,- ReactiveFormsModule,- ActorBannerEditComponent,- ActorAvatarEditComponent,- HelpComponent,- MarkdownTextareaComponent,- PeertubeCheckboxComponent,- AlertComponent,- MarkdownHintComponent,- SelectPlayerThemeComponent- ]-})-export class VideoChannelEditComponent implements OnInit {- private formReactiveService = inject(FormReactiveService)-- readonly mode = input.required<'create' | 'update'>()- readonly channel = input.required<VideoChannel>()- readonly rawPlayerSettings = input.required<PlayerChannelSettings>()- readonly error = input<string>()-- readonly formValidated = output<FormValidatedOutput>()-- form: FormGroup<Form>- formErrors: FormReactiveErrorsTyped<Form> = {}- validationMessages: FormReactiveMessagesTyped<Form> = {}-- private avatar: FormData- private banner: FormData- private oldSupportField: string-- ngOnInit () {- this.buildForm()-- this.oldSupportField = this.channel().support- }-- private buildForm () {- const obj: BuildFormArgumentTyped<Form> = {- name: this.mode() === 'create'- ? VIDEO_CHANNEL_NAME_VALIDATOR- : null,- displayName: VIDEO_CHANNEL_DISPLAY_NAME_VALIDATOR,- description: VIDEO_CHANNEL_DESCRIPTION_VALIDATOR,- support: VIDEO_CHANNEL_SUPPORT_VALIDATOR,- bulkVideosSupportUpdate: null,- playerTheme: null- }-- const defaultValues = {- displayName: this.channel().displayName,- description: this.channel().description,- support: this.channel().support,- playerTheme: this.rawPlayerSettings().theme- }-- const {- form,- formErrors,- validationMessages- } = this.formReactiveService.buildForm<Form>(obj, defaultValues)-- this.form = form- this.formErrors = formErrors- this.validationMessages = validationMessages- }-- getFormButtonTitle () {- if (this.mode() === 'update') {- return $localize`Update ${this.channel().name}`- }-- return $localize`Create your channel`- }-- onAvatarChange (formData: FormData) {- this.avatar = formData- }-- onAvatarDelete () {- this.avatar = null- }-- onBannerChange (formData: FormData) {- this.banner = formData- }-- onBannerDelete () {- this.banner = null- }-- get instanceHost () {- return window.location.host- }-- isBulkUpdateVideosDisplayed () {- if (this.mode() === 'create') return false-- if (this.oldSupportField === undefined) return false-- return this.oldSupportField !== this.form.value.support- }-- onFormValidated () {- const body = this.form.value-- this.formValidated.emit({- avatar: this.avatar,- banner: this.banner,- playerSettings: {- theme: body.playerTheme- },- channel: {- name: body.name,- displayName: body.displayName,- description: body.description || null,- support: body.support || null,-- bulkVideosSupportUpdate: this.mode() === 'update'- ? body.bulkVideosSupportUpdate || false- : undefined- }- })- }-}diff --git a/client/src/app/shared/standalone-channels/video-channel-update.component.ts b/client/src/app/shared/standalone-channels/video-channel-update.component.tsdeleted file mode 100644index f61033d184..0000000000--- a/client/src/app/shared/standalone-channels/video-channel-update.component.ts+++ /dev/null@@ -1,154 +0,0 @@-import { AfterViewInit, Component, inject, OnDestroy, OnInit } from '@angular/core'-import { ActivatedRoute } from '@angular/router'-import { AuthService, HooksService, Notifier, RedirectService } from '@app/core'-import { genericUploadErrorHandler } from '@app/helpers'-import { VideoChannelService } from '@app/shared/shared-main/channel/video-channel.service'-import { shallowCopy } from '@peertube/peertube-core-utils'-import { PlayerChannelSettings, VideoChannelUpdate } from '@peertube/peertube-models'-import { catchError, forkJoin, Subscription, switchMap, tap, throwError } from 'rxjs'-import { VideoChannel } from '../shared-main/channel/video-channel.model'-import { PlayerSettingsService } from '../shared-video/player-settings.service'-import { FormValidatedOutput, VideoChannelEditComponent } from './video-channel-edit.component'--@Component({- selector: 'my-video-channel-update',- template: `- @if (channel && rawPlayerSettings) {- <my-video-channel-edit- mode="update" [channel]="channel" [rawPlayerSettings]="rawPlayerSettings" [error]="error"- (formValidated)="onFormValidated($event)"- >- </my-video-channel-edit>- }- `,- imports: [- VideoChannelEditComponent- ],- providers: [- PlayerSettingsService- ]-})-export class VideoChannelUpdateComponent implements OnInit, AfterViewInit, OnDestroy {- private authService = inject(AuthService)- private notifier = inject(Notifier)- private route = inject(ActivatedRoute)- private videoChannelService = inject(VideoChannelService)- private playerSettingsService = inject(PlayerSettingsService)- private redirectService = inject(RedirectService)- private hooks = inject(HooksService)-- channel: VideoChannel- rawPlayerSettings: PlayerChannelSettings- error: string-- private paramsSub: Subscription-- ngOnInit () {- this.paramsSub = this.route.params.subscribe(routeParams => {- const videoChannelName = routeParams['videoChannelName']-- forkJoin([- this.videoChannelService.getVideoChannel(videoChannelName),- this.playerSettingsService.getChannelSettings({ channelHandle: videoChannelName, raw: true })- ]).subscribe({- next: ([ channel, rawPlayerSettings ]) => {- this.channel = channel- this.rawPlayerSettings = rawPlayerSettings-- this.hooks.runAction('action:video-channel-update.video-channel.loaded', 'video-channel', { videoChannel: this.channel })- },-- error: err => this.notifier.error(err.message)- })- })- }-- ngAfterViewInit () {- this.hooks.runAction('action:video-channel-update.init', 'video-channel')- }-- ngOnDestroy () {- if (this.paramsSub) this.paramsSub.unsubscribe()- }-- onFormValidated (output: FormValidatedOutput) {- this.error = undefined-- const videoChannelUpdate: VideoChannelUpdate = {- displayName: output.channel.displayName,- description: output.channel.description,- support: output.channel.support,- bulkVideosSupportUpdate: output.channel.bulkVideosSupportUpdate- }-- this.videoChannelService.updateVideoChannel(this.channel.name, videoChannelUpdate)- .pipe(- switchMap(() => {- return this.playerSettingsService.updateChannelSettings({- channelHandle: this.channel.name,- settings: {- theme: output.playerSettings.theme- }- })- }),- switchMap(() => this.updateOrDeleteAvatar(output.avatar)),- switchMap(() => this.updateOrDeleteBanner(output.banner))- )- .subscribe({- next: () => {- // So my-actor-avatar component detects changes- this.channel = shallowCopy(this.channel)-- this.authService.refreshUserInformation()-- this.notifier.success($localize`Video channel ${videoChannelUpdate.displayName} updated.`)-- this.redirectService.redirectToPreviousRoute('/c/' + this.channel.name)- },-- error: err => this.notifier.error(err.message)- })- }-- private updateOrDeleteAvatar (avatar: FormData) {- if (!avatar) {- return this.videoChannelService.deleteVideoChannelImage(this.channel.name, 'avatar')- .pipe(tap(() => this.channel.resetAvatar()))- }-- return this.videoChannelService.changeVideoChannelImage(this.channel.name, avatar, 'avatar')- .pipe(- tap(data => this.channel.updateAvatar(data.avatars)),- catchError(err =>- throwError(() => {- return new Error(genericUploadErrorHandler({- err,- name: $localize`avatar`,- notifier: this.notifier- }))- })- )- )- }-- private updateOrDeleteBanner (banner: FormData) {- if (!banner) {- return this.videoChannelService.deleteVideoChannelImage(this.channel.name, 'banner')- .pipe(tap(() => this.channel.resetBanner()))- }-- return this.videoChannelService.changeVideoChannelImage(this.channel.name, banner, 'banner')- .pipe(- tap(data => this.channel.updateBanner(data.banners)),- catchError(err =>- throwError(() => {- return new Error(genericUploadErrorHandler({- err,- name: $localize`banner`,- notifier: this.notifier- }))- })- )- )- }-}diff --git a/client/src/app/shared/standalone-notifications/user-notification-content.component.html b/client/src/app/shared/standalone-notifications/user-notification-content.component.htmlnew file mode 100644index 0000000000..871957c00c--- /dev/null+++ b/client/src/app/shared/standalone-notifications/user-notification-content.component.html@@ -0,0 +1,281 @@+<div class="root">+ @switch (n.payload.type) {+ @case (1) { <!-- UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION -->+ @if (n.payload.video) {+ <my-actor-avatar [size]="imageSize" [actor]="n.payload.video.channel" actorType="channel"></my-actor-avatar>++ <div class="message" i18n>+ <strong>{{ n.payload.video.channel.displayName }}</strong> published a new video: {{ n.payload.video.name }}+ </div>+ } @else {+ <my-global-icon iconName="alert"></my-global-icon>++ <div class="message" i18n>The notification concerns a video now unavailable</div>+ }+ }++ @case (5) { <!-- UserNotificationType.UNBLACKLIST_ON_MY_VIDEO -->+ <my-global-icon iconName="undo"></my-global-icon>++ <div class="message" i18n>Your video <strong>{{ n.payload.video.name }}</strong> has been unblocked</div>+ }++ @case (4) { <!-- UserNotificationType.BLACKLIST_ON_MY_VIDEO -->+ <my-global-icon iconName="no"></my-global-icon>++ <div class="message" i18n>Your video <strong>{{ n.payload.videoBlacklist.video.name }}</strong> has been blocked</div>+ }++ @case (3) { <!-- UserNotificationType.NEW_ABUSE_FOR_MODERATORS -->+ <my-global-icon iconName="flag"></my-global-icon>++ @if (n.payload.abuse.video) {+ <div class="message" i18n>A new <strong>video abuse</strong> has been created on video {{ n.payload.abuse.video.name }}</div>+ } @else if (n.payload.abuse.comment) {+ <div class="message" i18n>A new <strong>comment abuse</strong> has been created on video {{ n.payload.abuse.comment.video.name }}</div>+ } @else if (n.payload.abuse.account) {+ <div class="message" i18n>A new <strong>account abuse</strong> has been created on account {{ n.payload.abuse.account.displayName }}</div>+ } @else { <!-- Deleted entity associated to the abuse -->+ <div class="message" i18n>A new <strong>abuse</strong> has been created</div>+ }+ }++ @case (15) { <!-- UserNotificationType.ABUSE_STATE_CHANGE -->+ <my-global-icon iconName="flag"></my-global-icon>++ @if (isAbuseAccepted(n)) {+ @if (n.payload.abuse.video) {+ <div class="message" i18n>Your report of <strong>the video {{ n.payload.abuse.video.name }}</strong> has been accepted</div>+ } @else if (n.payload.abuse.comment) {+ <div class="message" i18n>Your report of <strong>the comment</strong> in the video <strong>{{ n.payload.abuse.comment.video.name }}</strong> has been accepted</div>+ } @else if (n.payload.abuse.account) {+ <div class="message" i18n>Your report of <strong>the account {{ n.payload.abuse.account.displayName }}</strong> has been accepted</div>+ } @else {+ <div class="message" i18n>Your <strong>report {{ n.payload.abuse.id }}</strong> has been accepted</div>+ }+ } @else {+ @if (n.payload.abuse.video) {+ <div class="message" i18n>Your report of <strong>the video {{ n.payload.abuse.video.name }}</strong> has been rejected</div>+ } @else if (n.payload.abuse.comment) {+ <div class="message" i18n>Your report of <strong>the comment</strong> in the video <strong>{{ n.payload.abuse.comment.video.name }}</strong> has been rejected</div>+ } @else if (n.payload.abuse.account) {+ <div class="message" i18n>Your report of <strong>the account {{ n.payload.abuse.account.displayName }}</strong> has been rejected</div>+ } @else {+ <div class="message" i18n>Your <strong>report {{ n.payload.abuse.id }}</strong> has been rejected</div>+ }+ }+ }++ @case (16) { <!-- UserNotificationType.ABUSE_NEW_MESSAGE -->+ <my-global-icon iconName="flag"></my-global-icon>++ @if (n.payload.abuse.video) {+ <div class="message" i18n>Report of <strong>the video {{ n.payload.abuse.video.name }}</strong> has a new message</div>+ } @else if (n.payload.abuse.comment) {+ <div class="message" i18n>Report of <strong>the comment</strong> in the video <strong>{{ n.payload.abuse.comment.video.name }}</strong> has a new message</div>+ } @else if (n.payload.abuse.account) {+ <div class="message" i18n>Report of <strong>the account {{ n.payload.abuse.account.displayName }}</strong> has a new message</div>+ } @else {+ <div class="message" i18n><strong>Report {{ n.payload.abuse.id }}</strong> has a new message</div>+ }+ }++ @case (12) { <!-- UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS -->+ <my-global-icon iconName="no"></my-global-icon>++ <div class="message" i18n>The recently added video <strong>{{ n.payload.videoBlacklist.video.name }}</strong> has been automatically blocked</div>+ }++ @case (2) {+ @if (n.payload.comment) {+ <my-actor-avatar [size]="imageSize" [actor]="n.payload.comment.account" actorType="account"></my-actor-avatar>++ <div class="message" i18n>+ {{ n.payload.comment.account.displayName }} commented your video <strong>{{ n.payload.comment.video.name }}</strong>++ @if (n.payload.comment.heldForReview) {+ <div>This comment requires your approval</div>+ }+ </div>+ } @else {+ <my-global-icon iconName="alert"></my-global-icon>++ <div class="message" i18n>The notification concerns a comment now unavailable</div>+ }+ }++ @case (6) { <!-- UserNotificationType.MY_VIDEO_PUBLISHED -->+ <my-global-icon iconName="film"></my-global-icon>++ <div class="message" i18n>Your video <strong>{{ n.payload.video.name }}</strong> has been published</div>+ }++ @case (7) { <!-- UserNotificationType.MY_VIDEO_IMPORT_SUCCESS -->+ <my-global-icon iconName="cloud-download"></my-global-icon>++ <div class="message" i18n>Your video import <strong class="limit-characters">{{ n.videoImportIdentifier }}</strong> succeeded</div>+ }++ @case (8) { <!-- UserNotificationType.MY_VIDEO_IMPORT_ERROR -->+ <my-global-icon iconName="cloud-error"></my-global-icon>++ <div class="message" i18n>Your video import <strong class="limit-characters">{{ n.videoImportIdentifier }}</strong> failed</div>+ }++ @case (9) { <!-- UserNotificationType.NEW_USER_REGISTRATION -->+ <my-global-icon iconName="user-add"></my-global-icon>++ <div class="message" i18n>User <strong>{{ n.payload.account.name }}</strong> registered on your platform</div>+ }++ @case (10) { <!-- UserNotificationType.NEW_FOLLOW -->+ <my-actor-avatar [size]="imageSize" [actor]="n.payload.actorFollow.follower" actorType="account"></my-actor-avatar>++ @if (n.payload.actorFollow.following.type === 'channel') {+ <div class="message" i18n>+ <strong>{{ n.payload.actorFollow.follower.displayName }}</strong> is following your channel <strong>{{ n.payload.actorFollow.following.displayName }}</strong>+ </div>+ } @else if (n.payload.actorFollow.following.type === 'account') {+ <div class="message" i18n>+ <strong>{{ n.payload.actorFollow.follower.displayName }}</strong> is following <strong>your account</strong></div>+ }+ }++ @case (11) {+ @if (n.payload.comment) {+ <my-actor-avatar [size]="imageSize" [actor]="n.payload.comment.account" actorType="account"></my-actor-avatar>++ <div class="message" i18n>+ <strong>{{ n.payload.comment.account.displayName }}</strong> mentioned you on video <strong>{{ n.payload.comment.video.name }}</strong>+ </div>+ } @else {+ <my-global-icon iconName="alert"></my-global-icon>++ <div class="message" i18n>The notification concerns a comment now unavailable</div>+ }+ }++ @case (13) { <!-- UserNotificationType.NEW_INSTANCE_FOLLOWER -->+ <my-global-icon iconName="users"></my-global-icon>++ <div class="message">+ <div i18n>Your platform has a new follower: <strong>{{ n.followerHandle }}</strong></div>++ @if (n.payload.actorFollow?.state === 'pending') {+ <div i18n>It is awaiting your approval</div>+ }+ </div>+ }++ @case (14) { <!-- UserNotificationType.AUTO_INSTANCE_FOLLOWING -->+ <my-global-icon iconName="users"></my-global-icon>++ <div class="message" i18n>Your platform automatically followed <strong>{{ n.followingHandle }}</strong></div>+ }++ @case (17) { <!-- UserNotificationType.NEW_PLUGIN_VERSION -->+ <my-global-icon iconName="cog"></my-global-icon>++ <div class="message" i18n>+ A new version of the plugin/theme <strong>{{ n.payload.plugin.name }}</strong> is available: <strong>{{ n.payload.plugin.latestVersion }}</strong>+ </div>+ }++ @case (18) { <!-- UserNotificationType.NEW_PEERTUBE_VERSION -->+ <my-global-icon iconName="cog"></my-global-icon>++ <div class="message" i18n>+ A <strong>new version</strong> of PeerTube is available: <strong>{{ n.payload.peertube.latestVersion }}</strong>+ </div>+ }++ @case (19) { <!-- UserNotificationType.MY_VIDEO_STUDIO_EDITION_FINISHED -->+ <my-global-icon iconName="film"></my-global-icon>++ <div class="message" i18n>The edits to your video <strong>{{ n.payload.video.name }}</strong> have been applied</div>+ }++ @case (20) { <!-- UserNotificationType.NEW_USER_REGISTRATION_REQUEST -->+ <my-global-icon iconName="user-add"></my-global-icon>++ <div class="message" i18n>User <strong>{{ n.payload.registration.username }}</strong> wants to register on your platform</div>+ }++ @case (21) { <!-- UserNotificationType.NEW_LIVE_FROM_SUBSCRIPTION -->+ @if (n.payload.video) {+ <my-actor-avatar [size]="imageSize" [actor]="n.payload.video.channel" actorType="channel"></my-actor-avatar>++ @if (isVideoPublished(n)) {+ <div class="message" i18n><strong>{{ n.payload.video.channel.displayName }}</strong> is live streaming: <strong>{{ n.payload.video.name }}</strong></div>+ } @else {+ <div class="message" i18n><strong>{{ n.payload.video.channel.displayName }}</strong> went live: <strong>{{ n.payload.video.name }}</strong></div>+ }+ } @else {+ <my-global-icon iconName="alert"></my-global-icon>++ <div class="message" i18n>The notification concerns a video now unavailable</div>+ }+ }++ @case (22) { <!-- UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED -->+ <my-global-icon iconName="video-lang"></my-global-icon>++ <div class="message" i18n>+ {{ n.payload.videoCaption.language.label }} transcription of your video <strong>{{ n.payload.videoCaption.video.name }}</strong> has been generated+ </div>+ }++ @case (23) { <!-- UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL -->+ <my-account-on-channel-avatar [size]="imageSize" [channel]="n.payload.videoChannelCollaborator.channel" [account]="n.payload.videoChannelCollaborator.channelOwner"></my-account-on-channel-avatar>++ <div class="message">+ <div i18n>+ <strong>{{ n.payload.videoChannelCollaborator.channelOwner.displayName }}</strong> invited you to become an editor of their channel <strong>{{ n.payload.videoChannelCollaborator.channel.displayName }}</strong>+ </div>++ @if (isChannelCollabRejected(n)) {+ <div class="d-flex gap-1 mt-2 align-items-center">+ <my-global-icon iconName="cross"></my-global-icon>++ <div i18n>Invitation declined</div>+ </div>+ } @else if (isChannelCollabInvitation(n)) {+ <div class="d-flex gap-1 mt-2">+ <my-button small="true" icon="tick" (click)="acceptChannelCollab()" i18n>Accept</my-button>+ <my-button small="true" icon="cross" (click)="rejectChannelCollab()" i18n>Decline</my-button>+ </div>+ } @else if (isChannelCollabAccepted(n)) {+ <div class="d-flex gap-1 mt-2 align-items-center">+ <my-global-icon iconName="tick"></my-global-icon>++ <div i18n>Invitation accepted</div>+ </div>+ }+ </div>+ }++ @case (24) { <!-- UserNotificationType.ACCEPTED_TO_COLLABORATE_TO_CHANNEL -->+ <my-account-on-channel-avatar [size]="imageSize" [channel]="n.payload.videoChannelCollaborator.channel" [account]="n.payload.videoChannelCollaborator.account"></my-account-on-channel-avatar>++ <div class="message" i18n>+ <strong>{{ n.payload.videoChannelCollaborator.account.displayName }}</strong> accepted your invitation to become an editor for your channel <strong>{{ n.payload.videoChannelCollaborator.channel.displayName }}</strong>+ </div>+ }++ @case (25) { <!-- UserNotificationType.REFUSED_TO_COLLABORATE_TO_CHANNEL -->+ <my-global-icon iconName="cross"></my-global-icon>++ <div class="message" i18n>+ <strong>{{ n.payload.videoChannelCollaborator.account.displayName }}</strong> declined your invitation to become an editor for your channel <strong>{{ n.payload.videoChannelCollaborator.channel.displayName }}</strong>+ </div>+ }++ @default {+ <my-global-icon iconName="alert"></my-global-icon>++ <div class="message" i18n>The notification points to content now unavailable</div>+ }+ }++ <div [title]="n.payload.createdAt" class="from-date">{{ n.payload.createdAt | myFromNow }}</div>+</div>diff --git a/client/src/app/shared/standalone-notifications/user-notification-content.component.scss b/client/src/app/shared/standalone-notifications/user-notification-content.component.scssnew file mode 100644index 0000000000..689a7aaf87--- /dev/null+++ b/client/src/app/shared/standalone-notifications/user-notification-content.component.scss@@ -0,0 +1,57 @@+@use "_variables" as *;+@use "_mixins" as *;++.root {+ display: flex;+ align-items: center;+ font-size: inherit;+ padding: 1rem 0.5rem;+ word-break: break-word;++ > my-actor-avatar,+ > my-account-on-channel-avatar {+ display: inline-block;++ @include margin-right(10px);+ }++ > my-global-icon {+ color: pvar(--secondary-icon-color);++ @include margin-right(11px);+ @include margin-left(3px);+ }+}++my-global-icon {+ color: pvar(--secondary-icon-color);+}++.message {+ flex-grow: 1;++ a {+ font-weight: $font-semibold;+ text-decoration: underline;+ }+}++.from-date {+ font-size: 0.85em;+ color: pvar(--fg-200);+ min-width: 70px;+ text-align: end;+ text-decoration: none;++ @include padding-left(5px);+ @include margin-left(auto);+}++.limit-characters {+ display: inline-block;+ max-width: 800px;+ vertical-align: bottom;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}diff --git a/client/src/app/shared/standalone-notifications/user-notification-content.component.ts b/client/src/app/shared/standalone-notifications/user-notification-content.component.tsnew file mode 100644index 0000000000..ac8a63cce9--- /dev/null+++ b/client/src/app/shared/standalone-notifications/user-notification-content.component.ts@@ -0,0 +1,98 @@+import { CommonModule } from '@angular/common'+import { Component, inject, input } from '@angular/core'+import { Router } from '@angular/router'+import { AuthService, Notifier } from '@app/core'+import { AbuseState, 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 { GlobalIconComponent } from '../shared-icons/global-icon.component'+import { ButtonComponent } from '../shared-main/buttons/button.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'++@Component({+ selector: 'my-user-notification-content',+ templateUrl: 'user-notification-content.component.html',+ styleUrls: [ 'user-notification-content.component.scss' ],+ imports: [+ CommonModule,+ GlobalIconComponent,+ ActorAvatarComponent,+ AccountOnChannelAvatarComponent,+ FromNowPipe,+ ButtonComponent+ ]+})+export class UserNotificationContentComponent {+ readonly router = inject(Router)+ readonly notifier = inject(Notifier)+ readonly channelService = inject(VideoChannelService)+ readonly authService = inject(AuthService)++ readonly notification = input.required<UserNotification>()++ imageSize = 30++ get n () {+ return this.notification()+ }++ isAbuseAccepted (notification: UserNotification) {+ return notification.payload.abuse.state === AbuseState.ACCEPTED+ }++ isVideoPublished (notification: UserNotification) {+ return notification.payload.video.state.id === VideoState.PUBLISHED+ }++ // ---------------------------------------------------------------------------++ isChannelCollabInvitation (notification: UserNotification) {+ if (!notification.payload.videoChannelCollaborator) return false++ return notification.payload.videoChannelCollaborator.state.id === VideoChannelCollaboratorState.PENDING+ }++ isChannelCollabAccepted (notification: UserNotification) {+ if (!notification.payload.videoChannelCollaborator) return false++ return notification.payload.videoChannelCollaborator.state.id === VideoChannelCollaboratorState.ACCEPTED+ }++ isChannelCollabRejected (notification: UserNotification) {+ if (!notification.payload.videoChannelCollaborator) return false++ return notification.payload.videoChannelCollaborator.state.id === VideoChannelCollaboratorState.REJECTED+ }++ acceptChannelCollab () {+ const collab = this.n.payload.videoChannelCollaborator++ this.channelService.acceptCollaboratorInvitation(collab.channel.name, collab.id)+ .subscribe({+ next: () => {+ this.authService.refreshUserInformation()++ this.n.payload.videoChannelCollaborator.state.id = VideoChannelCollaboratorState.ACCEPTED+ this.n.url = this.n.buildChannelEditorsUrl(collab.channel)+ this.router.navigate(this.n.url)+ },++ error: err => this.notifier.error(err.message)+ })+ }++ rejectChannelCollab () {+ const collab = this.n.payload.videoChannelCollaborator++ this.channelService.rejectCollaboratorInvitation(collab.channel.name, collab.id)+ .subscribe({+ next: () => {+ this.n.payload.videoChannelCollaborator.state.id = VideoChannelCollaboratorState.REJECTED+ },++ error: err => this.notifier.error(err.message)+ })+ }+}diff --git a/client/src/app/shared/standalone-notifications/user-notifications.component.html b/client/src/app/shared/standalone-notifications/user-notifications.component.htmlindex 91c19952a8..f60fd5621d 100644--- a/client/src/app/shared/standalone-notifications/user-notifications.component.html+++ b/client/src/app/shared/standalone-notifications/user-notifications.component.html@@ -1,271 +1,48 @@<div *ngIf="componentPagination.totalItems === 0" class="no-notification" i18n>You don't have notifications.</div>-<div class="notifications" myInfiniteScroller (nearOfBottom)="onNearOfBottom()" [dataObservable]="onDataSubject.asObservable()">- <!-- eslint-disable-next-line @angular-eslint/template/click-events-have-key-events,@angular-eslint/template/interactive-supports-focus -->- <div *ngFor="let notification of notifications" class="notification" [ngClass]="{ unread: !notification.read }" (click)="markAsRead(notification)">-- <ng-container [ngSwitch]="notification.type">- <ng-container *ngSwitchCase="1"> <!-- UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION -->- @if (notification.video) {- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">- <img alt="" aria-labelledby="avatar" class="avatar" [src]="notification.video.channel.avatarUrl" />- </a>-- <div class="message" i18n>- {{ notification.video.channel.displayName }} published a new video: <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.video.name }}</a>- </div>- } @else {- <my-global-icon iconName="alert" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- The notification concerns a video now unavailable- </div>- }- </ng-container>-- <ng-container *ngSwitchCase="5"> <!-- UserNotificationType.UNBLACKLIST_ON_MY_VIDEO -->- <my-global-icon iconName="undo" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- Your video <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.video.name }}</a> has been unblocked- </div>- </ng-container>-- <ng-container *ngSwitchCase="4"> <!-- UserNotificationType.BLACKLIST_ON_MY_VIDEO -->- <my-global-icon iconName="no" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- Your video <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.videoBlacklist.video.name }}</a> has been blocked- </div>- </ng-container>-- <ng-container *ngSwitchCase="3"> <!-- UserNotificationType.NEW_ABUSE_FOR_MODERATORS -->- <my-global-icon iconName="flag" aria-hidden="true"></my-global-icon>-- <div class="message" *ngIf="notification.videoUrl" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.abuseUrl" [queryParams]="notification.abuseQueryParams">A new video abuse</a> has been created on video <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.abuse.video.name }}</a>- </div>-- <div class="message" *ngIf="notification.commentUrl" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.abuseUrl" [queryParams]="notification.abuseQueryParams">A new comment abuse</a> has been created on video <a (click)="markAsRead(notification)" [routerLink]="notification.commentUrl">{{ notification.abuse.comment.video.name }}</a>- </div>-- <div class="message" *ngIf="notification.accountUrl" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.abuseUrl" [queryParams]="notification.abuseQueryParams">A new account abuse</a> has been created on account <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">{{ notification.abuse.account.displayName }}</a>- </div>-- <!-- Deleted entity associated to the abuse -->- <div class="message" *ngIf="!notification.videoUrl && !notification.commentUrl && !notification.accountUrl" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.abuseUrl" [queryParams]="notification.abuseQueryParams">A new abuse</a> has been created- </div>- </ng-container>-- <ng-container *ngSwitchCase="15"> <!-- UserNotificationType.ABUSE_STATE_CHANGE -->- <my-global-icon iconName="flag" aria-hidden="true"></my-global-icon>-- @if (isAbuseAccepted(notification)) {- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.abuseUrl" [queryParams]="notification.abuseQueryParams">Your abuse {{ notification.abuse.id }}</a> has been accepted- </div>- } @else {- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.abuseUrl" [queryParams]="notification.abuseQueryParams">Your abuse {{ notification.abuse.id }}</a> has been accepted- </div>- }- </ng-container>-- <ng-container *ngSwitchCase="16"> <!-- UserNotificationType.ABUSE_NEW_MESSAGE -->- <my-global-icon iconName="flag" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.abuseUrl" [queryParams]="notification.abuseQueryParams">Abuse {{ notification.abuse.id }}</a> has a new message- </div>- </ng-container>-- <ng-container *ngSwitchCase="12"> <!-- UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS -->- <my-global-icon iconName="no" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- The recently added video <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.videoBlacklist.video.name }}</a> has been <a (click)="markAsRead(notification)" [routerLink]="notification.videoAutoBlacklistUrl">automatically blocked</a>- </div>- </ng-container>-- <ng-container *ngSwitchCase="2">- <ng-container *ngIf="notification.comment">- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">- <img alt="" aria-labelledby="avatar" class="avatar" [src]="notification.comment.account.avatarUrl" />- </a>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">{{ notification.comment.account.displayName }}</a> commented your video <a (click)="markAsRead(notification)" [routerLink]="notification.commentUrl">{{ notification.comment.video.name }}</a>- <ng-container *ngIf="notification.comment.heldForReview">. This comment requires <a (click)="markAsRead(notification)" [routerLink]="notification.commentReviewUrl" [queryParams]="notification.commentReviewQueryParams">your approval</a></ng-container>- </div>- </ng-container>-- <ng-container *ngIf="!notification.comment">- <my-global-icon iconName="alert" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- The notification concerns a comment now unavailable- </div>- </ng-container>- </ng-container>-- <ng-container *ngSwitchCase="6"> <!-- UserNotificationType.MY_VIDEO_PUBLISHED -->- <my-global-icon iconName="film" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- Your video <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.video.name }}</a> has been published- </div>- </ng-container>-- <ng-container *ngSwitchCase="7"> <!-- UserNotificationType.MY_VIDEO_IMPORT_SUCCESS -->- <my-global-icon iconName="cloud-download" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl || notification.videoImportUrl">Your video import</a> <strong>{{ notification.videoImportIdentifier }}</strong> succeeded- </div>- </ng-container>-- <ng-container *ngSwitchCase="8"> <!-- UserNotificationType.MY_VIDEO_IMPORT_ERROR -->- <my-global-icon iconName="cloud-error" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.videoImportUrl">Your video import</a> {{ notification.videoImportIdentifier }} failed- </div>- </ng-container>-- <ng-container *ngSwitchCase="9"> <!-- UserNotificationType.NEW_USER_REGISTRATION -->- <my-global-icon iconName="user-add" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- User <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">{{ notification.account.name }}</a> registered on your instance- </div>- </ng-container>-- <ng-container *ngSwitchCase="10"> <!-- UserNotificationType.NEW_FOLLOW -->- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">- <img alt="" aria-labelledby="avatar" class="avatar" [src]="notification.actorFollow.follower.avatarUrl" />+<ul class="notifications" myInfiniteScroller (nearOfBottom)="onNearOfBottom()" [dataObservable]="onDataSubject.asObservable()">+ @for (notification of notifications; track notification.payload.id) {+ <li>+ @if (notification.externalUrl) {+ <a+ class="notification"+ [ngClass]="{ unread: !notification.payload.read }"+ (click)="markAsRead(notification)"+ i18n-title+ title="New message"+ [href]="notification.externalUrl"+ target="_blank"+ rel="noopener nofollow"+ >+ <my-user-notification-content [notification]="notification"></my-user-notification-content></a>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">{{ notification.actorFollow.follower.displayName }}</a> is following-- <ng-container *ngIf="notification.actorFollow.following.type === 'channel'">your channel {{ notification.actorFollow.following.displayName }}</ng-container>- <ng-container *ngIf="notification.actorFollow.following.type === 'account'">your account</ng-container>- </div>- </ng-container>-- <ng-container *ngSwitchCase="11">- <ng-container *ngIf="notification.comment">- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">- <img alt="" aria-labelledby="avatar" class="avatar" [src]="notification.comment.account.avatarUrl" />- </a>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">{{ notification.comment.account.displayName }}</a> mentioned you on <a (click)="markAsRead(notification)" [routerLink]="notification.commentUrl">video {{ notification.comment.video.name }}</a>- </div>- </ng-container>-- <ng-container *ngIf="!notification.comment">- <my-global-icon iconName="alert" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- The notification concerns a comment now unavailable- </div>- </ng-container>- </ng-container>-- <ng-container *ngSwitchCase="13"> <!-- UserNotificationType.NEW_INSTANCE_FOLLOWER -->- <my-global-icon iconName="users" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- Your instance has <a (click)="markAsRead(notification)" [routerLink]="notification.instanceFollowUrl">a new follower</a> ({{ notification.actorFollow?.follower.host }})- <ng-container *ngIf="notification.actorFollow?.state === 'pending'"> awaiting your approval</ng-container>- </div>- </ng-container>-- <ng-container *ngSwitchCase="14"> <!-- UserNotificationType.AUTO_INSTANCE_FOLLOWING -->- <my-global-icon iconName="users" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- Your instance automatically followed <a (click)="markAsRead(notification)" [routerLink]="notification.instanceFollowUrl">{{ notification.actorFollow.following.host }}</a>- </div>- </ng-container>-- <ng-container *ngSwitchCase="17"> <!-- UserNotificationType.NEW_PLUGIN_VERSION -->- <my-global-icon iconName="cog" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [routerLink]="notification.pluginUrl" [queryParams]="notification.pluginQueryParams">A new version of the plugin/theme {{ notification.plugin.name }}</a> is available: {{ notification.plugin.latestVersion }}- </div>- </ng-container>-- <ng-container *ngSwitchCase="18"> <!-- UserNotificationType.NEW_PEERTUBE_VERSION -->- <my-global-icon iconName="cog" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- <a (click)="markAsRead(notification)" [href]="notification.peertubeVersionLink" target="_blank" rel="noopener noreferrer">A new version of PeerTube</a> is available: {{ notification.peertube.latestVersion }}- </div>- </ng-container>-- <ng-container *ngSwitchCase="19"> <!-- UserNotificationType.MY_VIDEO_STUDIO_EDITION_FINISHED -->- <my-global-icon iconName="film" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- The edits to your video <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.video.name }}</a> have been applied- </div>- </ng-container>-- <ng-container *ngSwitchCase="20"> <!-- UserNotificationType.NEW_USER_REGISTRATION_REQUEST -->- <my-global-icon iconName="user-add" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- User <a (click)="markAsRead(notification)" [routerLink]="notification.registrationsUrl">{{ notification.registration.username }}</a> wants to register on your instance- </div>- </ng-container>-- <ng-container *ngSwitchCase="21"> <!-- UserNotificationType.NEW_LIVE_FROM_SUBSCRIPTION -->- @if (notification.video) {- <a (click)="markAsRead(notification)" [routerLink]="notification.accountUrl">- <img alt="" aria-labelledby="avatar" class="avatar" [src]="notification.video.channel.avatarUrl" />- </a>-- @if (isVideoPublished(notification)) {- <div class="message" i18n>- {{ notification.video.channel.displayName }} is live streaming: <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.video.name }}</a>- </div>- } @else {- <div class="message" i18n>- {{ notification.video.channel.displayName }} went live: <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">{{ notification.video.name }}</a>- </div>- }- } @else {- <my-global-icon iconName="alert" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- The notification concerns a video now unavailable- </div>- }- </ng-container>-- <ng-container *ngSwitchCase="22"> <!-- UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED -->- <my-global-icon iconName="video-lang" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- <em>{{ notification.videoCaption.language.label }}</em> transcription of <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">your video {{ notification.videoCaption.video.name }}</a> has been generated- </div>- </ng-container>-- <ng-container *ngSwitchDefault>- <my-global-icon iconName="alert" aria-hidden="true"></my-global-icon>-- <div class="message" i18n>- The notification points to content now unavailable- </div>- </ng-container>- </ng-container>-- <div [title]="notification.createdAt" class="from-date">{{ notification.createdAt | myFromNow }}</div>- </div>-</div>+ } @else if (notification.url) {+ <a+ class="notification"+ [ngClass]="{ unread: !notification.payload.read }"+ (click)="markAsRead(notification)"+ i18n-title+ title="New message"+ [routerLink]="notification.url"+ [queryParams]="notification.queryParams"+ >+ <my-user-notification-content [notification]="notification"></my-user-notification-content>+ </a>+ } @else if (notification.payload.read === false) {+ <button+ class="notification button-unstyle"+ [ngClass]="{ unread: !notification.payload.read }"+ (click)="markAsRead(notification)"+ i18n-title+ title="Mark as read"+ >+ <my-user-notification-content [notification]="notification"></my-user-notification-content>+ </button>+ }@else {+ <div class="notification">+ <my-user-notification-content [notification]="notification"></my-user-notification-content>+ </div>+ }+ </li>+ }+</ul>diff --git a/client/src/app/shared/standalone-notifications/user-notifications.component.scss b/client/src/app/shared/standalone-notifications/user-notifications.component.scssindex ec8af17539..bc34f6f45a 100644--- a/client/src/app/shared/standalone-notifications/user-notifications.component.scss+++ b/client/src/app/shared/standalone-notifications/user-notifications.component.scss@@ -1,5 +1,14 @@-@use '_variables' as *;-@use '_mixins' as *;+@use "_variables" as *;+@use "_mixins" as *;++ul {+ margin: 0;+ padding: 0;+}++li {+ list-style: none;+}.no-notification {display: flex;@@ -9,55 +18,24 @@}.notification {- display: flex;- align-items: center;- font-size: inherit;- padding: 15px 5px 15px 10px;+ display: block;border-bottom: 1px solid $separator-border-color-on-secondary;- word-break: break-word;+ text-decoration: none;&.unread {background-color: pvar(--bg-secondary-400);- cursor: pointer;++ &:hover {+ opacity: 1;+ }}&:hover {background-color: pvar(--bg-secondary-350);}- my-global-icon {- color: pvar(--secondary-icon-color);-- @include margin-right(11px);- @include margin-left(3px);- }-- .avatar {- width: 30px;- height: 30px;- min-width: 30px;- min-height: 30px;- border-radius: 5px;-- @include margin-right(10px);- }-- .message {- flex-grow: 1;-- a {- font-weight: $font-semibold;- text-decoration: underline;- }- }-- .from-date {- font-size: 0.85em;- color: pvar(--fg-300);- min-width: 70px;- text-align: end;-- @include padding-left(5px);- @include margin-left(auto);+ &.button-unstyle {+ width: 100%;+ text-align: left;}}diff --git a/client/src/app/shared/standalone-notifications/user-notifications.component.ts b/client/src/app/shared/standalone-notifications/user-notifications.component.tsindex ede991ad9c..c5fc0fccd2 100644--- a/client/src/app/shared/standalone-notifications/user-notifications.component.ts+++ b/client/src/app/shared/standalone-notifications/user-notifications.component.ts@@ -1,20 +1,23 @@-import { Subject } from 'rxjs'-import { Component, OnInit, inject, input, output } from '@angular/core'-import { ComponentPagination, hasMoreItems, Notifier } from '@app/core'-import { AbuseState, VideoState } from '@peertube/peertube-models'import { CommonModule } from '@angular/common'-import { GlobalIconComponent } from '../shared-icons/global-icon.component'+import { Component, inject, input, OnInit, output } from '@angular/core'import { RouterLink } from '@angular/router'-import { FromNowPipe } from '../shared-main/date/from-now.pipe'+import { ComponentPagination, hasMoreItems, Notifier } from '@app/core'+import { Subject } from 'rxjs'import { InfiniteScrollerDirective } from '../shared-main/common/infinite-scroller.directive'-import { UserNotificationService } from '../shared-main/users/user-notification.service'import { UserNotification } from '../shared-main/users/user-notification.model'+import { UserNotificationService } from '../shared-main/users/user-notification.service'+import { UserNotificationContentComponent } from './user-notification-content.component'@Component({selector: 'my-user-notifications',templateUrl: 'user-notifications.component.html',styleUrls: [ 'user-notifications.component.scss' ],- imports: [ CommonModule, GlobalIconComponent, RouterLink, FromNowPipe, InfiniteScrollerDirective ]+ imports: [+ CommonModule,+ RouterLink,+ InfiniteScrollerDirective,+ UserNotificationContentComponent+ ]})export class UserNotificationsComponent implements OnInit {private userNotificationService = inject(UserNotificationService)@@ -94,12 +97,12 @@ export class UserNotificationsComponent implements OnInit {}markAsRead (notification: UserNotification) {- if (notification.read) return+ if (notification.payload.read) returnthis.userNotificationService.markAsRead(notification).subscribe({next: () => {- notification.read = true+ notification.payload.read = true},error: err => this.notifier.error(err.message)@@ -111,7 +114,7 @@ export class UserNotificationsComponent implements OnInit {.subscribe({next: () => {for (const notification of this.notifications) {- notification.read = true+ notification.payload.read = true}},@@ -128,12 +131,4 @@ export class UserNotificationsComponent implements OnInit {this.sortField = columnthis.loadNotifications(true)}-- isAbuseAccepted (notification: UserNotification) {- return notification.abuse.state === AbuseState.ACCEPTED- }-- isVideoPublished (notification: UserNotification) {- return notification.video.state.id === VideoState.PUBLISHED- }}diff --git a/client/src/assets/images/misc/video-lang.svg b/client/src/assets/images/misc/video-lang.svgindex f950ff353a..1fee8eab5c 100644--- a/client/src/assets/images/misc/video-lang.svg+++ b/client/src/assets/images/misc/video-lang.svg@@ -1,48 +1,6 @@-<?xml version="1.0" encoding="UTF-8" standalone="no"?>-<svg- transform="scale(1.1)"- viewBox="0 0 24 24"- version="1.1"- id="svg2"- sodipodi:docname="video-lang.svg"- inkscape:version="1.3.2 (091e20ef0f, 2023-11-25, custom)"- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"- xmlns="http://www.w3.org/2000/svg"- xmlns:svg="http://www.w3.org/2000/svg">- <sodipodi:namedview- id="namedview2"- pagecolor="#ffffff"- bordercolor="#666666"- borderopacity="1.0"- inkscape:showpageshadow="2"- inkscape:pageopacity="0.0"- inkscape:pagecheckerboard="0"- inkscape:deskcolor="#d1d1d1"- inkscape:zoom="30.708333"- inkscape:cx="12"- inkscape:cy="12.016282"- inkscape:window-width="1916"- inkscape:window-height="1036"- inkscape:window-x="0"- inkscape:window-y="0"- inkscape:window-maximized="0"- inkscape:current-layer="svg2" />- <defs- id="defs1" />- <g- class="layer"- id="g2"- transform="translate(1.1816062,0.78854308)">- <path- fill="transparent"- fill-rule="evenodd"- stroke="currentColor"- stroke-width="1.8"- d="m 20.5,6.7 c 0,0 -0.2,-1.4 -0.8,-2 C 19,3.9 18.1,3.9 17.7,3.8 15,3.6 10.8,3.6 10.8,3.6 v 0 c 0,0 -4.2,0 -7,0.2 -0.3,0 -1.2,0 -2,0.9 -0.5,0.6 -0.7,2 -0.7,2 L 0.9,10 v 1.6 l 0.2,3.3 c 0,0 0.2,1.4 0.8,2 0.7,0.8 1.7,0.8 2.2,0.9 1.6,0.2 6.7,0.2 6.7,0.2 0,0 4.2,0 7,-0.2 0.3,0 1.2,0 2,-0.9 0.5,-0.6 0.7,-2 0.7,-2 l 0.2,-3.3 V 10 Z"- id="path1" />- <path- d="M 8.7,14.7 A 0.7,0.7 0 0 1 8.2,13.5 l 2.9,-3 H 8.7 a 0.7,0.7 0 0 1 0,-1.3 h 4 a 0.7,0.7 0 0 1 0.5,1.2 l -4,4 a 0.7,0.7 0 0 1 -0.5,0.3 z m 3,-6.1 h -2 a 0.7,0.7 0 1 1 0,-1.4 h 2 a 0.7,0.7 0 0 1 0,1.4 z"- id="path2" />- </g>+<svg xmlns="http://www.w3.org/2000/svg" transform="scale(1.1)" viewBox="0 0 24 24">+ <g class="layer">+ <path fill="transparent" fill-rule="evenodd" stroke="currentColor" stroke-width="1.8" d="M21.682 7.489s-.2-1.4-.8-2c-.7-.8-1.6-.8-2-.9-2.7-.2-6.9-.2-6.9-.2s-4.2 0-7 .2c-.3 0-1.2 0-2 .9-.5.6-.7 2-.7 2l-.2 3.3v1.6l.2 3.3s.2 1.4.8 2c.7.8 1.7.8 2.2.9 1.6.2 6.7.2 6.7.2s4.2 0 7-.2c.3 0 1.2 0 2-.9.5-.6.7-2 .7-2l.2-3.3v-1.6Z"/>+ <path stroke="currentColor" d="M9.882 15.489a.7.7 0 0 1-.5-1.2l2.9-3h-2.4a.7.7 0 0 1 0-1.3h4a.7.7 0 0 1 .5 1.2l-4 4a.7.7 0 0 1-.5.3m3-6.1h-2a.7.7 0 1 1 0-1.4h2a.7.7 0 0 1 0 1.4"/>+ </g></svg>diff --git a/client/src/sass/class-helpers/_buttons.scss b/client/src/sass/class-helpers/_buttons.scssindex 5ab50580c1..083885fa8c 100644--- a/client/src/sass/class-helpers/_buttons.scss+++ b/client/src/sass/class-helpers/_buttons.scss@@ -1,6 +1,6 @@-@use '_variables' as *;-@use '_mixins' as *;-@use '_button-mixins' as *;+@use "_variables" as *;+@use "_mixins" as *;+@use "_button-mixins" as *;.peertube-button {@include peertube-button;@@ -57,6 +57,7 @@}.button-unstyle {+ font-weight: inherit;padding: 0;border: 0;}diff --git a/client/src/sass/class-helpers/_layout.scss b/client/src/sass/class-helpers/_layout.scssindex 6e83576805..0ad48bd514 100644--- a/client/src/sass/class-helpers/_layout.scss+++ b/client/src/sass/class-helpers/_layout.scss@@ -17,7 +17,8 @@@include make-col(3);}- h2 {+ h2,+ h3 {font-size: 1rem;margin-bottom: 10px;@@ -52,6 +53,12 @@max-width: 300px;}+.w-fit-content {+ width: fit-content;+}++// ---------------------------------------------------------------------------+.d-none-mw {@include on-mobile-main-col {display: none !important;diff --git a/client/src/sass/class-helpers/_table.scss b/client/src/sass/class-helpers/_table.scssnew file mode 100644index 0000000000..82bbfa3be2--- /dev/null+++ b/client/src/sass/class-helpers/_table.scss@@ -0,0 +1,18 @@+@use "_variables" as *;+@use "_mixins" as *;++.channel-sub-link-in-cell {+ color: pvar(--fg-200);+ text-decoration: none;+ display: inline-flex;+ align-items: center;+ line-height: 1;+ margin-top: 0.25rem;++ @include font-size(14px);++ &:hover {+ opacity: 1;+ color: pvar(--fg-300);+ }+}diff --git a/client/src/sass/class-helpers/_titles.scss b/client/src/sass/class-helpers/_titles.scssnew file mode 100644index 0000000000..862001e224--- /dev/null+++ b/client/src/sass/class-helpers/_titles.scss@@ -0,0 +1,16 @@+@use "_variables" as *;+@use "_mixins" as *;++.form-title {+ font-weight: $font-bold;+ color: pvar(--fg-350);+ line-height: 1;++ @include font-size(2rem);+ @include rfs(2rem, margin-bottom);++ my-global-icon {+ @include global-icon-size(28px);+ @include margin-right(0.5rem);+ }+}diff --git a/client/src/sass/class-helpers/index.scss b/client/src/sass/class-helpers/index.scssindex 2cd6f6e7ee..142ae9c923 100644--- a/client/src/sass/class-helpers/index.scss+++ b/client/src/sass/class-helpers/index.scss@@ -1,11 +1,13 @@-@use './_buttons';-@use './_badges';-@use './_common';-@use './_custom-bootstrap-helpers';-@use './_forms';-@use './images';-@use './_menu';-@use './_text';-@use './_layout';-@use './_position';-@use './_transform';+@use "./_buttons";+@use "./_badges";+@use "./_common";+@use "./_custom-bootstrap-helpers";+@use "./_forms";+@use "./images";+@use "./_menu";+@use "./_text";+@use "./_titles";+@use "./_layout";+@use "./_position";+@use "./_table";+@use "./_transform";diff --git a/client/src/sass/include/_button-mixins.scss b/client/src/sass/include/_button-mixins.scssindex 1e93dcfc1b..f21b52f994 100644--- a/client/src/sass/include/_button-mixins.scss+++ b/client/src/sass/include/_button-mixins.scss@@ -40,7 +40,7 @@&[disabled] {pointer-events: none;- opacity: 0.8;+ opacity: 0.6;}&:not(.icon-only) my-global-icon {@@ -128,22 +128,6 @@}}-@mixin rounded-icon-button {- padding: 0.5rem !important;- border-radius: 100% !important;-- &.small-button {- padding: 6px !important;- line-height: 0 !important;-- my-global-icon {- line-height: 0;-- @include global-icon-size(12px);- }- }-}-@mixin danger-button {background-color: pvar(--input-danger-bg);color: pvar(--input-danger-fg);@@ -184,9 +168,29 @@padding: pvar(--input-y-padding) 8px;}- &:is(input[type="button"]) {- // Because of primeng that redefines border-radius of all input[type="..."]- border-radius: pvar(--input-border-radius) !important;+ &.small-button {+ font-size: $button-font-size * 0.9;+ padding: calc(#{pvar(--input-y-padding)} / 2) calc(#{pvar(--input-x-padding)} / 2) !important;++ my-global-icon {+ @include global-icon-size(18px !important);+ }+ }+}++@mixin rounded-icon-button {+ padding: 0.5rem !important;+ border-radius: 100% !important;++ &.small-button {+ padding: calc(#{pvar(--input-x-padding)} / 4) !important;+ line-height: 0 !important;++ my-global-icon {+ line-height: 0;++ @include global-icon-size(12px !important);+ }}}diff --git a/client/src/sass/include/_mixins.scss b/client/src/sass/include/_mixins.scssindex 6e64d61f8f..932450813c 100644--- a/client/src/sass/include/_mixins.scss+++ b/client/src/sass/include/_mixins.scss@@ -154,8 +154,8 @@@mixin row-blocks($column-responsive: true, $min-height: 130px, $separator: true) {display: flex;min-height: $min-height;- padding-bottom: 20px;- margin-bottom: 20px;+ padding-bottom: 1.25rem;+ margin-bottom: 1.25rem;@if $separator {border-bottom: 1px solid pvar(--input-border-color);@@ -168,14 +168,14 @@align-items: center;} @else {min-height: initial;- padding-bottom: 10px;- margin-bottom: 10px;+ padding-bottom: 0.5rem;+ margin-bottom: 0.5rem;}}}@mixin dropdown-with-icon-item {- padding: pvar(--input-y-padding) 15px;+ padding: pvar(--input-y-padding) 1rem;my-global-icon {width: 22px;@@ -183,7 +183,11 @@position: relative;top: -2px;- @include margin-right(10px);+ @include margin-right($dropdown-icon-margin-right);+ }++ my-actor-avatar {+ @include margin-right($dropdown-icon-margin-right);}}diff --git a/client/src/sass/include/_variables.scss b/client/src/sass/include/_variables.scssindex 497101b0b7..fb34a3230f 100644--- a/client/src/sass/include/_variables.scss+++ b/client/src/sass/include/_variables.scss@@ -81,6 +81,10 @@ $form-input-font-size: 16px;$video-watch-info-margin-left: 44px;+// ---------------------------------------------------------------------------++$dropdown-icon-margin-right: 0.5rem;+// ---------------------------------------------------------------------------// Theme variables with key check using pvar() function// ---------------------------------------------------------------------------diff --git a/client/src/standalone/videos/embed.ts b/client/src/standalone/videos/embed.tsindex 70106698bd..f55d4a3442 100644--- a/client/src/standalone/videos/embed.ts+++ b/client/src/standalone/videos/embed.ts@@ -69,7 +69,7 @@ export class PeerTubeEmbed {this.peertubePlugin = new PeerTubePlugin(this.http)this.peertubeTheme = new PeerTubeTheme(this.peertubePlugin)this.playerHTML = new PlayerHTML(videoWrapperId)- this.playerOptionsBuilder = new PlayerOptionsBuilder(this.playerHTML, this.videoFetcher, this.peertubePlugin, this.config)+ this.playerOptionsBuilder = new PlayerOptionsBuilder(this.playerHTML, this.videoFetcher, this.peertubePlugin)this.liveManager = new LiveManager(this.playerHTML)this.requiresPassword = falsediff --git a/client/src/standalone/videos/shared/player-options-builder.ts b/client/src/standalone/videos/shared/player-options-builder.tsindex d11cd83eea..3c951164cd 100644--- a/client/src/standalone/videos/shared/player-options-builder.ts+++ b/client/src/standalone/videos/shared/player-options-builder.ts@@ -65,8 +65,7 @@ export class PlayerOptionsBuilder {constructor (private readonly playerHTML: PlayerHTML,private readonly videoFetcher: VideoFetcher,- private readonly peertubePlugin: PeerTubePlugin,- private readonly serverConfig: HTMLServerConfig+ private readonly peertubePlugin: PeerTubePlugin) {}hasAPIEnabled () {diff --git a/client/src/types/select-options-item.model.ts b/client/src/types/select-options-item.model.tsindex aa0767c7ee..4f724ecfce 100644--- a/client/src/types/select-options-item.model.ts+++ b/client/src/types/select-options-item.model.ts@@ -12,4 +12,6 @@ export interface SelectChannelItem extends SelectOptionsItem {name: stringavatarPath: stringsupport: string++ editor: boolean}diff --git a/config/default.yaml b/config/default.yamlindex f3acfac161..2e0611ca05 100644--- a/config/default.yaml+++ b/config/default.yaml@@ -576,7 +576,9 @@ user:min_length: 8video_channels:- max_per_user: 20 # Allows each user to create up to 20 video channels.+ max_per_user: 20 # Allows each user to create up to 20 video channels++ max_collaborators_per_channel: 20# If enabled, the video will be transcoded to mp4 (x264) with `faststart` flag# In addition, if some resolutions are enabled the mp4 video file will be transcoded to these new resolutionsdiff --git a/config/production.yaml.example b/config/production.yaml.exampleindex 03a7abcf66..bf4f08ec49 100644--- a/config/production.yaml.example+++ b/config/production.yaml.example@@ -586,7 +586,9 @@ user:min_length: 8video_channels:- max_per_user: 20 # Allows each user to create up to 20 video channels.+ max_per_user: 20 # Allows each user to create up to 20 video channels++ max_collaborators_per_channel: 20# If enabled, the video will be transcoded to mp4 (x264) with `faststart` flag# In addition, if some resolutions are enabled the mp4 video file will be transcoded to these new resolutionsdiff --git a/eslint.config.mjs b/eslint.config.mjsindex ed4d3a2004..9e6e8cc440 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -85,7 +85,11 @@ export default defineConfig(['@typescript-eslint/no-unnecessary-boolean-literal-compare': 'off','@typescript-eslint/strict-boolean-expressions': 'off','@typescript-eslint/consistent-type-definitions': 'off',- '@typescript-eslint/no-misused-promises': 'off',+ '@typescript-eslint/no-misused-promises': [ 'error', {+ checksConditionals: true,+ checksSpreads: true,+ checksVoidReturn: false+ } ],'@typescript-eslint/no-namespace': 'off','@typescript-eslint/no-empty-interface': 'off','@typescript-eslint/no-extraneous-class': 'off',diff --git a/packages/models/src/bulk/bulk-remove-comments-of-body.model.ts b/packages/models/src/bulk/bulk-remove-comments-of-body.model.tsindex 31e018c2a3..fe26680238 100644--- a/packages/models/src/bulk/bulk-remove-comments-of-body.model.ts+++ b/packages/models/src/bulk/bulk-remove-comments-of-body.model.ts@@ -1,4 +1,4 @@export interface BulkRemoveCommentsOfBody {accountName: string- scope: 'my-videos' | 'instance'+ scope: 'my-videos' | 'my-videos-and-collaborations' | 'instance'}diff --git a/packages/models/src/users/index.ts b/packages/models/src/users/index.tsindex 5c7be1121c..601e475f5c 100644--- a/packages/models/src/users/index.ts+++ b/packages/models/src/users/index.ts@@ -4,6 +4,7 @@ export * from './user-create-result.model.js'export * from './user-create.model.js'export * from './user-flag.model.js'export * from './user-login.model.js'+export * from './user-notification-data.model.js'export * from './user-notification-list-query.model.js'export * from './user-notification-setting.model.js'export * from './user-notification.model.js'diff --git a/packages/models/src/users/user-notification-data.model.ts b/packages/models/src/users/user-notification-data.model.tsnew file mode 100644index 0000000000..e458daa661--- /dev/null+++ b/packages/models/src/users/user-notification-data.model.ts@@ -0,0 +1 @@+export type UserNotificationData = {}diff --git a/packages/models/src/users/user-notification.model.ts b/packages/models/src/users/user-notification.model.tsindex cc46232556..4dae92534d 100644--- a/packages/models/src/users/user-notification.model.ts+++ b/packages/models/src/users/user-notification.model.ts@@ -1,8 +1,10 @@import { FollowState } from '../actors/index.js'import { AbuseStateType } from '../moderation/index.js'import { PluginType_Type } from '../plugins/index.js'+import { VideoChannelCollaboratorStateType } from '../videos/index.js'import { VideoConstant } from '../videos/video-constant.model.js'import { VideoStateType } from '../videos/video-state.enum.js'+import { UserNotificationData } from './user-notification-data.model.js'export const UserNotificationType = {NEW_VIDEO_FROM_SUBSCRIPTION: 1,@@ -40,7 +42,11 @@ export const UserNotificationType = {NEW_LIVE_FROM_SUBSCRIPTION: 21,- MY_VIDEO_TRANSCRIPTION_GENERATED: 22+ MY_VIDEO_TRANSCRIPTION_GENERATED: 22,++ INVITED_TO_COLLABORATE_TO_CHANNEL: 23,+ ACCEPTED_TO_COLLABORATE_TO_CHANNEL: 24,+ REFUSED_TO_COLLABORATE_TO_CHANNEL: 25} as constexport type UserNotificationType_Type = typeof UserNotificationType[keyof typeof UserNotificationType]@@ -79,6 +85,7 @@ export interface UserNotification {id: numbertype: UserNotificationType_Typeread: boolean+ data: UserNotificationDatavideo?: VideoInfo & {channel: ActorInfo@@ -156,6 +163,16 @@ export interface UserNotification {video: VideoInfo}+ videoChannelCollaborator?: {+ id: number++ state: VideoConstant<VideoChannelCollaboratorStateType>++ channel: ActorInfo+ channelOwner: ActorInfo+ account: ActorInfo+ }+createdAt: stringupdatedAt: string}diff --git a/packages/models/src/users/user.model.ts b/packages/models/src/users/user.model.tsindex c9e8658561..c3978e9c78 100644--- a/packages/models/src/users/user.model.ts+++ b/packages/models/src/users/user.model.ts@@ -6,6 +6,9 @@ import { UserAdminFlagType } from './user-flag.model.js'import { UserNotificationSetting } from './user-notification-setting.model.js'import { UserRoleType } from './user-role.js'+type UserVideoChannel = Omit<VideoChannel, 'ownerAccount'> & {+ ownerAccountId: number+}export interface User {id: numberusername: string@@ -57,7 +60,8 @@ export interface User {account: AccountnotificationSettings?: UserNotificationSetting- videoChannels?: VideoChannel[]++ videoChannels?: UserVideoChannel[]blocked: booleanblockedReason?: string@@ -83,4 +87,5 @@ export interface MyUserSpecialPlaylist {export interface MyUser extends User {specialPlaylists: MyUserSpecialPlaylist[]+ videoChannelCollaborations?: UserVideoChannel[]}diff --git a/packages/models/src/videos/channel/index.ts b/packages/models/src/videos/channel/index.tsindex 3c96e80f00..7d7e2cb252 100644--- a/packages/models/src/videos/channel/index.ts+++ b/packages/models/src/videos/channel/index.ts@@ -1,3 +1,4 @@+export * from './video-channel-collaborator.model.js'export * from './video-channel-create-result.model.js'export * from './video-channel-create.model.js'export * from './video-channel-update.model.js'diff --git a/packages/models/src/videos/channel/video-channel-collaborator.model.ts b/packages/models/src/videos/channel/video-channel-collaborator.model.tsnew file mode 100644index 0000000000..0a2bea23a4--- /dev/null+++ b/packages/models/src/videos/channel/video-channel-collaborator.model.ts@@ -0,0 +1,22 @@+import { AccountSummary } from '../../actors/index.js'++export const VideoChannelCollaboratorState = {+ PENDING: 1,+ ACCEPTED: 2,+ REJECTED: 3+} as const++export type VideoChannelCollaboratorStateType = typeof VideoChannelCollaboratorState[keyof typeof VideoChannelCollaboratorState]++export interface VideoChannelCollaborator {+ id: number+ account: AccountSummary++ state: {+ id: VideoChannelCollaboratorStateType+ label: string+ }++ createdAt: string+ updatedAt: string+}diff --git a/packages/models/src/videos/channel/video-channel.model.ts b/packages/models/src/videos/channel/video-channel.model.tsindex bb10f6da58..4e89c0152c 100644--- a/packages/models/src/videos/channel/video-channel.model.ts+++ b/packages/models/src/videos/channel/video-channel.model.ts@@ -32,3 +32,7 @@ export interface VideoChannelSummary {avatars: ActorImage[]}++export function isVideoChannel (obj: Account | VideoChannel): obj is VideoChannel {+ return obj && typeof obj === 'object' && 'support' in obj+}diff --git a/packages/models/src/videos/comment/video-comment.model.ts b/packages/models/src/videos/comment/video-comment.model.tsindex c818cb736b..f944119112 100644--- a/packages/models/src/videos/comment/video-comment.model.ts+++ b/packages/models/src/videos/comment/video-comment.model.ts@@ -1,5 +1,6 @@import { ResultList } from '../../common/index.js'import { Account } from '../../actors/index.js'+import { VideoChannelSummary } from '../channel/video-channel.model.js'export interface VideoComment {id: number@@ -40,6 +41,8 @@ export interface VideoCommentForAdminOrUser {id: numberuuid: stringname: string++ channel: VideoChannelSummary}heldForReview: booleandiff --git a/packages/models/src/videos/playlist/video-playlists-list-query.model.ts b/packages/models/src/videos/playlist/video-playlists-list-query.model.tsindex ad505484e3..aa400d1070 100644--- a/packages/models/src/videos/playlist/video-playlists-list-query.model.ts+++ b/packages/models/src/videos/playlist/video-playlists-list-query.model.ts@@ -7,3 +7,8 @@ export interface VideoPlaylistsListQuery {search?: stringplaylistType?: VideoPlaylistType_Type}++export interface VideoPlaylistForAccountListQuery extends VideoPlaylistsListQuery {+ includeCollaborations?: boolean+ channelNameOneOf?: string[]+}diff --git a/packages/server-commands/src/server/server.ts b/packages/server-commands/src/server/server.tsindex c3dec34909..06d4c46f1e 100644--- a/packages/server-commands/src/server/server.ts+++ b/packages/server-commands/src/server/server.ts@@ -1,5 +1,5 @@import { randomInt } from '@peertube/peertube-core-utils'-import { Video, VideoChannel, VideoChannelSync, VideoCreateResult, VideoDetails } from '@peertube/peertube-models'+import { User, Video, VideoChannelSync, VideoCreateResult, VideoDetails } from '@peertube/peertube-models'import { parallelTests, root } from '@peertube/peertube-node-utils'import { ChildProcess, fork } from 'child_process'import { copy } from 'fs-extra/esm'@@ -31,6 +31,7 @@ import {BlacklistCommand,CaptionsCommand,ChangeOwnershipCommand,+ ChannelCollaboratorsCommand,ChannelSyncsCommand,ChannelsCommand,ChaptersCommand,@@ -82,6 +83,7 @@ export class PeerTubeServer {parallel?: booleaninternalServerNumber: number+ adminEmail: stringserverNumber?: numbercustomConfigFile?: string@@ -97,7 +99,7 @@ export class PeerTubeServer {password: string}- channel?: VideoChannel+ channel?: User['videoChannels'][0]videoChannelSync?: Partial<VideoChannelSync>video?: Video@@ -170,6 +172,8 @@ export class PeerTubeServer {watchedWordsLists?: WatchedWordsCommandautoTags?: AutomaticTagsCommand+ channelCollaborators?: ChannelCollaboratorsCommand+constructor (options: { serverNumber: number } | { url: string }) {if ((options as any).url) {this.setUrl((options as any).url)@@ -188,6 +192,7 @@ export class PeerTubeServer {}}+ this.adminEmail = this.buildEmail()this.assignCommands()}@@ -406,7 +411,7 @@ export class PeerTubeServer {well_known: this.getDirectoryPath('well-known') + '/'},admin: {- email: `admin${this.internalServerNumber}@example.com`+ email: this.buildEmail()},live: {rtmp: {@@ -477,5 +482,11 @@ export class PeerTubeServer {this.watchedWordsLists = new WatchedWordsCommand(this)this.autoTags = new AutomaticTagsCommand(this)++ this.channelCollaborators = new ChannelCollaboratorsCommand(this)+ }++ private buildEmail () {+ return `admin${this.internalServerNumber}@example.com`}}diff --git a/packages/server-commands/src/users/users-command.ts b/packages/server-commands/src/users/users-command.tsindex a690ed623a..73bab7c9de 100644--- a/packages/server-commands/src/users/users-command.ts+++ b/packages/server-commands/src/users/users-command.ts@@ -12,7 +12,8 @@ import {UserUpdate,UserUpdateMe,UserVideoQuota,- UserVideoRate+ UserVideoRate,+ VideoChannel} from '@peertube/peertube-models'import { unwrapBody } from '../requests/index.js'import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'@@ -282,6 +283,20 @@ export class UsersCommand extends AbstractCommand {})}+ listMyChannels (options: OverrideCommandOptions = {}) {+ const path = '/api/v1/users/me/video-channels'++ return this.getRequestBody<ResultList<VideoChannel>>({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.OK_200+ })+ }++ // ---------------------------------------------------------------------------+deleteMe (options: OverrideCommandOptions = {}) {const path = '/api/v1/users/me'diff --git a/packages/server-commands/src/videos/channel-collaborators-command.ts b/packages/server-commands/src/videos/channel-collaborators-command.tsnew file mode 100644index 0000000000..5c82551458--- /dev/null+++ b/packages/server-commands/src/videos/channel-collaborators-command.ts@@ -0,0 +1,119 @@+import { HttpStatusCode, ResultList, VideoChannelCollaborator } from '@peertube/peertube-models'+import { unwrapBody } from '../requests/index.js'+import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'++export class ChannelCollaboratorsCommand extends AbstractCommand {+ list (+ options: OverrideCommandOptions & {+ channel: string+ }+ ) {+ const { channel } = options+ const path = '/api/v1/video-channels/' + channel + '/collaborators'++ return this.getRequestBody<ResultList<VideoChannelCollaborator>>({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.OK_200+ })+ }++ async invite (+ options: OverrideCommandOptions & {+ channel: string+ target: string+ }+ ) {+ const { channel, target } = options+ const path = '/api/v1/video-channels/' + channel + '/collaborators/invite'++ const body = await unwrapBody<{ collaborator: VideoChannelCollaborator }>(this.postBodyRequest({+ ...options,++ path,+ fields: {+ accountHandle: target+ },+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.OK_200+ }))++ return body.collaborator+ }++ accept (+ options: OverrideCommandOptions & {+ channel: string+ id: number+ }+ ) {+ const { id, channel } = options+ const path = '/api/v1/video-channels/' + channel + '/collaborators/' + id + '/accept'++ return this.postBodyRequest({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }++ reject (+ options: OverrideCommandOptions & {+ channel: string+ id: number+ }+ ) {+ const { id, channel } = options+ const path = '/api/v1/video-channels/' + channel + '/collaborators/' + id + '/reject'++ return this.postBodyRequest({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }++ remove (+ options: OverrideCommandOptions & {+ channel: string+ id: number+ }+ ) {+ const { id, channel } = options+ const path = '/api/v1/video-channels/' + channel + '/collaborators/' + id++ return this.deleteRequest({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }++ // ---------------------------------------------------------------------------++ async createEditor (user: string, channel: string) {+ const collaboratorToken = await this.server.users.generateUserAndToken(user)++ const { id } = await this.invite({ channel, target: user })++ await this.accept({ channel, id, token: collaboratorToken })++ return collaboratorToken+ }++ async createInvited (user: string, channel: string) {+ const collaboratorToken = await this.server.users.generateUserAndToken(user)++ await this.invite({ channel, target: user })++ return collaboratorToken+ }+}diff --git a/packages/server-commands/src/videos/channel-syncs-command.ts b/packages/server-commands/src/videos/channel-syncs-command.tsindex 718000c8a0..217e9be2f5 100644--- a/packages/server-commands/src/videos/channel-syncs-command.ts+++ b/packages/server-commands/src/videos/channel-syncs-command.ts@@ -1,17 +1,20 @@-import { HttpStatusCode, ResultList, VideoChannelSync, VideoChannelSyncCreate } from '@peertube/peertube-models'import { pick } from '@peertube/peertube-core-utils'+import { HttpStatusCode, ResultList, VideoChannelSync, VideoChannelSyncCreate } from '@peertube/peertube-models'import { unwrapBody } from '../requests/index.js'import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'export class ChannelSyncsCommand extends AbstractCommand {private static readonly API_PATH = '/api/v1/video-channel-syncs'- listByAccount (options: OverrideCommandOptions & {- accountName: string- start?: number- count?: number- sort?: string- }) {+ listByAccount (+ options: OverrideCommandOptions & {+ accountName: string+ start?: number+ count?: number+ sort?: string+ includeCollaborations?: boolean+ }+ ) {const { accountName, sort = 'createdAt' } = optionsconst path = `/api/v1/accounts/${accountName}/video-channel-syncs`@@ -20,15 +23,17 @@ export class ChannelSyncsCommand extends AbstractCommand {...options,path,- query: { sort, ...pick(options, [ 'start', 'count' ]) },+ query: { sort, ...pick(options, [ 'start', 'count', 'includeCollaborations' ]) },implicitToken: true,defaultExpectedStatus: HttpStatusCode.OK_200})}- async create (options: OverrideCommandOptions & {- attributes: VideoChannelSyncCreate- }) {+ async create (+ options: OverrideCommandOptions & {+ attributes: VideoChannelSyncCreate+ }+ ) {return unwrapBody<{ videoChannelSync: VideoChannelSync }>(this.postBodyRequest({...options,@@ -39,9 +44,11 @@ export class ChannelSyncsCommand extends AbstractCommand {}))}- delete (options: OverrideCommandOptions & {- channelSyncId: number- }) {+ delete (+ options: OverrideCommandOptions & {+ channelSyncId: number+ }+ ) {const path = `${ChannelSyncsCommand.API_PATH}/${options.channelSyncId}`return this.deleteRequest({diff --git a/packages/server-commands/src/videos/channels-command.ts b/packages/server-commands/src/videos/channels-command.tsindex 14b6d8d16f..0bab8b7c57 100644--- a/packages/server-commands/src/videos/channels-command.ts+++ b/packages/server-commands/src/videos/channels-command.ts@@ -39,6 +39,7 @@ export class ChannelsCommand extends AbstractCommand {sort?: stringwithStats?: booleansearch?: string+ includeCollaborations?: boolean}) {const { accountName, sort = 'createdAt' } = options@@ -48,7 +49,7 @@ export class ChannelsCommand extends AbstractCommand {...options,path,- query: { sort, ...pick(options, [ 'start', 'count', 'withStats', 'search' ]) },+ query: { sort, ...pick(options, [ 'start', 'count', 'withStats', 'search', 'includeCollaborations' ]) },implicitToken: false,defaultExpectedStatus: HttpStatusCode.OK_200})@@ -144,6 +145,12 @@ export class ChannelsCommand extends AbstractCommand {return id}+ async getDefaultId (options: OverrideCommandOptions) {+ const { videoChannels } = await this.server.users.getMyInfo(options)++ return videoChannels[0].id+ }+// ---------------------------------------------------------------------------updateImage (diff --git a/packages/server-commands/src/videos/comments-command.ts b/packages/server-commands/src/videos/comments-command.tsindex 86ea6332b4..55c8af9960 100644--- a/packages/server-commands/src/videos/comments-command.ts+++ b/packages/server-commands/src/videos/comments-command.ts@@ -23,7 +23,6 @@ type ListForAdminOrAccountCommonOptions = {}export class CommentsCommand extends AbstractCommand {-private lastVideoId: number | stringprivate lastThreadId: numberprivate lastReplyId: number@@ -51,6 +50,7 @@ export class CommentsCommand extends AbstractCommand {listCommentsOnMyVideos (options: OverrideCommandOptions & ListForAdminOrAccountCommonOptions & {isHeldForReview?: boolean+ includeCollaborations?: boolean} = {}) {const path = '/api/v1/users/me/videos/comments'@@ -61,7 +61,7 @@ export class CommentsCommand extends AbstractCommand {query: {...this.buildListForAdminOrAccountQuery(options),- isHeldForReview: options.isHeldForReview+ ...pick(options, [ 'isHeldForReview', 'includeCollaborations' ])},implicitToken: true,defaultExpectedStatus: HttpStatusCode.OK_200@@ -78,13 +78,15 @@ export class CommentsCommand extends AbstractCommand {// ---------------------------------------------------------------------------- listThreads (options: OverrideCommandOptions & {- videoId: number | string- videoPassword?: string- start?: number- count?: number- sort?: string- }) {+ listThreads (+ options: OverrideCommandOptions & {+ videoId: number | string+ videoPassword?: string+ start?: number+ count?: number+ sort?: string+ }+ ) {const { start, count, sort, videoId, videoPassword } = optionsconst path = '/api/v1/videos/' + videoId + '/comment-threads'@@ -99,10 +101,12 @@ export class CommentsCommand extends AbstractCommand {})}- getThread (options: OverrideCommandOptions & {- videoId: number | string- threadId: number- }) {+ getThread (+ options: OverrideCommandOptions & {+ videoId: number | string+ threadId: number+ }+ ) {const { videoId, threadId } = optionsconst path = '/api/v1/videos/' + videoId + '/comment-threads/' + threadId@@ -115,21 +119,25 @@ export class CommentsCommand extends AbstractCommand {})}- async getThreadOf (options: OverrideCommandOptions & {- videoId: number | string- text: string- }) {+ async getThreadOf (+ options: OverrideCommandOptions & {+ videoId: number | string+ text: string+ }+ ) {const { videoId, text } = optionsconst threadId = await this.findCommentId({ videoId, text })return this.getThread({ ...options, videoId, threadId })}- async createThread (options: OverrideCommandOptions & {- videoId: number | string- text: string- videoPassword?: string- }) {+ async createThread (+ options: OverrideCommandOptions & {+ videoId: number | string+ text: string+ videoPassword?: string+ }+ ) {const { videoId, text, videoPassword } = optionsconst path = '/api/v1/videos/' + videoId + '/comment-threads'@@ -149,12 +157,14 @@ export class CommentsCommand extends AbstractCommand {return body.comment}- async addReply (options: OverrideCommandOptions & {- videoId: number | string- toCommentId: number- text: string- videoPassword?: string- }) {+ async addReply (+ options: OverrideCommandOptions & {+ videoId: number | string+ toCommentId: number+ text: string+ videoPassword?: string+ }+ ) {const { videoId, toCommentId, text, videoPassword } = optionsconst path = '/api/v1/videos/' + videoId + '/comments/' + toCommentId@@ -173,22 +183,28 @@ export class CommentsCommand extends AbstractCommand {return body.comment}- async addReplyToLastReply (options: OverrideCommandOptions & {- text: string- }) {+ async addReplyToLastReply (+ options: OverrideCommandOptions & {+ text: string+ }+ ) {return this.addReply({ ...options, videoId: this.lastVideoId, toCommentId: this.lastReplyId })}- async addReplyToLastThread (options: OverrideCommandOptions & {- text: string- }) {+ async addReplyToLastThread (+ options: OverrideCommandOptions & {+ text: string+ }+ ) {return this.addReply({ ...options, videoId: this.lastVideoId, toCommentId: this.lastThreadId })}- async findCommentId (options: OverrideCommandOptions & {- videoId: number | string- text: string- }) {+ async findCommentId (+ options: OverrideCommandOptions & {+ videoId: number | string+ text: string+ }+ ) {const { videoId, text } = optionsconst { data } = await this.listForAdmin({ videoId, count: 25, sort: '-createdAt' })@@ -197,10 +213,12 @@ export class CommentsCommand extends AbstractCommand {// ---------------------------------------------------------------------------- delete (options: OverrideCommandOptions & {- videoId: number | string- commentId: number- }) {+ delete (+ options: OverrideCommandOptions & {+ videoId: number | string+ commentId: number+ }+ ) {const { videoId, commentId } = optionsconst path = '/api/v1/videos/' + videoId + '/comments/' + commentId@@ -213,9 +231,11 @@ export class CommentsCommand extends AbstractCommand {})}- async deleteAllComments (options: OverrideCommandOptions & {- videoUUID: string- }) {+ async deleteAllComments (+ options: OverrideCommandOptions & {+ videoUUID: string+ }+ ) {const { data } = await this.listForAdmin({ ...options, start: 0, count: 20 })for (const comment of data) {@@ -227,10 +247,12 @@ export class CommentsCommand extends AbstractCommand {// ---------------------------------------------------------------------------- approve (options: OverrideCommandOptions & {- videoId: number | string- commentId: number- }) {+ approve (+ options: OverrideCommandOptions & {+ videoId: number | string+ commentId: number+ }+ ) {const { videoId, commentId } = optionsconst path = '/api/v1/videos/' + videoId + '/comments/' + commentId + '/approve'diff --git a/packages/server-commands/src/videos/index.ts b/packages/server-commands/src/videos/index.tsindex d704b0446f..ffb8a884ea 100644--- a/packages/server-commands/src/videos/index.ts+++ b/packages/server-commands/src/videos/index.ts@@ -1,5 +1,6 @@export * from './blacklist-command.js'export * from './captions-command.js'+export * from './channel-collaborators-command.js'export * from './change-ownership-command.js'export * from './channels.js'export * from './channels-command.js'diff --git a/packages/server-commands/src/videos/playlists-command.ts b/packages/server-commands/src/videos/playlists-command.tsindex 3fca7e03f1..85688a9edf 100644--- a/packages/server-commands/src/videos/playlists-command.ts+++ b/packages/server-commands/src/videos/playlists-command.ts@@ -48,10 +48,11 @@ export class PlaylistsCommand extends AbstractCommand {count?: numbersort?: stringplaylistType?: VideoPlaylistType_Type+ includeCollaborations?: boolean}) {const path = '/api/v1/video-channels/' + options.handle + '/video-playlists'- const query = pick(options, [ 'start', 'count', 'sort', 'playlistType' ])+ const query = pick(options, [ 'start', 'count', 'sort', 'playlistType', 'includeCollaborations' ])return this.getRequestBody<ResultList<VideoPlaylist>>({...options,@@ -71,10 +72,12 @@ export class PlaylistsCommand extends AbstractCommand {sort?: stringsearch?: stringplaylistType?: VideoPlaylistType_Type+ includeCollaborations?: boolean+ channelNameOneOf?: string[]}) {const path = '/api/v1/accounts/' + options.handle + '/video-playlists'- const query = pick(options, [ 'start', 'count', 'sort', 'search', 'playlistType' ])+ const query = pick(options, [ 'start', 'count', 'sort', 'search', 'playlistType', 'includeCollaborations', 'channelNameOneOf' ])return this.getRequestBody<ResultList<VideoPlaylist>>({...options,diff --git a/packages/server-commands/src/videos/video-imports-command.ts b/packages/server-commands/src/videos/video-imports-command.tsindex b0c22d332c..0a7ba1f3c8 100644--- a/packages/server-commands/src/videos/video-imports-command.ts+++ b/packages/server-commands/src/videos/video-imports-command.ts@@ -1,12 +1,13 @@-import { HttpStatusCode, ResultList, VideoImport, VideoImportCreate } from '@peertube/peertube-models'+import { HttpStatusCode, ResultList, VideoImport, VideoImportCreate, VideoImportState } from '@peertube/peertube-models'import { unwrapBody } from '../requests/index.js'import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'export class VideoImportsCommand extends AbstractCommand {-- async importVideo (options: OverrideCommandOptions & {- attributes: (Partial<VideoImportCreate> | { torrentfile?: string, previewfile?: string, thumbnailfile?: string })- }) {+ async importVideo (+ options: OverrideCommandOptions & {+ attributes: Partial<VideoImportCreate> | { torrentfile?: string, previewfile?: string, thumbnailfile?: string }+ }+ ) {const { attributes } = optionsconst path = '/api/v1/videos/imports'@@ -37,9 +38,35 @@ export class VideoImportsCommand extends AbstractCommand {}))}- delete (options: OverrideCommandOptions & {- importId: number- }) {+ async quickImport (+ options: OverrideCommandOptions & {+ name: string+ targetUrl: string+ channelId?: number+ }+ ) {+ const { name, targetUrl } = options++ const channelId = options.channelId ?? await this.server.channels.getDefaultId(options)++ return this.importVideo({+ ...options,++ attributes: {+ name,+ targetUrl,+ channelId+ }+ })+ }++ // ---------------------------------------------------------------------------++ delete (+ options: OverrideCommandOptions & {+ importId: number+ }+ ) {const path = '/api/v1/videos/imports/' + options.importIdreturn this.deleteRequest({@@ -51,9 +78,11 @@ export class VideoImportsCommand extends AbstractCommand {})}- cancel (options: OverrideCommandOptions & {- importId: number- }) {+ cancel (+ options: OverrideCommandOptions & {+ importId: number+ }+ ) {const path = '/api/v1/videos/imports/' + options.importId + '/cancel'return this.postBodyRequest({@@ -65,22 +94,45 @@ export class VideoImportsCommand extends AbstractCommand {})}- getMyVideoImports (options: OverrideCommandOptions & {+ listMyVideoImports (options: OverrideCommandOptions & {sort?: stringtargetUrl?: stringvideoChannelSyncId?: numbersearch?: string+ includeCollaborations?: boolean} = {}) {- const { sort, targetUrl, videoChannelSyncId, search } = options+ const { sort, targetUrl, videoChannelSyncId, search, includeCollaborations } = optionsconst path = '/api/v1/users/me/videos/imports'return this.getRequestBody<ResultList<VideoImport>>({...options,path,- query: { sort, targetUrl, videoChannelSyncId, search },+ query: { sort, targetUrl, videoChannelSyncId, search, includeCollaborations },implicitToken: true,defaultExpectedStatus: HttpStatusCode.OK_200})}++ // ---------------------------------------------------------------------------++ async getVideoId (+ options: OverrideCommandOptions & {+ importId: number+ }+ ) {+ const { data } = await this.listMyVideoImports(options)++ return data.find(i => i.id === options.importId)?.video?.id+ }++ async cancelAll (options: OverrideCommandOptions = {}) {+ const { data } = await this.listMyVideoImports(options)++ for (const videoImport of data) {+ if (videoImport.state.id === VideoImportState.PENDING) {+ await this.cancel({ ...options, importId: videoImport.id })+ }+ }+ }}diff --git a/packages/server-commands/src/videos/videos-command.ts b/packages/server-commands/src/videos/videos-command.tsindex 4e626dfa98..905387b638 100644--- a/packages/server-commands/src/videos/videos-command.ts+++ b/packages/server-commands/src/videos/videos-command.ts@@ -229,14 +229,18 @@ export class VideosCommand extends AbstractCommand {// ---------------------------------------------------------------------------- listMyVideos (options: OverrideCommandOptions & VideosCommonQuery & { channelId?: number, channelNameOneOf?: string[] } = {}) {+ listMyVideos (options: OverrideCommandOptions & VideosCommonQuery & {+ channelId?: number+ channelNameOneOf?: string[]+ includeCollaborations?: boolean+ } = {}) {const path = '/api/v1/users/me/videos'return this.getRequestBody<ResultList<Video>>({...options,path,- query: { ...this.buildListQuery(options), ...pick(options, [ 'channelId', 'channelNameOneOf' ]) },+ query: { ...this.buildListQuery(options), ...pick(options, [ 'channelId', 'channelNameOneOf', 'includeCollaborations' ]) },implicitToken: true,defaultExpectedStatus: HttpStatusCode.OK_200})diff --git a/packages/tests/src/api/activitypub/client.ts b/packages/tests/src/api/activitypub/client.tsindex 65d6bb66b9..e1a9233cee 100644--- a/packages/tests/src/api/activitypub/client.ts+++ b/packages/tests/src/api/activitypub/client.ts@@ -5,8 +5,11 @@ import {ActivityPubActor,HttpStatusCode,VideoComment,+ VideoCreateResult,VideoObject,+ VideoPlaylistCreateResult,VideoPlaylistPrivacy,+ VideoPrivacy,WatchActionObject} from '@peertube/peertube-models'import {@@ -25,8 +28,13 @@ import { expect } from 'chai'describe('Test ActivityPub', function () {let servers: PeerTubeServer[] = []- let video: { id: number, uuid: string, shortUUID: string }- let playlist: { id: number, uuid: string, shortUUID: string }++ let video: VideoCreateResult+ let privateVideo: VideoCreateResult++ let playlist: VideoPlaylistCreateResult+ let privatePlaylist: VideoPlaylistCreateResult+let comment: VideoCommentasync function testAccount (path: string, hasIcon: boolean) {@@ -132,11 +140,24 @@ describe('Test ActivityPub', function () {{video = await servers[0].videos.quickUpload({ name: 'video' })+ privateVideo = await servers[0].videos.quickUpload({ name: 'private video', privacy: VideoPrivacy.PRIVATE })}{- const attributes = { displayName: 'playlist', privacy: VideoPlaylistPrivacy.PUBLIC, videoChannelId: servers[0].store.channel.id }- playlist = await servers[0].playlists.create({ attributes })+ playlist = await servers[0].playlists.create({+ attributes: {+ displayName: 'playlist',+ privacy: VideoPlaylistPrivacy.PUBLIC,+ videoChannelId: servers[0].store.channel.id+ }+ })+ privatePlaylist = await servers[0].playlists.create({+ attributes: {+ displayName: 'private playlist',+ privacy: VideoPlaylistPrivacy.PRIVATE,+ videoChannelId: servers[0].store.channel.id+ }+ })}comment = await servers[0].comments.createThread({ text: 'thread', videoId: video.id })@@ -213,6 +234,11 @@ describe('Test ActivityPub', function () {expect(object.watchSections[0].endTimestamp).to.equal(2)})+ it('Should not return private video or private playlist', async function () {+ await makeActivityPubGetRequest(servers[0].url, '/videos/watch/' + privateVideo.uuid, HttpStatusCode.UNAUTHORIZED_401)+ await makeActivityPubGetRequest(servers[0].url, '/video-playlists/' + privatePlaylist.uuid, HttpStatusCode.UNAUTHORIZED_401)+ })+after(async function () {await cleanupTests(servers)})diff --git a/packages/tests/src/api/check-params/channel-collaborators.ts b/packages/tests/src/api/check-params/channel-collaborators.tsnew file mode 100644index 0000000000..ad1e811950--- /dev/null+++ b/packages/tests/src/api/check-params/channel-collaborators.ts@@ -0,0 +1,488 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { HttpStatusCode } from '@peertube/peertube-models'+import {+ cleanupTests,+ createMultipleServers,+ doubleFollow,+ PeerTubeServer,+ setAccessTokensToServers,+ waitJobs+} from '@peertube/peertube-server-commands'++describe('Test video channel collaborators API validators', function () {+ let server: PeerTubeServer+ let remoteServer: PeerTubeServer++ let collaboratorToken: string+ let collaboratorId: number++ let collaboratorId2: number++ let unrelatedCollaboratorId: number++ let userToken: string++ before(async function () {+ this.timeout(60000)++ const servers = await createMultipleServers(2, {+ rates_limit: {+ login: {+ max: 100+ }+ }+ })++ server = servers[0]+ remoteServer = servers[1]+ await setAccessTokensToServers(servers)+ await doubleFollow(servers[0], servers[1])++ await servers[1].videos.quickUpload({ name: 'remote video' })++ collaboratorToken = await server.users.generateUserAndToken('collaborator')+ await server.users.generateUserAndToken('collaborator2')+ userToken = await server.users.generateUserAndToken('user1')++ await server.users.generateUserAndToken('user2')++ const { id } = await server.channelCollaborators.invite({ channel: 'user1_channel', target: 'user2' })+ unrelatedCollaboratorId = id++ await waitJobs(servers)+ })++ describe('Invite', function () {+ it('Should fail when not authenticated', async function () {+ await server.channelCollaborators.invite({+ token: null,+ channel: 'root_channel',+ target: 'collaborator',+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a bad channel handle', async function () {+ await server.channelCollaborators.invite({+ channel: 'bad handle',+ target: 'collaborator',+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })++ await server.channelCollaborators.invite({+ channel: 'root_channel@' + remoteServer.host,+ target: 'collaborator',+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with a non owned channel', async function () {+ await server.channelCollaborators.invite({+ token: userToken,+ channel: 'root_channel',+ target: 'collaborator',+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with a bad account handle', async function () {+ await server.channelCollaborators.invite({+ channel: 'root_channel',+ target: 'bad handle',+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })++ await server.channelCollaborators.invite({+ channel: 'root_channel',+ target: 'root@' + remoteServer.host,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with myself', async function () {+ await server.channelCollaborators.invite({+ channel: 'root_channel',+ target: 'root',+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail for a collaborator to invite another collaborator', async function () {+ const collaboratorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')++ await server.channelCollaborators.invite({+ token: collaboratorToken,+ channel: 'root_channel',+ target: 'collaborator2',+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should succeed with the correct parameters', async function () {+ {+ const { id } = await server.channelCollaborators.invite({ channel: 'root_channel', target: 'collaborator' })+ collaboratorId = id+ }++ {+ const { id } = await server.channelCollaborators.invite({ channel: 'root_channel', target: 'collaborator2' })+ collaboratorId2 = id+ }+ })++ it('Should fail to re-invite the user', async function () {+ await server.channelCollaborators.invite({+ channel: 'root_channel',+ target: 'collaborator',+ expectedStatus: HttpStatusCode.CONFLICT_409+ })+ })++ it('Should limit the number of collaborators', async function () {+ const claireToken = await server.users.generateUserAndToken('claire')++ for (let i = 0; i < 20; i++) {+ await server.channelCollaborators.createEditor('editor' + i, 'claire_channel')+ }++ await server.users.generateUserAndToken('celie')++ await server.channelCollaborators.invite({+ channel: 'claire_channel',+ token: claireToken,+ target: 'celie',+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+ })++ describe('Common Accept/Reject', function () {+ it('Should fail when not authenticated', async function () {+ const options = {+ token: null,+ channel: 'root_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ }++ await server.channelCollaborators.accept(options)+ })++ it('Should fail to accept the collaborator with another user', async function () {+ const options = {+ token: userToken,+ channel: 'root_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ }++ await server.channelCollaborators.accept(options)+ })++ it('Should fail with an invalid collaborator id', async function () {+ {+ const options = {+ token: collaboratorToken,+ channel: 'root_channel',+ id: 'toto' as any,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ }++ await server.channelCollaborators.accept(options)++ {+ const options = {+ token: collaboratorToken,+ channel: 'root_channel',+ id: 42,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ }++ await server.channelCollaborators.accept(options)+ }+ }+ })++ it('Should fail with a bad channel handle', async function () {+ {+ const options = {+ token: collaboratorToken,+ channel: 'bad handle',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ }++ await server.channelCollaborators.accept(options)+ }++ {+ const options = {+ token: collaboratorToken,+ channel: 'root_channel@' + remoteServer.host,+ id: collaboratorId,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ }++ await server.channelCollaborators.accept(options)+ }+ })++ it('Should fail with another channel than the collaborator id', async function () {+ const options = {+ token: collaboratorToken,+ channel: 'user1_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ }++ await server.channelCollaborators.accept(options)+ })++ it('Should fail to accept another collaborator invitation', async function () {+ const options = {+ token: collaboratorToken,+ channel: 'root_channel',+ id: collaboratorId2,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ }++ await server.channelCollaborators.accept(options)+ })++ it('Should fail with a channel not related to the collaborator id', async function () {+ {+ const options = {+ token: collaboratorToken,+ channel: 'root_channel',+ id: unrelatedCollaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ }++ await server.channelCollaborators.accept(options)+ }++ {+ const options = {+ token: collaboratorToken,+ channel: 'user1_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ }++ await server.channelCollaborators.accept(options)+ }+ })+ })++ describe('Accept', function () {+ it('Should succeed with the correct params', async function () {+ await server.channelCollaborators.accept({+ token: collaboratorToken,+ channel: 'root_channel',+ id: collaboratorId+ })+ })++ it('Should fail to re-accept the same collaborator', async function () {+ await server.channelCollaborators.accept({+ token: collaboratorToken,+ channel: 'root_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail to invite an accepted collaborator', async function () {+ await server.channelCollaborators.invite({+ channel: 'root_channel',+ target: 'collaborator',+ expectedStatus: HttpStatusCode.CONFLICT_409+ })+ })++ it('Should fail to invite another collaborator with an existing collaborator token', async function () {+ await server.channelCollaborators.invite({+ token: collaboratorToken,+ channel: 'root_channel',+ target: 'collaborator2',+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })+ })++ describe('Remove', function () {+ it('Should fail when not authenticated', async function () {+ await server.channelCollaborators.remove({+ token: null,+ channel: 'root_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail to remove the collaborator with another user', async function () {+ await server.channelCollaborators.remove({+ token: userToken,+ channel: 'root_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with an invalid collaborator id', async function () {+ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'root_channel',+ id: 'toto' as any,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })++ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'root_channel',+ id: 42,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with a bad channel handle', async function () {+ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'bad handle',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })++ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'root@' + remoteServer.host,+ id: collaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with a channel not related to the collaborator id', async function () {+ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'root_channel',+ id: unrelatedCollaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })++ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'user1_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail for a collaborator to remove another collaborator', async function () {+ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'root_channel',+ id: collaboratorId2,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should succeed with the correct params', async function () {+ await server.channelCollaborators.remove({+ token: collaboratorToken,+ channel: 'root_channel',+ id: collaboratorId+ })++ await server.channelCollaborators.remove({+ token: server.accessToken,+ channel: 'root_channel',+ id: collaboratorId2+ })+ })+ })++ describe('Reject', function () {+ before(async function () {+ const { id } = await server.channelCollaborators.invite({ channel: 'root_channel', target: 'collaborator' })+ collaboratorId = id+ })++ it('Should succeed with the correct params', async function () {+ await server.channelCollaborators.reject({+ token: collaboratorToken,+ channel: 'root_channel',+ id: collaboratorId+ })+ })++ it('Should fail to reject the same collaborator', async function () {+ await server.channelCollaborators.reject({+ token: collaboratorToken,+ channel: 'root_channel',+ id: collaboratorId,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+ })++ describe('List', function () {+ before(async function () {+ const { id } = await server.channelCollaborators.invite({ channel: 'root_channel', target: 'collaborator' })+ collaboratorId = id+ })++ it('Should fail when not authenticated', async function () {+ await server.channelCollaborators.list({+ token: null,+ channel: 'root_channel',+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a bad channel handle', async function () {+ await server.channelCollaborators.list({+ token: userToken,+ channel: 'bad handle',+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })++ await server.channelCollaborators.list({+ token: userToken,+ channel: 'root@' + remoteServer.host,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with a non owned channel', async function () {+ await server.channelCollaborators.list({+ token: userToken,+ channel: 'root_channel',+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail to list if the collaborator is not accepted yet', async function () {+ await server.channelCollaborators.list({+ token: collaboratorToken,+ channel: 'root_channel',+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })++ await server.channelCollaborators.accept({ token: collaboratorToken, channel: 'root_channel', id: collaboratorId })++ await server.channelCollaborators.list({+ token: collaboratorToken,+ channel: 'root_channel'+ })+ })++ it('Should succeed with the correct parameters', async function () {+ await server.channelCollaborators.list({ channel: 'root_channel' })+ })+ })++ after(async function () {+ await cleanupTests([ server, remoteServer ])+ })+})diff --git a/packages/tests/src/api/check-params/channel-import-videos.ts b/packages/tests/src/api/check-params/channel-import-videos.tsindex 0250c87825..3ada14ebb6 100644--- a/packages/tests/src/api/check-params/channel-import-videos.ts+++ b/packages/tests/src/api/check-params/channel-import-videos.ts@@ -1,8 +1,7 @@/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'-import { areHttpImportTestsDisabled } from '@peertube/peertube-node-utils'import { HttpStatusCode } from '@peertube/peertube-models'+import { areHttpImportTestsDisabled } from '@peertube/peertube-node-utils'import {ChannelsCommand,cleanupTests,@@ -11,6 +10,7 @@ import {setAccessTokensToServers,setDefaultVideoChannel} from '@peertube/peertube-server-commands'+import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'describe('Test videos import in a channel API validator', function () {let server: PeerTubeServer@@ -23,6 +23,8 @@ describe('Test videos import in a channel API validator', function () {videoQuotaDaily: -1,channelSyncId: -1}+ let editorToken: string+let command: ChannelsCommand// ---------------------------------------------------------------@@ -63,6 +65,8 @@ describe('Test videos import in a channel API validator', function () {userInfo.channelSyncId = videoChannelSync.id}+ editorToken = await server.channelCollaborators.createEditor('user_editor', userCreds.username + '_channel')+command = server.channels})@@ -194,13 +198,16 @@ describe('Test videos import in a channel API validator', function () {})})- it('Should succeed when sync is run with root and for another user\'s channel', async function () {+ it('Should succeed when sync is run with root or an editor', async function () {if (!areHttpImportTestsDisabled()) return- await command.importVideos({- channelName: 'fake_channel',- externalChannelUrl: FIXTURE_URLS.youtubeChannel- })+ for (const token of [ server.accessToken, editorToken ]) {+ await command.importVideos({+ channelName: 'fake_channel',+ externalChannelUrl: FIXTURE_URLS.youtubeChannel,+ token+ })+ }})after(async function () {diff --git a/packages/tests/src/api/check-params/video-channel-syncs.ts b/packages/tests/src/api/check-params/channel-syncs.tssimilarity index 85%rename from packages/tests/src/api/check-params/video-channel-syncs.tsrename to packages/tests/src/api/check-params/channel-syncs.tsindex aff3dde345..c0cafe2516 100644--- a/packages/tests/src/api/check-params/video-channel-syncs.ts+++ b/packages/tests/src/api/check-params/channel-syncs.ts@@ -4,6 +4,7 @@ import { HttpStatusCode, VideoChannelSyncCreate } from '@peertube/peertube-modelimport {ChannelSyncsCommand,createSingleServer,+ killallServers,makePostBodyRequest,PeerTubeServer,setAccessTokensToServers,@@ -23,6 +24,7 @@ describe('Test video channel sync API validator', () => {channelId: -1,syncId: -1}+ let editorToken: stringasync function withChannelSyncDisabled<T> (callback: () => Promise<T>): Promise<void> {try {@@ -54,7 +56,7 @@ describe('Test video channel sync API validator', () => {}before(async function () {- this.timeout(30_000)+ this.timeout(60_000)server = await createSingleServer(1)@@ -73,6 +75,8 @@ describe('Test video channel sync API validator', () => {userInfo.channelId = videoChannels[0].id}+ editorToken = await server.channelCollaborators.createEditor('user_editor', userInfo.username + '_channel')+await server.config.enableChannelSync()})@@ -159,16 +163,28 @@ describe('Test video channel sync API validator', () => {})})- it('Should succeed to create a sync with root and for another user\'s channel', async function () {- const { videoChannelSync } = await command.create({- token: server.accessToken,- attributes: {- ...baseCorrectParams,- videoChannelId: userInfo.channelId- },- expectedStatus: HttpStatusCode.OK_200- })- userInfo.syncId = videoChannelSync.id+ it('Should succeed to create a sync with root and editor tokens for another user channel', async function () {+ const create = async (token: string) => {+ const { videoChannelSync } = await command.create({+ token,+ attributes: {+ ...baseCorrectParams,++ videoChannelId: userInfo.channelId+ },+ expectedStatus: HttpStatusCode.OK_200+ })++ return videoChannelSync+ }++ {+ const sync = await create(editorToken)+ await command.delete({ channelSyncId: sync.id })+ }++ const sync = await create(server.accessToken)+ userInfo.syncId = sync.id})it('Should succeed with the correct parameters', async function () {@@ -194,7 +210,7 @@ describe('Test video channel sync API validator', () => {})})- describe('When listing my channel syncs', function () {+ describe('When listing channel syncs', function () {const myPath = '/api/v1/accounts/root/video-channel-syncs'it('Should fail with a bad start pagination', async function () {@@ -285,21 +301,18 @@ describe('Test video channel sync API validator', () => {})})- it('Should succeed when user delete a sync they own', async function () {- const { videoChannelSync } = await command.create({- attributes: {- externalChannelUrl: FIXTURE_URLS.youtubeChannel,- videoChannelId: userInfo.channelId- },- token: server.accessToken,- expectedStatus: HttpStatusCode.OK_200- })+ it('Should succeed with appropriate user or edit tokens', async function () {+ for (const token of [ server.accessToken, editorToken ]) {+ const { videoChannelSync } = await command.create({+ attributes: {+ externalChannelUrl: FIXTURE_URLS.youtubeChannel,+ videoChannelId: userInfo.channelId+ },+ token: userInfo.accessToken+ })- await command.delete({- channelSyncId: videoChannelSync.id,- token: server.accessToken,- expectedStatus: HttpStatusCode.NO_CONTENT_204- })+ await command.delete({ channelSyncId: videoChannelSync.id, token })+ }})it('Should succeed even when synchronization is disabled', async function () {@@ -314,6 +327,6 @@ describe('Test video channel sync API validator', () => {})after(async function () {- await server?.kill()+ await killallServers([ server ])})})diff --git a/packages/tests/src/api/check-params/video-channels.ts b/packages/tests/src/api/check-params/channels.tssimilarity index 91%rename from packages/tests/src/api/check-params/video-channels.tsrename to packages/tests/src/api/check-params/channels.tsindex 84b962b19f..e7c0713b28 100644--- a/packages/tests/src/api/check-params/video-channels.ts+++ b/packages/tests/src/api/check-params/channels.ts@@ -1,9 +1,7 @@/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { expect } from 'chai'import { omit } from '@peertube/peertube-core-utils'import { HttpStatusCode, VideoChannelUpdate } from '@peertube/peertube-models'-import { checkBadCountPagination, checkBadSortPagination, checkBadStartPagination } from '@tests/shared/checks.js'import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'import {ChannelsCommand,@@ -16,6 +14,8 @@ import {PeerTubeServer,setAccessTokensToServers} from '@peertube/peertube-server-commands'+import { checkBadCountPagination, checkBadSortPagination, checkBadStartPagination } from '@tests/shared/checks.js'+import { expect } from 'chai'describe('Test video channels API validator', function () {const videoChannelPath = '/api/v1/video-channels'@@ -28,6 +28,7 @@ describe('Test video channels API validator', function () {videoQuotaDaily: -1}let command: ChannelsCommand+ let editorToken: string// ---------------------------------------------------------------@@ -155,6 +156,8 @@ describe('Test video channels API validator', function () {fields: baseCorrectParams,expectedStatus: HttpStatusCode.OK_200})++ editorToken = await server.channelCollaborators.createEditor('editor', 'super_channel')})it('Should fail when adding a channel with the same username', async function () {@@ -222,13 +225,15 @@ describe('Test video channels API validator', function () {})it('Should succeed with the correct parameters', async function () {- await makePutBodyRequest({- url: server.url,- path,- token: server.accessToken,- fields: baseCorrectParams,- expectedStatus: HttpStatusCode.NO_CONTENT_204- })+ for (const token of [ server.accessToken, editorToken ]) {+ await makePutBodyRequest({+ url: server.url,+ path,+ token,+ fields: baseCorrectParams,+ expectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }})})@@ -278,19 +283,20 @@ describe('Test video channels API validator', function () {})it('Should succeed with the correct params', async function () {- for (const type of types) {- const fields = {}- const attaches = {- [type + 'file']: buildAbsoluteFixturePath('avatar.png')+ for (const token of [ server.accessToken, editorToken ]) {+ for (const type of types) {+ const fields = {}+ const attaches = { [type + 'file']: buildAbsoluteFixturePath('avatar.png') }++ await makeUploadRequest({+ url: server.url,+ path: `${path}/${type}/pick`,+ token,+ fields,+ attaches,+ expectedStatus: HttpStatusCode.OK_200+ })}- await makeUploadRequest({- url: server.url,- path: `${path}/${type}/pick`,- token: server.accessToken,- fields,- attaches,- expectedStatus: HttpStatusCode.OK_200- })}})})@@ -347,7 +353,9 @@ describe('Test video channels API validator', function () {})it('Should succeed with the correct params', async function () {- await makeGetRequest({ url: server.url, path, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ for (const token of [ server.accessToken, editorToken ]) {+ await makeGetRequest({ url: server.url, path, token, expectedStatus: HttpStatusCode.OK_200 })+ }})})@@ -364,6 +372,10 @@ describe('Test video channels API validator', function () {await command.delete({ channelName: 'super_channel2', expectedStatus: HttpStatusCode.NOT_FOUND_404 })})+ it('Should fail with a another user', async function () {+ await command.delete({ token: editorToken, channelName: 'super_channel', expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ })+it('Should succeed with the correct parameters', async function () {await command.delete({ channelName: 'super_channel' })})diff --git a/packages/tests/src/api/check-params/generate-download.ts b/packages/tests/src/api/check-params/generate-download.tsindex 618d13f199..abf0bbed3e 100644--- a/packages/tests/src/api/check-params/generate-download.ts+++ b/packages/tests/src/api/check-params/generate-download.ts@@ -21,23 +21,28 @@ describe('Test generate download API validator', function () {})describe('Download rights', function () {- let videoFileToken: string+ let userFileToken: string+ let editorFileToken: string+let videoId: stringlet videoFileIds: number[]- let user3: string- let user4: string+ let userToken: string+ let anotherUserToken: string+ let editorToken: stringbefore(async function () {this.timeout(60000)- user3 = await server.users.generateUserAndToken('user3')- user4 = await server.users.generateUserAndToken('user4')+ userToken = await server.users.generateUserAndToken('user')+ anotherUserToken = await server.users.generateUserAndToken('another_user')+ editorToken = await server.channelCollaborators.createEditor('editor', 'user_channel')- const { uuid } = await server.videos.quickUpload({ name: 'video', token: user3, privacy: VideoPrivacy.PRIVATE })+ const { uuid } = await server.videos.quickUpload({ name: 'video', token: userToken, privacy: VideoPrivacy.PRIVATE })videoId = uuid- videoFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid, token: user3 })+ userFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid, token: userToken })+ editorFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid, token: editorToken })const video = await server.videos.getWithToken({ id: uuid })videoFileIds = [ video.files[0].id ]@@ -45,11 +50,11 @@ describe('Test generate download API validator', function () {await waitJobs([ server ])})- it('Should fail without header token or video file token', async function () {+ it('Should fail without user token or video file token', async function () {await server.videos.generateDownload({ videoId, videoFileIds, token: null, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})- it('Should fail with an invalid header token', async function () {+ it('Should fail with an invalid user token', async function () {await server.videos.generateDownload({ videoId, videoFileIds, token: 'toto', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })})@@ -59,24 +64,27 @@ describe('Test generate download API validator', function () {await server.videos.generateDownload({ videoId, videoFileIds, token: null, query, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})- it('Should fail with header token of another user', async function () {- await server.videos.generateDownload({ videoId, videoFileIds, token: user4, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ it('Should fail with user token of another user', async function () {+ await server.videos.generateDownload({ videoId, videoFileIds, token: anotherUserToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})- it('Should fail with video file token of another user', async function () {- const { uuid: otherVideo } = await server.videos.quickUpload({ name: 'other video' })- const videoFileToken = await server.videoToken.getVideoFileToken({ videoId: otherVideo, token: user4 })+ it('Should fail with video file token of another video', async function () {+ const { uuid: otherVideo } = await server.videos.quickUpload({ name: 'other video', token: userToken })+ const videoFileToken = await server.videoToken.getVideoFileToken({ videoId: otherVideo, token: userToken })const query = { videoFileToken }await server.videos.generateDownload({ videoId, videoFileIds, token: null, query, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})- it('Should succeed with a valid header token', async function () {- await server.videos.generateDownload({ videoId, videoFileIds, token: user3 })+ it('Should succeed with a valid user token', async function () {+ for (const token of [ server.accessToken, userToken, editorToken ]) {+ await server.videos.generateDownload({ videoId, videoFileIds, token })+ }})it('Should succeed with a valid query token', async function () {- await server.videos.generateDownload({ videoId, videoFileIds, token: null, query: { videoFileToken } })+ await server.videos.generateDownload({ videoId, videoFileIds, token: null, query: { videoFileToken: userFileToken } })+ await server.videos.generateDownload({ videoId, videoFileIds, token: null, query: { videoFileToken: editorFileToken } })})})diff --git a/packages/tests/src/api/check-params/index.ts b/packages/tests/src/api/check-params/index.tsindex 74e687f14f..f52644851a 100644--- a/packages/tests/src/api/check-params/index.ts+++ b/packages/tests/src/api/check-params/index.ts@@ -14,7 +14,7 @@ import './jobs.js'import './live.js'import './logs.js'import './metrics.js'-import './my-user.js'+import './user-me.js'import './player-settings.js'import './plugins.js'import './redundancy.js'@@ -35,8 +35,9 @@ import './users-admin.js'import './users-emails.js'import './video-blacklist.js'import './video-captions.js'-import './video-channel-syncs.js'-import './video-channels.js'+import './video-change-ownership.js'+import './channel-syncs.js'+import './channels.js'import './video-chapters.js'import './video-comments.js'import './video-files.js'@@ -51,5 +52,5 @@ import './videos-common-filters.js'import './videos-history.js'import './videos-overviews.js'import './videos.js'-import './views.js'+import './views-and-stats.js'import './watched-words.js'diff --git a/packages/tests/src/api/check-params/live.ts b/packages/tests/src/api/check-params/live.tsindex 8f407405e7..2fd3119066 100644--- a/packages/tests/src/api/check-params/live.ts+++ b/packages/tests/src/api/check-params/live.ts@@ -27,7 +27,10 @@ import { expect } from 'chai'describe('Test video lives API validator', function () {const path = '/api/v1/videos/live'let server: PeerTubeServer- let userAccessToken = ''++ let userAccessToken: string+ let editorToken: string+let channelId: numberlet video: VideoCreateResultlet videoIdNotLive: number@@ -57,10 +60,8 @@ describe('Test video lives API validator', function () {}})- const username = 'user1'- const password = 'my super password'- await server.users.create({ username, password })- userAccessToken = await server.login.getAccessToken({ username, password })+ userAccessToken = await server.users.generateUserAndToken('user1')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel'){const { videoChannels } = await server.users.getMyInfo()@@ -186,7 +187,7 @@ describe('Test video lives API validator', function () {it('Should fail with a bad channel', async function () {const fields = { ...baseCorrectParams, channelId: 545454 }- await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields })+ await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, expectedStatus: HttpStatusCode.NOT_FOUND_404 })})it('Should fail with a bad privacy for replay settings', async function () {@@ -208,7 +209,7 @@ describe('Test video lives API validator', function () {const fields = { ...baseCorrectParams, channelId: customChannelId }- await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields })+ await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})it('Should fail with too many tags', async function () {@@ -296,15 +297,17 @@ describe('Test video lives API validator', function () {it('Should succeed with the correct parameters', async function () {this.timeout(30000)- const res = await makePostBodyRequest({- url: server.url,- path,- token: server.accessToken,- fields: baseCorrectParams,- expectedStatus: HttpStatusCode.OK_200- })+ for (const token of [ server.accessToken, editorToken ]) {+ const res = await makePostBodyRequest({+ url: server.url,+ path,+ token,+ fields: baseCorrectParams,+ expectedStatus: HttpStatusCode.OK_200+ })- video = res.body.video+ video = res.body.video+ }})it('Should forbid if live is disabled', async function () {@@ -415,11 +418,13 @@ describe('Test video lives API validator', function () {})it('Should display private information with appropriate token', async function () {- const live = await command.get({ videoId: video.id })+ for (const token of [ server.accessToken, editorToken ]) {+ const live = await command.get({ videoId: video.id, token })- expect(live.rtmpUrl).to.exist- expect(live.streamKey).to.exist- expect(live.latencyMode).to.exist+ expect(live.rtmpUrl).to.exist+ expect(live.streamKey).to.exist+ expect(live.latencyMode).to.exist+ }})it('Should fail with a bad video id', async function () {@@ -467,7 +472,9 @@ describe('Test video lives API validator', function () {})it('Should succeed with the correct params', async function () {- await command.listSessions({ videoId: video.id })+ for (const token of [ server.accessToken, editorToken ]) {+ await command.listSessions({ videoId: video.id, token })+ }})})@@ -567,7 +574,11 @@ describe('Test video lives API validator', function () {await command.update({ videoId: video.uuid, fields: { saveReplay: false } })await command.update({ videoId: video.shortUUID, fields: { saveReplay: false } })- await command.update({ videoId: video.id, fields: { saveReplay: true, replaySettings: { privacy: VideoPrivacy.PUBLIC } } })+ await command.update({+ videoId: video.id,+ token: editorToken,+ fields: { saveReplay: true, replaySettings: { privacy: VideoPrivacy.PUBLIC } }+ })})it('Should fail to update replay status if replay is not allowed on the instance', async function () {diff --git a/packages/tests/src/api/check-params/player-settings.ts b/packages/tests/src/api/check-params/player-settings.tsindex f7da771d2a..0360027a86 100644--- a/packages/tests/src/api/check-params/player-settings.ts+++ b/packages/tests/src/api/check-params/player-settings.ts@@ -11,8 +11,12 @@ import {describe('Test player settings API validator', function () {let server: PeerTubeServer+let ownerAccessToken: stringlet userAccessToken: string+ let editorAccessToken: string+ let invitedEditorAccessToken: string+let video: VideoCreateResultlet privateVideo: VideoCreateResult@@ -28,6 +32,8 @@ describe('Test player settings API validator', function () {ownerAccessToken = await server.users.generateUserAndToken('owner')userAccessToken = await server.users.generateUserAndToken('user1')+ editorAccessToken = await server.channelCollaborators.createEditor('accepted_editor', 'owner_channel')+ invitedEditorAccessToken = await server.channelCollaborators.createInvited('invited_editor', 'owner_channel')video = await server.videos.upload({ token: ownerAccessToken })privateVideo = await server.videos.upload({ token: ownerAccessToken, attributes: { privacy: VideoPrivacy.PRIVATE } })@@ -42,6 +48,8 @@ describe('Test player settings API validator', function () {await server.playerSettings.getForVideo({ token: server.accessToken, videoId })await server.playerSettings.getForVideo({ token: ownerAccessToken, videoId })+ await server.playerSettings.getForVideo({ token: editorAccessToken, videoId })+ await server.playerSettings.getForVideo({ token: invitedEditorAccessToken, videoId, expectedStatus: HttpStatusCode.FORBIDDEN_403 })await server.playerSettings.getForVideo({ token: userAccessToken, videoId, expectedStatus: HttpStatusCode.FORBIDDEN_403 })await server.playerSettings.getForVideo({ token: null, videoId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })})@@ -54,12 +62,20 @@ describe('Test player settings API validator', function () {})})- it('Should only allow to get raw player settings of a channel by owner/moderators', async function () {+ it('Should only allow to get raw player settings of a channel by owner/editors/moderators', async function () {const channelHandle = 'owner_channel'const videoId = video.uuidawait server.playerSettings.getForChannel({ token: server.accessToken, channelHandle, raw: true })await server.playerSettings.getForChannel({ token: ownerAccessToken, channelHandle, raw: true })+ await server.playerSettings.getForChannel({ token: editorAccessToken, channelHandle, raw: true })++ await server.playerSettings.getForChannel({+ token: invitedEditorAccessToken,+ channelHandle,+ expectedStatus: HttpStatusCode.FORBIDDEN_403,+ raw: true+ })await server.playerSettings.getForChannel({token: userAccessToken,channelHandle,@@ -79,8 +95,16 @@ describe('Test player settings API validator', function () {const playerSettings: PlayerVideoSettings = { theme: 'lucide' }await server.playerSettings.updateForVideo({ token: server.accessToken, videoId, ...playerSettings })+ await server.playerSettings.updateForVideo({ token: editorAccessToken, videoId, ...playerSettings })await server.playerSettings.updateForVideo({ token: ownerAccessToken, videoId, ...playerSettings })+ await server.playerSettings.updateForVideo({+ token: invitedEditorAccessToken,+ videoId,+ ...playerSettings,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+await server.playerSettings.updateForVideo({token: userAccessToken,videoId,@@ -97,6 +121,14 @@ describe('Test player settings API validator', function () {await server.playerSettings.updateForChannel({ token: server.accessToken, channelHandle, ...playerSettings })await server.playerSettings.updateForChannel({ token: ownerAccessToken, channelHandle, ...playerSettings })+ await server.playerSettings.updateForChannel({ token: editorAccessToken, channelHandle, ...playerSettings })++ await server.playerSettings.updateForChannel({+ token: invitedEditorAccessToken,+ channelHandle,+ ...playerSettings,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })await server.playerSettings.updateForChannel({token: userAccessToken,diff --git a/packages/tests/src/api/check-params/upload-quota.ts b/packages/tests/src/api/check-params/upload-quota.tsindex 9a540f6ebd..908ba84a65 100644--- a/packages/tests/src/api/check-params/upload-quota.ts+++ b/packages/tests/src/api/check-params/upload-quota.ts@@ -37,7 +37,6 @@ describe('Test upload quota', function () {})describe('When having a video quota', function () {-it('Should fail with a registered user having too many videos with legacy upload', async function () {this.timeout(120000)@@ -81,7 +80,7 @@ describe('Test upload quota', function () {await waitJobs([ server ])- const { total, data: videoImports } = await server.videoImports.getMyVideoImports()+ const { total, data: videoImports } = await server.videoImports.listMyVideoImports()expect(total).to.equal(3)expect(videoImports).to.have.lengthOf(3)@@ -95,7 +94,6 @@ describe('Test upload quota', function () {})describe('When having a daily video quota', function () {-it('Should fail with a user having too many videos daily', async function () {await server.users.update({ userId: rootId, videoQuotaDaily: 42 })diff --git a/packages/tests/src/api/check-params/my-user.ts b/packages/tests/src/api/check-params/user-me.tssimilarity index 100%rename from packages/tests/src/api/check-params/my-user.tsrename to packages/tests/src/api/check-params/user-me.tsdiff --git a/packages/tests/src/api/check-params/video-blacklist.ts b/packages/tests/src/api/check-params/video-blacklist.tsindex e5006574e3..e52561d874 100644--- a/packages/tests/src/api/check-params/video-blacklist.ts+++ b/packages/tests/src/api/check-params/video-blacklist.ts@@ -1,7 +1,5 @@/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { expect } from 'chai'-import { checkBadCountPagination, checkBadSortPagination, checkBadStartPagination } from '@tests/shared/checks.js'import { HttpStatusCode, VideoBlacklistType } from '@peertube/peertube-models'import {BlacklistCommand,@@ -14,13 +12,19 @@ import {setAccessTokensToServers,waitJobs} from '@peertube/peertube-server-commands'+import { checkBadCountPagination, checkBadSortPagination, checkBadStartPagination } from '@tests/shared/checks.js'+import { expect } from 'chai'describe('Test video blacklist API validators', function () {let servers: PeerTubeServer[]+let notBlacklistedVideoId: stringlet remoteVideoUUID: string- let userAccessToken1 = ''- let userAccessToken2 = ''++ let userToken: string+ let anotherUserToken: string+ let userEditorToken: string+let command: BlacklistCommand// ---------------------------------------------------------------@@ -33,23 +37,11 @@ describe('Test video blacklist API validators', function () {await setAccessTokensToServers(servers)await doubleFollow(servers[0], servers[1])- {- const username = 'user1'- const password = 'my super password'- await servers[0].users.create({ username, password })- userAccessToken1 = await servers[0].login.getAccessToken({ username, password })- }-- {- const username = 'user2'- const password = 'my super password'- await servers[0].users.create({ username, password })- userAccessToken2 = await servers[0].login.getAccessToken({ username, password })- }+ userToken = await servers[0].users.generateUserAndToken('user')+ anotherUserToken = await servers[0].users.generateUserAndToken('another_user')+ userEditorToken = await servers[0].channelCollaborators.createEditor('user_editor', 'user_channel')- {- servers[0].store.videoCreated = await servers[0].videos.upload({ token: userAccessToken1 })- }+ servers[0].store.videoCreated = await servers[0].videos.upload({ token: userToken }){const { uuid } = await servers[0].videos.upload()@@ -93,7 +85,7 @@ describe('Test video blacklist API validators', function () {await makePostBodyRequest({url: servers[0].url,path,- token: userAccessToken2,+ token: anotherUserToken,fields,expectedStatus: HttpStatusCode.FORBIDDEN_403})@@ -166,7 +158,7 @@ describe('Test video blacklist API validators', function () {await makePutBodyRequest({url: servers[0].url,path,- token: userAccessToken2,+ token: anotherUserToken,fields,expectedStatus: HttpStatusCode.FORBIDDEN_403})@@ -194,22 +186,23 @@ describe('Test video blacklist API validators', function () {})describe('When getting blacklisted video', function () {-it('Should fail with a non authenticated user', async function () {await servers[0].videos.get({ id: servers[0].store.videoCreated.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })})it('Should fail with another user', async function () {await servers[0].videos.getWithToken({- token: userAccessToken2,+ token: anotherUserToken,id: servers[0].store.videoCreated.uuid,expectedStatus: HttpStatusCode.FORBIDDEN_403})})- it('Should succeed with the owner authenticated user', async function () {- const video = await servers[0].videos.getWithToken({ token: userAccessToken1, id: servers[0].store.videoCreated.uuid })- expect(video.blacklisted).to.be.true+ it('Should succeed with the owner or an editor', async function () {+ for (const token of [ userToken, userEditorToken ]) {+ const video = await servers[0].videos.getWithToken({ token, id: servers[0].store.videoCreated.uuid })+ expect(video.blacklisted).to.be.true+ }})it('Should succeed with an admin', async function () {@@ -223,7 +216,6 @@ describe('Test video blacklist API validators', function () {})describe('When removing a video in blacklist', function () {-it('Should fail with a non authenticated user', async function () {await command.remove({token: 'faketoken',@@ -234,7 +226,7 @@ describe('Test video blacklist API validators', function () {it('Should fail with a non admin user', async function () {await command.remove({- token: userAccessToken2,+ token: anotherUserToken,videoId: servers[0].store.videoCreated.uuid,expectedStatus: HttpStatusCode.FORBIDDEN_403})@@ -262,7 +254,7 @@ describe('Test video blacklist API validators', function () {})it('Should fail with a non admin user', async function () {- await servers[0].blacklist.list({ token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await servers[0].blacklist.list({ token: anotherUserToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})it('Should fail with a bad start pagination', async function () {diff --git a/packages/tests/src/api/check-params/video-captions.ts b/packages/tests/src/api/check-params/video-captions.tsindex 18aeb0b7b5..945c74469f 100644--- a/packages/tests/src/api/check-params/video-captions.ts+++ b/packages/tests/src/api/check-params/video-captions.ts@@ -17,6 +17,7 @@ describe('Test video captions API validator', function () {let server: PeerTubeServerlet userAccessToken: string+ let editorToken: stringlet video: VideoCreateResultlet privateVideo: VideoCreateResult@@ -32,6 +33,7 @@ describe('Test video captions API validator', function () {video = await server.videos.upload()privateVideo = await server.videos.upload({ attributes: { privacy: VideoPrivacy.PRIVATE } })userAccessToken = await server.users.generateUserAndToken('user1')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')})describe('When adding video caption', function () {@@ -185,15 +187,18 @@ describe('Test video captions API validator', function () {it('Should succeed with the correct parameters', async function () {const captionPath = path + video.uuid + '/captions/fr'- await makeUploadRequest({- method: 'PUT',- url: server.url,- path: captionPath,- token: server.accessToken,- fields,- attaches,- expectedStatus: HttpStatusCode.NO_CONTENT_204- })++ for (const token of [ server.accessToken, editorToken ]) {+ await makeUploadRequest({+ method: 'PUT',+ url: server.url,+ path: captionPath,+ token,+ fields,+ attaches,+ expectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }})})@@ -228,14 +233,20 @@ describe('Test video captions API validator', function () {})it('Should succeed with the correct parameters', async function () {- await makeGetRequest({ url: server.url, path: path + video.shortUUID + '/captions', expectedStatus: HttpStatusCode.OK_200 })-await makeGetRequest({url: server.url,- path: path + privateVideo.shortUUID + '/captions',- token: server.accessToken,+ path: path + video.shortUUID + '/captions',expectedStatus: HttpStatusCode.OK_200})++ for (const token of [ server.accessToken, editorToken ]) {+ await makeGetRequest({+ url: server.url,+ path: path + privateVideo.shortUUID + '/captions',+ token,+ expectedStatus: HttpStatusCode.OK_200+ })+ }})})@@ -296,13 +307,18 @@ describe('Test video captions API validator', function () {})it('Should succeed with the correct parameters', async function () {- const captionPath = path + video.shortUUID + '/captions/fr'- await makeDeleteRequest({- url: server.url,- path: captionPath,- token: server.accessToken,- expectedStatus: HttpStatusCode.NO_CONTENT_204- })+ for (const token of [ server.accessToken, editorToken ]) {+ const captionPath = path + video.shortUUID + '/captions/fr'++ await makeDeleteRequest({+ url: server.url,+ path: captionPath,+ token,+ expectedStatus: HttpStatusCode.NO_CONTENT_204+ })++ await server.captions.add({ language: 'fr', videoId: video.uuid, fixture: 'subtitle-good1.vtt' })+ }})})diff --git a/packages/tests/src/api/check-params/video-change-ownership.ts b/packages/tests/src/api/check-params/video-change-ownership.tsnew file mode 100644index 0000000000..34466ff2cb--- /dev/null+++ b/packages/tests/src/api/check-params/video-change-ownership.ts@@ -0,0 +1,209 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { HttpStatusCode, VideoCreateResult } from '@peertube/peertube-models'+import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@peertube/peertube-server-commands'++describe('Test video change ownership API validator', function () {+ let server: PeerTubeServer+ let userToken: string+ let anotherUserToken: string+ let rootEditorToken: string+ let userEditorToken: string+ let ownershipChangeId: number++ let userVideo: VideoCreateResult+ let rootVideo: VideoCreateResult++ // ---------------------------------------------------------------++ before(async function () {+ this.timeout(120000)++ server = await createSingleServer(1)++ await setAccessTokensToServers([ server ])++ userToken = await server.users.generateUserAndToken('user')+ anotherUserToken = await server.users.generateUserAndToken('another_user')+ rootEditorToken = await server.channelCollaborators.createEditor('root_editor', 'root_channel')+ userEditorToken = await server.channelCollaborators.createEditor('user_editor', 'user_channel')++ rootVideo = await server.videos.quickUpload({ name: 'root video' })+ userVideo = await server.videos.quickUpload({ name: 'user video', token: userToken })+ })++ describe('Create video ownership change request', function () {+ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.create({+ videoId: userVideo.id,+ username: 'another_user',+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a video of another user', async function () {+ for (const token of [ userToken, rootEditorToken ]) {+ await server.changeOwnership.create({+ videoId: rootVideo.id,+ username: 'another_user',+ token,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ }+ })++ it('Should fail with a non existing target', async function () {+ await server.changeOwnership.create({+ videoId: userVideo.id,+ username: 'unexisting',+ token: userToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail with a non existing video', async function () {+ await server.changeOwnership.create({+ videoId: 42,+ username: 'another_user',+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should succeed with valid params', async function () {+ await server.changeOwnership.create({ videoId: rootVideo.id, username: 'user' })+ })+ })++ describe('List ownership change requests', function () {+ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.list({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })+ })++ it('Should succeed with valid params', async function () {+ const { data } = await server.changeOwnership.list({ token: userToken })+ ownershipChangeId = data[0].id+ })+ })++ describe('Reject ownership change request', function () {+ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.refuse({+ ownershipId: ownershipChangeId,+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a non existing ownership id', async function () {+ await server.changeOwnership.refuse({ ownershipId: 42, 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.refuse({+ ownershipId: ownershipChangeId,+ token,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ }+ })++ it('Should succeed with valid params', async function () {+ await server.changeOwnership.refuse({ ownershipId: ownershipChangeId, token: userToken })+ })++ it('Should fail to reject a non pending request', async function () {+ await server.changeOwnership.refuse({+ ownershipId: ownershipChangeId,+ token: userToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+ })++ describe('Accept ownership change request', function () {+ let targetChannelId: number++ before(async function () {+ await server.changeOwnership.create({ videoId: rootVideo.id, username: 'user' })++ const { data } = await server.changeOwnership.list({ token: userToken })+ ownershipChangeId = data[0].id++ const me = await server.users.getMyInfo({ token: userToken })+ targetChannelId = me.videoChannels[0].id+ })++ it('Should fail if not authenticated', async function () {+ await server.changeOwnership.accept({+ ownershipId: ownershipChangeId,+ token: null,+ channelId: targetChannelId,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a non existing ownership id', async function () {+ await server.changeOwnership.accept({+ ownershipId: 42,+ token: userToken,+ channelId: targetChannelId,+ 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.accept({+ ownershipId: ownershipChangeId,+ token,+ channelId: targetChannelId,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ }+ })++ it('Should fail with a non existing target', async function () {+ await server.changeOwnership.accept({+ ownershipId: 42,+ token: userToken,+ channelId: targetChannelId,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with a target channel not owned by the user', async function () {+ const me = await server.users.getMyInfo({ token: anotherUserToken })+ const anotherUserChannelId = me.videoChannels[0].id++ await server.changeOwnership.accept({+ ownershipId: ownershipChangeId,+ token: userToken,+ channelId: anotherUserChannelId,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should succeed with valid params', async function () {+ await server.changeOwnership.accept({+ ownershipId: ownershipChangeId,+ token: userToken,+ channelId: targetChannelId+ })+ })++ it('Should fail to accept a non pending request', async function () {+ await server.changeOwnership.accept({+ ownershipId: ownershipChangeId,+ token: userToken,+ channelId: targetChannelId,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })+ })++ after(async function () {+ await cleanupTests([ server ])+ })+})diff --git a/packages/tests/src/api/check-params/video-chapters.ts b/packages/tests/src/api/check-params/video-chapters.tsindex 481b6d1a0e..e8e10796be 100644--- a/packages/tests/src/api/check-params/video-chapters.ts+++ b/packages/tests/src/api/check-params/video-chapters.ts@@ -15,6 +15,7 @@ describe('Test videos chapters API validator', function () {let live: Videolet privateVideo: VideoCreateResultlet userAccessToken: string+ let editorToken: string// ---------------------------------------------------------------@@ -29,6 +30,7 @@ describe('Test videos chapters API validator', function () {video = await server.videos.upload()privateVideo = await server.videos.upload({ attributes: { privacy: VideoPrivacy.PRIVATE } })userAccessToken = await server.users.generateUserAndToken('user1')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')await server.config.enableLive({ allowReplay: false })@@ -37,7 +39,6 @@ describe('Test videos chapters API validator', function () {})describe('When updating chapters', function () {-it('Should fail without a valid uuid', async function () {await server.chapters.update({ videoId: '4da6fd', chapters: [], expectedStatus: HttpStatusCode.BAD_REQUEST_400 })})@@ -135,15 +136,17 @@ describe('Test videos chapters API validator', function () {chapters: []})- await server.chapters.update({- videoId: video.id,- chapters: [ { title: 'hello', timecode: 21 }, { title: 'hello 2', timecode: 35 } ]- })+ for (const token of [ server.accessToken, editorToken ]) {+ await server.chapters.update({+ videoId: video.id,+ token,+ chapters: [ { title: 'hello', timecode: 21 }, { title: 'hello 2', timecode: 35 } ]+ })+ }})})describe('When listing chapters', function () {-it('Should fail without a valid uuid', async function () {await server.chapters.list({ videoId: '4da6fd', expectedStatus: HttpStatusCode.BAD_REQUEST_400 })})@@ -161,8 +164,10 @@ describe('Test videos chapters API validator', function () {})it('Should list chapters', async function () {- await server.chapters.list({ videoId: privateVideo.uuid })- await server.chapters.list({ videoId: video.uuid })+ for (const token of [ server.accessToken, editorToken ]) {+ await server.chapters.list({ videoId: privateVideo.uuid, token })+ await server.chapters.list({ videoId: video.uuid, token })+ }})})diff --git a/packages/tests/src/api/check-params/video-comments.ts b/packages/tests/src/api/check-params/video-comments.tsindex 81da2b4751..99c54ed6fa 100644--- a/packages/tests/src/api/check-params/video-comments.ts+++ b/packages/tests/src/api/check-params/video-comments.ts@@ -24,6 +24,7 @@ describe('Test video comments API validator', function () {let userAccessToken: stringlet userAccessToken2: string+ let editorToken: stringlet commentId: numberlet privateCommentId: number@@ -70,6 +71,8 @@ describe('Test video comments API validator', function () {await server.users.create({ username: user.username, password: user.password })userAccessToken2 = await server.login.getAccessToken(user)}++ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')})describe('When listing video comment threads', function () {@@ -111,12 +114,14 @@ describe('Test video comments API validator', function () {})it('Should succeed with the correct params', async function () {- await makeGetRequest({- url: server.url,- token: server.accessToken,- path: '/api/v1/videos/' + privateVideo.shortUUID + '/comment-threads',- expectedStatus: HttpStatusCode.OK_200- })+ for (const token of [ server.accessToken, editorToken ]) {+ await makeGetRequest({+ url: server.url,+ token,+ path: '/api/v1/videos/' + privateVideo.shortUUID + '/comment-threads',+ expectedStatus: HttpStatusCode.OK_200+ })+ }})})@@ -155,12 +160,14 @@ describe('Test video comments API validator', function () {})it('Should succeed with the correct params', async function () {- await makeGetRequest({- url: server.url,- token: server.accessToken,- path: '/api/v1/videos/' + privateVideo.shortUUID + '/comment-threads/' + privateCommentId,- expectedStatus: HttpStatusCode.OK_200- })+ for (const token of [ server.accessToken, editorToken ]) {+ await makeGetRequest({+ url: server.url,+ token,+ path: '/api/v1/videos/' + privateVideo.shortUUID + '/comment-threads/' + privateCommentId,+ expectedStatus: HttpStatusCode.OK_200+ })+ }await makeGetRequest({url: server.url,@@ -231,6 +238,16 @@ describe('Test video comments API validator', function () {it('Should succeed with the correct parameters', async function () {const fields = { text: 'super comment' }+ for (const token of [ server.accessToken, editorToken ]) {+ await makePostBodyRequest({+ url: server.url,+ path: '/api/v1/videos/' + privateVideo.shortUUID + '/comment-threads',+ token,+ fields,+ expectedStatus: HttpStatusCode.OK_200+ })+ }+await makePostBodyRequest({url: server.url,path: pathThread,@@ -315,9 +332,18 @@ describe('Test video comments API validator', function () {})it('Should succeed with the correct parameters', async function () {- const fields = {- text: 'super comment'+ const fields = { text: 'super comment' }++ for (const token of [ server.accessToken, editorToken ]) {+ await makePostBodyRequest({+ url: server.url,+ path: '/api/v1/videos/' + privateVideo.uuid + '/comments/' + privateCommentId,+ token,+ fields,+ expectedStatus: HttpStatusCode.OK_200+ })}+await makePostBodyRequest({url: server.url,path: pathComment,@@ -353,21 +379,14 @@ describe('Test video comments API validator', function () {})it('Should succeed with the same user', async function () {- let commentToDelete: number-- {- const created = await server.comments.createThread({ videoId: video.uuid, token: userAccessToken, text: 'hello' })- commentToDelete = created.id- }-- const path = '/api/v1/videos/' + video.uuid + '/comments/' + commentToDelete+ const created = await server.comments.createThread({ videoId: video.uuid, token: userAccessToken, text: 'hello' })+ const path = '/api/v1/videos/' + video.uuid + '/comments/' + created.idawait makeDeleteRequest({ url: server.url, path, token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 })await makeDeleteRequest({ url: server.url, path, token: userAccessToken, expectedStatus: HttpStatusCode.NO_CONTENT_204 })})it('Should succeed with the owner of the video', async function () {- let commentToDelete: numberlet anotherVideoUUID: string{@@ -375,17 +394,18 @@ describe('Test video comments API validator', function () {anotherVideoUUID = uuid}- {- const created = await server.comments.createThread({ videoId: anotherVideoUUID, text: 'hello' })- commentToDelete = created.id- }-- const path = '/api/v1/videos/' + anotherVideoUUID + '/comments/' + commentToDelete+ const created = await server.comments.createThread({ videoId: anotherVideoUUID, text: 'hello' })+ const path = '/api/v1/videos/' + anotherVideoUUID + '/comments/' + created.idawait makeDeleteRequest({ url: server.url, path, token: userAccessToken2, expectedStatus: HttpStatusCode.FORBIDDEN_403 })await makeDeleteRequest({ url: server.url, path, token: userAccessToken, expectedStatus: HttpStatusCode.NO_CONTENT_204 })})+ it('Should succeed with the editor of the video', async function () {+ const created = await server.comments.createThread({ videoId: video.uuid, text: 'hello' })+ await server.comments.delete({ commentId: created.id, videoId: video.uuid, token: editorToken })+ })+it('Should succeed with the correct parameters', async function () {await makeDeleteRequest({url: server.url,@@ -492,6 +512,7 @@ describe('Test video comments API validator', function () {await server.comments.listForAdmin({ ...base, isLocal: false })await server.comments.listCommentsOnMyVideos(base)+ await server.comments.listCommentsOnMyVideos({ ...base, token: editorToken })})})@@ -562,6 +583,13 @@ describe('Test video comments API validator', function () {await server.comments.approve({ token: userAccessToken, commentId, videoId })})+ it('Should succeed with the editor token', async function () {+ const created = await server.comments.createThread({ text: 'thread for editor', videoId, token: userAccessToken2 })++ const editor2Token = await server.channelCollaborators.createEditor('editor2', 'user1_channel')+ await server.comments.approve({ token: editor2Token, commentId: created.id, videoId })+ })+it('Should fail with an already held for review comment', async function () {await server.comments.approve({ token: userAccessToken, commentId, videoId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })})diff --git a/packages/tests/src/api/check-params/video-files.ts b/packages/tests/src/api/check-params/video-files.tsindex a53016509f..5f4ff98835 100644--- a/packages/tests/src/api/check-params/video-files.ts+++ b/packages/tests/src/api/check-params/video-files.ts@@ -17,6 +17,7 @@ describe('Test videos files API validators', function () {let userToken: stringlet moderatorToken: string+ let editorToken: string// ---------------------------------------------------------------@@ -30,6 +31,7 @@ describe('Test videos files API validators', function () {userToken = await servers[0].users.generateUserAndToken('user', UserRole.USER)moderatorToken = await servers[0].users.generateUserAndToken('moderator', UserRole.MODERATOR)+ editorToken = await servers[0].channelCollaborators.createEditor('editor', 'root_channel')})describe('Getting metadata', function () {@@ -54,7 +56,9 @@ describe('Test videos files API validators', function () {it('Should get metadata of private video with the appropriate token', async function () {for (const file of getAllFiles(video)) {- await makeRawRequest({ url: file.metadataUrl, token: servers[0].accessToken, expectedStatus: HttpStatusCode.OK_200 })+ for (const token of [ servers[0].accessToken, editorToken ]) {+ await makeRawRequest({ url: file.metadataUrl, token, expectedStatus: HttpStatusCode.OK_200 })+ }}})})diff --git a/packages/tests/src/api/check-params/video-imports.ts b/packages/tests/src/api/check-params/video-imports.tsindex 0e33d85cbb..4981907ac7 100644--- a/packages/tests/src/api/check-params/video-imports.ts+++ b/packages/tests/src/api/check-params/video-imports.ts@@ -20,7 +20,8 @@ import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'describe('Test video imports API validator', function () {const path = '/api/v1/videos/imports'let server: PeerTubeServer- let userAccessToken = ''+ let userAccessToken: string+ let editorToken: stringlet channelId: number// ---------------------------------------------------------------@@ -38,6 +39,8 @@ describe('Test video imports API validator', function () {await server.users.create({ username, password })userAccessToken = await server.login.getAccessToken({ username, password })+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')+{const { videoChannels } = await server.users.getMyInfo()channelId = videoChannels[0].id@@ -229,7 +232,7 @@ describe('Test video imports API validator', function () {it('Should fail with a bad channel', async function () {const fields = { ...baseCorrectParams, channelId: 545454 }- await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields })+ await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, expectedStatus: HttpStatusCode.NOT_FOUND_404 })})it('Should fail with another user channel', async function () {@@ -245,7 +248,7 @@ describe('Test video imports API validator', function () {const fields = { ...baseCorrectParams, channelId: customChannelId }- await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields })+ await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})it('Should fail with too many tags', async function () {@@ -321,13 +324,15 @@ describe('Test video imports API validator', function () {it('Should succeed with the correct parameters', async function () {this.timeout(120000)- await makePostBodyRequest({- url: server.url,- path,- token: server.accessToken,- fields: baseCorrectParams,- expectedStatus: HttpStatusCode.OK_200- })+ for (const token of [ editorToken, server.accessToken ]) {+ await makePostBodyRequest({+ url: server.url,+ path,+ token,+ fields: baseCorrectParams,+ expectedStatus: HttpStatusCode.OK_200+ })+ }await makePostBodyRequest({url: server.url,@@ -454,10 +459,6 @@ describe('Test video imports API validator', function () {await server.videoImports.cancel({ importId, expectedStatus: HttpStatusCode.CONFLICT_409 })})- it('Should succeed to delete an import', async function () {- await server.videoImports.delete({ importId })- })-it('Should fail to delete a pending import', async function () {await server.jobs.pauseJobQueue()@@ -466,10 +467,27 @@ describe('Test video imports API validator', function () {await server.videoImports.delete({ importId, expectedStatus: HttpStatusCode.CONFLICT_409 })})- it('Should succeed to cancel an import', async function () {+ it('Should succeed to cancel and delete an import', async function () {+ for (const token of [ editorToken, server.accessToken ]) {+ importId = await importVideo()++ await server.videoImports.cancel({ importId, token })+ await server.videoImports.delete({ importId, token })+ }+ })++ it('Should not allow a editor to delete an import without a video', async function () {+ await server.videoImports.cancelAll()+ await server.jobs.resumeJobQueue()+importId = await importVideo()+ await waitJobs([ server ], { skipFailed: true })++ const videoId = await server.videoImports.getVideoId({ importId })+ await server.videos.remove({ id: videoId })- await server.videoImports.cancel({ importId })+ await server.videoImports.delete({ importId, token: editorToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await server.videoImports.delete({ importId, token: server.accessToken })})})diff --git a/packages/tests/src/api/check-params/video-passwords.ts b/packages/tests/src/api/check-params/video-passwords.tsindex d9829e0e11..658c4d4a50 100644--- a/packages/tests/src/api/check-params/video-passwords.ts+++ b/packages/tests/src/api/check-params/video-passwords.ts@@ -23,7 +23,8 @@ import { expect } from 'chai'describe('Test video passwords validator', function () {let path: stringlet server: PeerTubeServer- let userAccessToken = ''+ let userAccessToken: string+ let editorToken: stringlet video: VideoCreateResultlet channelId: numberlet publicVideo: VideoCreateResult@@ -70,6 +71,9 @@ describe('Test video passwords validator', function () {videoPasswords: [ 'password1', 'password2' ]})}++ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')+path = '/api/v1/videos/'})@@ -232,7 +236,9 @@ describe('Test video passwords validator', function () {? HttpStatusCode.NO_CONTENT_204: HttpStatusCode.OK_200- await checkVideoPasswordOptions({ server, token: server.accessToken, videoPasswords, expectedStatus, mode })+ for (const token of [ server.accessToken, editorToken ]) {+ await checkVideoPasswordOptions({ server, token, videoPasswords, expectedStatus, mode })+ }})}@@ -384,18 +390,23 @@ describe('Test video passwords validator', function () {? ServerErrorCode.VIDEO_REQUIRES_PASSWORD: ServerErrorCode.INCORRECT_VIDEO_PASSWORD- const message = mode === 'providePassword'- ? 'Please provide a password to access this password protected video'- : 'Incorrect video password. Access to the video is denied.'-if (!error.code) {error = JSON.parse(error.text)}expect(error.code).to.equal(serverCode)- expect(error.detail).to.equal(message)- expect(error.status).to.equal(HttpStatusCode.FORBIDDEN_403)+ if (mode === 'providePassword') {+ expect(error.detail).to.equal('Please provide a password to access this password protected video')+ } else {+ expect(error.detail).to.equal('Incorrect video password. Access to the video is denied')+ }++ try {+ expect(error.status).to.equal(HttpStatusCode.FORBIDDEN_403)+ } catch {+ expect(error.status).to.equal(HttpStatusCode.UNAUTHORIZED_401)+ }}function validateVideoAccess (@@ -406,7 +417,7 @@ describe('Test video passwords validator', function () {if (!requiresUserAuth) {it('Should fail without providing a password for an unlogged user', async function () {- const body = await checkVideoAccessOptions({ server, expectedStatus: HttpStatusCode.FORBIDDEN_403, mode })+ const body = await checkVideoAccessOptions({ server, expectedStatus: HttpStatusCode.UNAUTHORIZED_401, mode })const error = body as unknown as PeerTubeProblemDocumentcheckVideoError(error, 'providePassword')@@ -465,7 +476,7 @@ describe('Test video passwords validator', function () {}})- it('Should fail if an inccorect password containing the correct password is entered', async function () {+ it('Should fail if an incorrect password containing the correct password is entered', async function () {const tmp = mode === 'get' ? 'getWithPassword' : modefor (const token of tokens) {@@ -482,13 +493,20 @@ describe('Test video passwords validator', function () {}})- it('Should succeed without providing a password for an authorised user', async function () {- const tmp = mode === 'get' ? 'getWithToken' : mode- const expectedStatus = mode === 'rate' ? HttpStatusCode.NO_CONTENT_204 : HttpStatusCode.OK_200+ it('Should succeed without providing a password for an authorized user', async function () {+ const tmp = mode === 'get'+ ? 'getWithToken'+ : mode++ const expectedStatus = mode === 'rate'+ ? HttpStatusCode.NO_CONTENT_204+ : HttpStatusCode.OK_200- const body = await checkVideoAccessOptions({ server, token: server.accessToken, expectedStatus, mode: tmp })+ for (const token of [ editorToken, server.accessToken ]) {+ const body = await checkVideoAccessOptions({ server, token, expectedStatus, mode: tmp })- if (mode === 'createThread') commentId = body.comment.id+ if (mode === 'createThread') commentId = body.comment.id+ }})it('Should succeed using correct passwords', async function () {@@ -566,11 +584,13 @@ describe('Test video passwords validator', function () {})it('Should succeed with the correct parameters', async function () {- await server.videoPasswords.list({- token: server.accessToken,- expectedStatus: HttpStatusCode.OK_200,- videoId: video.id- })+ for (const token of [ server.accessToken, editorToken ]) {+ await server.videoPasswords.list({+ token,+ expectedStatus: HttpStatusCode.OK_200,+ videoId: video.id+ })+ }})})@@ -614,11 +634,15 @@ describe('Test video passwords validator', function () {})it('Should succeed with correct parameter', async function () {- await server.videoPasswords.remove({ id: passwords[0].id, videoId: video.id, expectedStatus: HttpStatusCode.NO_CONTENT_204 })+ for (const token of [ server.accessToken, editorToken ]) {+ await server.videoPasswords.remove({ id: passwords[0].id, videoId: video.id, expectedStatus: HttpStatusCode.NO_CONTENT_204, token })++ passwords.shift()+ }})it('Should fail for last password of a video', async function () {- await server.videoPasswords.remove({ id: passwords[1].id, videoId: video.id, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })+ await server.videoPasswords.remove({ id: passwords[0].id, videoId: video.id, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })})})diff --git a/packages/tests/src/api/check-params/video-playlists.ts b/packages/tests/src/api/check-params/video-playlists.tsindex 46581bb597..1b2edecb32 100644--- a/packages/tests/src/api/check-params/video-playlists.ts+++ b/packages/tests/src/api/check-params/video-playlists.ts@@ -2,6 +2,7 @@import {HttpStatusCode,+ VideoChannelCreateResult,VideoPlaylistCreate,VideoPlaylistCreateResult,VideoPlaylistElementCreate,@@ -20,14 +21,18 @@ import {setDefaultVideoChannel} from '@peertube/peertube-server-commands'import { checkBadCountPagination, checkBadSortPagination, checkBadStartPagination } from '@tests/shared/checks.js'+import { expect } from 'chai'describe('Test video playlists API validator', function () {let server: PeerTubeServerlet userAccessToken: string+ let editorToken: stringlet playlist: VideoPlaylistCreateResultlet userPlaylist: VideoPlaylistCreateResultlet privatePlaylistUUID: string+ let anotherChannelPlaylistUUID: string+ let privateForEditorPlaylistUUID: stringlet watchLaterPlaylistId: numberlet videoId: number@@ -35,6 +40,8 @@ describe('Test video playlists API validator', function () {let command: PlaylistsCommand+ let anotherRootChannel: VideoChannelCreateResult+// ---------------------------------------------------------------before(async function () {@@ -45,9 +52,13 @@ describe('Test video playlists API validator', function () {await setAccessTokensToServers([ server ])await setDefaultVideoChannel([ server ])+ anotherRootChannel = await server.channels.create({ attributes: { name: 'another_root_channel' } })+userAccessToken = await server.users.generateUserAndToken('user1')const user = await server.users.getMyInfo({ token: userAccessToken })+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')+videoId = (await server.videos.quickUpload({ name: 'video 1' })).idcommand = server.playlists@@ -74,14 +85,14 @@ describe('Test video playlists API validator', function () {}{- userPlaylist = await command.create({- token: userAccessToken,+ const created = await command.create({attributes: {- displayName: 'user playlist',+ displayName: 'another channel playlist',privacy: VideoPlaylistPrivacy.PUBLIC,- videoChannelId: user.videoChannels[0].id+ videoChannelId: anotherRootChannel.id}})+ anotherChannelPlaylistUUID = created.uuid}{@@ -93,6 +104,28 @@ describe('Test video playlists API validator', function () {})privatePlaylistUUID = created.uuid}++ {+ const created = await command.create({+ attributes: {+ displayName: 'private for editor',+ videoChannelId: server.store.channel.id,+ privacy: VideoPlaylistPrivacy.PRIVATE+ }+ })+ privateForEditorPlaylistUUID = created.uuid+ }++ {+ userPlaylist = await command.create({+ token: userAccessToken,+ attributes: {+ displayName: 'user playlist',+ privacy: VideoPlaylistPrivacy.PUBLIC,+ videoChannelId: user.videoChannels[0].id+ }+ })+ }})describe('When listing playlists', function () {@@ -146,6 +179,17 @@ describe('Test video playlists API validator', function () {})})+ it('Should not list playlists of a channel of another user', async function () {+ const { total, data } = await server.playlists.listByAccount({+ handle: 'user1',+ token: userAccessToken,+ channelNameOneOf: [ 'root_channel' ]+ })++ expect(total).to.equal(0)+ expect(data).to.have.lengthOf(0)+ })+it('Should succeed with the correct parameters', async function () {await makeGetRequest({ url: server.url, path: globalPath, expectedStatus: HttpStatusCode.OK_200, token: server.accessToken })await makeGetRequest({ url: server.url, path: accountPath, expectedStatus: HttpStatusCode.OK_200, token: server.accessToken })@@ -197,7 +241,11 @@ describe('Test video playlists API validator', function () {})it('Should succeed with the correct params', async function () {- await command.get({ playlistId: playlist.uuid, expectedStatus: HttpStatusCode.OK_200 })+ for (const playlistId of [ playlist.uuid, privateForEditorPlaylistUUID ]) {+ for (const token of [ server.accessToken, editorToken ]) {+ await command.get({ playlistId, token, expectedStatus: HttpStatusCode.OK_200 })+ }+ }})})@@ -260,7 +308,7 @@ describe('Test video playlists API validator', function () {})it('Should fail with an unknown video channel id', async function () {- const params = getBase({ videoChannelId: 42 }, { expectedStatus: HttpStatusCode.BAD_REQUEST_400 })+ const params = getBase({ videoChannelId: 42 }, { expectedStatus: HttpStatusCode.NOT_FOUND_404 })await command.create(params)await command.update(getUpdate(params, playlist.shortUUID))@@ -306,11 +354,69 @@ describe('Test video playlists API validator', function () {))})+ it('Should fail for an editor to update a playlist of another channel', async function () {+ await command.update(getUpdate(+ getBase({}, { token: editorToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }),+ privatePlaylistUUID+ ))++ await command.update(getUpdate(+ getBase({}, { token: editorToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }),+ anotherChannelPlaylistUUID+ ))+ })+it('Should fail to set a playlist to a channel owned by another user', async function () {- const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })+ // User doesn't have the right on the root channel+ {+ const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await command.create(params)- await command.update(getUpdate(params, userPlaylist.shortUUID))+ await command.create(params)+ await command.update(getUpdate(params, userPlaylist.shortUUID))+ }++ // User has the right on the channel, but this new channel is not owned by the playlist owner+ {+ const playlists: VideoPlaylistCreateResult[] = []++ playlists.push(+ await server.playlists.create({+ attributes: {+ displayName: 'playlist editor',+ videoChannelId: server.store.channel.id,+ privacy: VideoPlaylistPrivacy.PUBLIC+ },+ token: editorToken+ })+ )++ playlists.push(+ await server.playlists.create({+ attributes: {+ displayName: 'playlist editor',+ privacy: VideoPlaylistPrivacy.PRIVATE+ }+ })+ )++ for (const playlist of playlists) {+ await server.playlists.update({+ playlistId: playlist.shortUUID,+ attributes: { videoChannelId: await server.channels.getDefaultId({ token: userAccessToken }) },+ token: server.accessToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ }+ }+ })++ it('Should fail to update with another channel if the editor does not have the right on the target channel', async function () {+ const params = getBase({ videoChannelId: anotherRootChannel.id }, {+ token: editorToken,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })++ await command.update(getUpdate(params, playlist.shortUUID))})it('Should fail to update the watch later playlist', async function () {@@ -321,14 +427,16 @@ describe('Test video playlists API validator', function () {})it('Should succeed with the correct params', async function () {- {- const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200 })- await command.create(params)- }+ for (const token of [ server.accessToken, editorToken ]) {+ {+ const params = getBase({}, { token, expectedStatus: HttpStatusCode.OK_200 })+ await command.create(params)+ }- {- const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 })- await command.update(getUpdate(params, playlist.shortUUID))+ {+ const params = getBase({}, { token, expectedStatus: HttpStatusCode.NO_CONTENT_204 })+ await command.update(getUpdate(params, playlist.shortUUID))+ }}})})@@ -364,6 +472,12 @@ describe('Test video playlists API validator', function () {await command.addElement(params)})+ it('Should fail for an editor to add elements to a private or another channel playlist', async function () {+ for (const playlistId of [ privatePlaylistUUID, anotherChannelPlaylistUUID ]) {+ await command.addElement(getBase({}, { playlistId, expectedStatus: HttpStatusCode.FORBIDDEN_403, token: editorToken }))+ }+ })+it('Should fail with an unknown or incorrect playlist id', async function () {{const params = getBase({}, { playlistId: 'toto' })@@ -394,9 +508,11 @@ describe('Test video playlists API validator', function () {})it('Succeed with the correct params', async function () {- const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200 })- const created = await command.addElement(params)- elementId = created.id+ for (const token of [ editorToken, server.accessToken ]) {+ const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200, token })+ const created = await command.addElement(params)+ elementId = created.id+ }})})@@ -431,6 +547,12 @@ describe('Test video playlists API validator', function () {await command.updateElement(params)})+ it('Should fail for an editor with elements of a private or another channel playlist', async function () {+ for (const playlistId of [ privatePlaylistUUID, anotherChannelPlaylistUUID ]) {+ await command.updateElement(getBase({}, { playlistId, expectedStatus: HttpStatusCode.FORBIDDEN_403, token: editorToken }))+ }+ })+it('Should fail with an unknown or incorrect playlist id', async function () {{const params = getBase({}, { playlistId: 'toto' })@@ -473,8 +595,10 @@ describe('Test video playlists API validator', function () {})it('Succeed with the correct params', async function () {- const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 })- await command.updateElement(params)+ for (const token of [ editorToken, server.accessToken ]) {+ const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204, token })+ await command.updateElement(params)+ }})})@@ -527,6 +651,20 @@ describe('Test video playlists API validator', function () {await command.reorderPlaylistsOfChannel(params)})+ it('Should fail for an editor to add elements to a private or another channel playlist', async function () {+ for (const playlistId of [ privatePlaylistUUID, anotherChannelPlaylistUUID ]) {+ const params = getBase({}, {+ playlistId,+ channelName: 'another_root_channel',+ expectedStatus: HttpStatusCode.FORBIDDEN_403,+ token: editorToken+ })++ await command.reorderElements(params)+ await command.reorderPlaylistsOfChannel(params)+ }+ })+it('Should fail with an invalid start position', async function () {{const params = getBase({ startPosition: -1 })@@ -588,9 +726,11 @@ describe('Test video playlists API validator', function () {})it('Succeed with the correct params', async function () {- const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 })- await command.reorderElements(params)- await command.reorderPlaylistsOfChannel(params)+ for (const token of [ editorToken, server.accessToken ]) {+ const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204, token })+ await command.reorderElements(params)+ await command.reorderPlaylistsOfChannel(params)+ }})})@@ -700,6 +840,12 @@ describe('Test video playlists API validator', function () {await command.removeElement(params)})+ it('Should fail for an editor with a private or another channel playlist', async function () {+ for (const playlistId of [ privatePlaylistUUID, anotherChannelPlaylistUUID ]) {+ await command.removeElement(getBase({ token: editorToken, playlistId, expectedStatus: HttpStatusCode.FORBIDDEN_403 }))+ }+ })+it('Should fail with an unknown or incorrect playlist id', async function () {{const params = getBase({ playlistId: 'toto' })@@ -743,6 +889,11 @@ describe('Test video playlists API validator', function () {it('Should fail with a playlist of another user', async function () {await command.delete({ token: userAccessToken, playlistId: playlist.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})+ it('Should fail for an editor with a private or another channel playlist', async function () {+ for (const playlistId of [ privatePlaylistUUID, anotherChannelPlaylistUUID ]) {+ await command.delete({ token: editorToken, playlistId, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ }+ })it('Should fail with the watch later playlist', async function () {await command.delete({ playlistId: watchLaterPlaylistId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })diff --git a/packages/tests/src/api/check-params/video-source.ts b/packages/tests/src/api/check-params/video-source.tsindex 4f25325e70..05401d0713 100644--- a/packages/tests/src/api/check-params/video-source.ts+++ b/packages/tests/src/api/check-params/video-source.ts@@ -11,8 +11,16 @@ import {describe('Test video sources API validator', function () {let server: PeerTubeServer = null- let uuid: string++ let videoId: string+ let userVideoId: string+let userToken: string+ let userId: number++ let editorToken: string+ let userEditorToken: string+ let anotherUserToken: stringbefore(async function () {this.timeout(120000)@@ -21,14 +29,20 @@ describe('Test video sources API validator', function () {await setAccessTokensToServers([ server ])await setDefaultVideoChannel([ server ])- userToken = await server.users.generateUserAndToken('user1')+ anotherUserToken = await server.users.generateUserAndToken('another_user')++ const res = await server.users.generate('user')+ userToken = res.token+ userId = res.userId++ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')+ userEditorToken = await server.channelCollaborators.createEditor('user_editor', 'user_channel')})describe('When getting latest source', function () {-before(async function () {const created = await server.videos.quickUpload({ name: 'video' })- uuid = created.uuid+ videoId = created.uuid})it('Should fail without a valid uuid', async function () {@@ -40,30 +54,22 @@ describe('Test video sources API validator', function () {})it('Should not get the source as unauthenticated', async function () {- await server.videos.getSource({ id: uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401, token: null })+ await server.videos.getSource({ id: videoId, expectedStatus: HttpStatusCode.UNAUTHORIZED_401, token: null })})it('Should not get the source with another user', async function () {- await server.videos.getSource({ id: uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403, token: userToken })+ await server.videos.getSource({ id: videoId, expectedStatus: HttpStatusCode.FORBIDDEN_403, token: userToken })})- it('Should succeed with the correct parameters get the source as another user', async function () {- await server.videos.getSource({ id: uuid })+ it('Should succeed with the correct parameters', async function () {+ for (const token of [ server.accessToken, editorToken ]) {+ await server.videos.getSource({ id: videoId, token })+ }})})describe('When updating source video file', function () {- let userAccessToken: string- let userId: number-- let videoId: string- let userVideoId: string-before(async function () {- const res = await server.users.generate('user2')- userAccessToken = res.token- userId = res.userId-const { uuid } = await server.videos.quickUpload({ name: 'video' })videoId = uuid@@ -104,7 +110,7 @@ describe('Test video sources API validator', function () {it('Should fail with another user', async function () {await server.videos.replaceSourceFile({- token: userAccessToken,+ token: userToken,videoId,fixture: 'video_short.mp4',expectedStatus: HttpStatusCode.FORBIDDEN_403@@ -128,61 +134,60 @@ describe('Test video sources API validator', function () {it('Should fail if quota is exceeded', async function () {this.timeout(60000)- const { uuid } = await server.videos.quickUpload({ name: 'user video' })+ const { uuid } = await server.videos.quickUpload({ name: 'user video', token: userToken })userVideoId = uuidawait waitJobs([ server ])await server.users.update({ userId, videoQuota: 1 })- await server.videos.replaceSourceFile({- token: userAccessToken,- videoId: uuid,- fixture: 'video_short.mp4',- expectedStatus: HttpStatusCode.FORBIDDEN_403- })++ for (const token of [ server.accessToken, userEditorToken, userToken ]) {+ await server.videos.replaceSourceFile({+ token,+ videoId: userVideoId,+ fixture: 'video_short.mp4',+ expectedStatus: HttpStatusCode.PAYLOAD_TOO_LARGE_413+ })+ }})it('Should succeed with the correct params', async function () {this.timeout(60000)await server.users.update({ userId, videoQuota: 1000 * 1000 * 1000 })- await server.videos.replaceSourceFile({ videoId: userVideoId, fixture: 'video_short.mp4' })++ for (const token of [ server.accessToken, userEditorToken, userToken ]) {+ await server.videos.replaceSourceFile({ token, videoId: userVideoId, fixture: 'video_short.mp4' })+ }})})describe('When downloading the source file', function () {- let videoFileToken: string- let videoId: stringlet source: VideoSource- let user3: string- let user4: stringbefore(async function () {this.timeout(60000)- user3 = await server.users.generateUserAndToken('user3')- user4 = await server.users.generateUserAndToken('user4')-await server.config.enableMinimumTranscoding({ hls: true, keepOriginal: true, webVideo: true })- const { uuid } = await server.videos.quickUpload({ name: 'video', token: user3 })-- videoId = uuid- videoFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid, token: user3 })+ const { uuid } = await server.videos.quickUpload({ name: 'video', token: userToken })+ userVideoId = uuidawait waitJobs([ server ])- source = await server.videos.getSource({ id: videoId, token: user3 })+ await server.config.disableTranscoding()++ source = await server.videos.getSource({ id: userVideoId, token: userToken })})it('Should fail with an invalid filename', async function () {await makeRawRequest({ url: server.url + '/download/original-video-files/hello.mp4', expectedStatus: HttpStatusCode.NOT_FOUND_404 })})- it('Should fail without header token or video file token', async function () {- await makeRawRequest({ url: source.fileDownloadUrl, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ it('Should fail without user token or video file token', async function () {+ await makeRawRequest({ url: source.fileDownloadUrl, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })})- it('Should fail with an invalid header token', async function () {+ it('Should fail with an invalid user token', async function () {await makeRawRequest({ url: source.fileDownloadUrl, token: 'toto', expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })})@@ -190,46 +195,42 @@ describe('Test video sources API validator', function () {await makeRawRequest({ url: source.fileDownloadUrl, query: { videoFileToken: 'toto' }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})- it('Should fail with header token of another user', async function () {- await makeRawRequest({ url: source.fileDownloadUrl, token: user4, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ it('Should fail with user token of another user', async function () {+ await makeRawRequest({ url: source.fileDownloadUrl, token: anotherUserToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})it('Should fail with video file token of another user', async function () {- const videoFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid, token: user4 })+ const anotherFileToken = await server.videoToken.getVideoFileToken({ videoId: userVideoId, token: anotherUserToken })- await makeRawRequest({ url: source.fileDownloadUrl, query: { videoFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({+ url: source.fileDownloadUrl,+ query: { videoFileToken: anotherFileToken },+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })})- it('Should succeed with a valid header token', async function () {- await makeRawRequest({ url: source.fileDownloadUrl, token: user3, expectedStatus: HttpStatusCode.OK_200 })+ it('Should succeed with a valid user token', async function () {+ for (const token of [ server.accessToken, userToken, userEditorToken ]) {+ await makeRawRequest({ url: source.fileDownloadUrl, token, expectedStatus: HttpStatusCode.OK_200 })+ }})it('Should succeed with a valid query token', async function () {- await makeRawRequest({ url: source.fileDownloadUrl, query: { videoFileToken }, expectedStatus: HttpStatusCode.OK_200 })+ for (const token of [ server.accessToken, userEditorToken, userToken ]) {+ const videoFileToken = await server.videoToken.getVideoFileToken({ videoId: userVideoId, token })++ await makeRawRequest({ url: source.fileDownloadUrl, query: { videoFileToken }, expectedStatus: HttpStatusCode.OK_200 })+ }})})describe('When deleting video source file', function () {- let userAccessToken: string-- let videoId: string-- before(async function () {- userAccessToken = await server.users.generateUserAndToken('user56')-- await server.config.enableMinimumTranscoding({ keepOriginal: true })- const { uuid } = await server.videos.quickUpload({ name: 'with source' })- videoId = uuid-- await waitJobs([ server ])- })-it('Should fail without token', async function () {- await server.videos.deleteSource({ id: videoId, token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })+ await server.videos.deleteSource({ id: userVideoId, token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })})it('Should fail with another user', async function () {- await server.videos.deleteSource({ id: videoId, token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await server.videos.deleteSource({ id: userVideoId, token: anotherUserToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})it('Should fail with an unknown video', async function () {@@ -237,7 +238,11 @@ describe('Test video sources API validator', function () {})it('Should succeed with the correct params', async function () {- await server.videos.deleteSource({ id: videoId })+ for (const token of [ userToken, server.accessToken, userEditorToken ]) {+ await server.videos.deleteSource({ id: userVideoId, token })++ await server.videos.replaceSourceFile({ token, videoId: userVideoId, fixture: 'video_short.mp4' })+ }})})diff --git a/packages/tests/src/api/check-params/video-storyboards.ts b/packages/tests/src/api/check-params/video-storyboards.tsindex f83b541d87..50e657a60a 100644--- a/packages/tests/src/api/check-params/video-storyboards.ts+++ b/packages/tests/src/api/check-params/video-storyboards.ts@@ -9,6 +9,9 @@ describe('Test video storyboards API validator', function () {let publicVideo: { uuid: string }let privateVideo: { uuid: string }+ let userToken: string+ let editorToken: string+// ---------------------------------------------------------------before(async function () {@@ -17,6 +20,9 @@ describe('Test video storyboards API validator', function () {server = await createSingleServer(1)await setAccessTokensToServers([ server ])+ userToken = await server.users.generateUserAndToken('user')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')+publicVideo = await server.videos.quickUpload({ name: 'public' })privateVideo = await server.videos.quickUpload({ name: 'private', privacy: VideoPrivacy.PRIVATE })})@@ -31,12 +37,17 @@ describe('Test video storyboards API validator', function () {it('Should not get the private storyboard without the appropriate token', async function () {await server.storyboard.list({ id: privateVideo.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401, token: null })+ await server.storyboard.list({ id: privateVideo.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403, token: userToken })+await server.storyboard.list({ id: publicVideo.uuid, expectedStatus: HttpStatusCode.OK_200, token: null })})it('Should succeed with the correct parameters', async function () {- await server.storyboard.list({ id: privateVideo.uuid })await server.storyboard.list({ id: publicVideo.uuid })++ for (const token of [ server.accessToken, editorToken ]) {+ await server.storyboard.list({ id: privateVideo.uuid, token })+ }})after(async function () {diff --git a/packages/tests/src/api/check-params/video-studio.ts b/packages/tests/src/api/check-params/video-studio.tsindex bc5f6998d1..0e1926b886 100644--- a/packages/tests/src/api/check-params/video-studio.ts+++ b/packages/tests/src/api/check-params/video-studio.ts@@ -13,7 +13,10 @@ import {describe('Test video studio API validator', function () {let server: PeerTubeServerlet command: VideoStudioCommand+let userAccessToken: string+ let editorToken: string+let videoUUID: string// ---------------------------------------------------------------@@ -25,6 +28,7 @@ describe('Test video studio API validator', function () {await setAccessTokensToServers([ server ])userAccessToken = await server.users.generateUserAndToken('user1')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')await server.config.enableMinimumTranscoding()@@ -37,9 +41,7 @@ describe('Test video studio API validator', function () {})describe('Task creation', function () {-describe('Config settings', function () {-it('Should fail if studio is disabled', async function () {await server.config.updateExistingConfig({newConfig: {@@ -85,7 +87,6 @@ describe('Test video studio API validator', function () {})describe('Common tasks', function () {-it('Should fail without token', async function () {await command.createEditionTasks({token: null,@@ -188,12 +189,13 @@ describe('Test video studio API validator', function () {})})- it('Should succeed with correct parameters', async function () {+ it('Should succeed with correct parameters and editor token', async function () {await server.jobs.pauseJobQueue()await command.createEditionTasks({videoId: videoUUID,tasks: VideoStudioCommand.getComplexTask(),+ token: editorToken,expectedStatus: HttpStatusCode.NO_CONTENT_204})})@@ -214,7 +216,6 @@ describe('Test video studio API validator', function () {})describe('Cut task', function () {-async function cut (start: number, end: number, expectedStatus: HttpStatusCodeType = HttpStatusCode.BAD_REQUEST_400) {await command.createEditionTasks({videoId: videoUUID,@@ -266,7 +267,6 @@ describe('Test video studio API validator', function () {})describe('Watermark task', function () {-async function addWatermark (file: string, expectedStatus: HttpStatusCodeType = HttpStatusCode.BAD_REQUEST_400) {await command.createEditionTasks({videoId: videoUUID,@@ -300,7 +300,6 @@ describe('Test video studio API validator', function () {})describe('Intro/Outro task', function () {-async function addIntroOutro (type: 'add-intro' | 'add-outro',file: string,@@ -333,7 +332,6 @@ describe('Test video studio API validator', function () {it('Should fail with a file that does not contain video stream', async function () {await addIntroOutro('add-intro', 'sample.ogg')await addIntroOutro('add-outro', 'sample.ogg')-})it('Should succeed with the correct params', async function () {diff --git a/packages/tests/src/api/check-params/video-token.ts b/packages/tests/src/api/check-params/video-token.tsindex 5f838102d3..a7ea5725a8 100644--- a/packages/tests/src/api/check-params/video-token.ts+++ b/packages/tests/src/api/check-params/video-token.ts@@ -5,9 +5,12 @@ import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServdescribe('Test video tokens', function () {let server: PeerTubeServer+let privateVideoId: stringlet passwordProtectedVideoId: string+let userToken: string+ let editorToken: stringconst videoPassword = 'password'@@ -22,6 +25,7 @@ describe('Test video tokens', function () {const { uuid } = await server.videos.quickUpload({ name: 'private video', privacy: VideoPrivacy.PRIVATE })privateVideoId = uuid}+{const { uuid } = await server.videos.quickUpload({name: 'password protected video',@@ -30,7 +34,9 @@ describe('Test video tokens', function () {})passwordProtectedVideoId = uuid}+userToken = await server.users.generateUserAndToken('user1')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')})it('Should not generate tokens on private video for unauthenticated user', async function () {@@ -55,7 +61,9 @@ describe('Test video tokens', function () {})it('Should generate token', async function () {- await server.videoToken.create({ videoId: privateVideoId })+ for (const token of [ server.accessToken, editorToken ]) {+ await server.videoToken.create({ videoId: privateVideoId, token })+ }})it('Should generate token on password protected video', async function () {diff --git a/packages/tests/src/api/check-params/video-transcription.ts b/packages/tests/src/api/check-params/video-transcription.tsindex fc28924a5e..e780c4fd86 100644--- a/packages/tests/src/api/check-params/video-transcription.ts+++ b/packages/tests/src/api/check-params/video-transcription.ts@@ -14,10 +14,12 @@ describe('Test video transcription API validator', function () {let servers: PeerTubeServer[]let userToken: string+ let editorToken: stringlet anotherUserToken: stringlet remoteId: stringlet validId: string+ let validId2: string// ---------------------------------------------------------------@@ -31,6 +33,7 @@ describe('Test video transcription API validator', function () {userToken = await servers[0].users.generateUserAndToken('user', UserRole.USER)anotherUserToken = await servers[0].users.generateUserAndToken('user2', UserRole.USER)+ editorToken = await servers[0].channelCollaborators.createEditor('editor', 'user_channel'){const { uuid } = await servers[1].videos.quickUpload({ name: 'remote video' })@@ -42,6 +45,11 @@ describe('Test video transcription API validator', function () {validId = uuid}+ {+ const { uuid } = await servers[0].videos.quickUpload({ name: 'both 2', token: userToken })+ validId2 = uuid+ }+await waitJobs(servers)await servers[0].config.enableTranscription()@@ -55,7 +63,7 @@ describe('Test video transcription API validator', function () {await servers[0].captions.runGenerate({ videoId: remoteId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })})- it('Should not run transcription by a owner/moderator user', async function () {+ it('Should not run transcription by a non owner/moderator user', async function () {await servers[0].captions.runGenerate({ videoId: validId, token: anotherUserToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })})@@ -81,6 +89,7 @@ describe('Test video transcription API validator', function () {it('Should succeed to run transcription', async function () {await servers[0].captions.runGenerate({ videoId: validId, token: userToken })+ await servers[0].captions.runGenerate({ videoId: validId2, token: editorToken })})it('Should fail to run transcription twice', async function () {diff --git a/packages/tests/src/api/check-params/videos.ts b/packages/tests/src/api/check-params/videos.tsindex 7e44c9d1db..23c7573d35 100644--- a/packages/tests/src/api/check-params/videos.ts+++ b/packages/tests/src/api/check-params/videos.ts@@ -7,7 +7,8 @@ import {PeerTubeProblemDocument,VideoCommentPolicy,VideoCreateResult,- VideoPrivacy+ VideoPrivacy,+ VideoUpdate} from '@peertube/peertube-models'import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'import {@@ -28,10 +29,17 @@ import { expect } from 'chai'describe('Test videos API validator', function () {const path = '/api/v1/videos/'let server: PeerTubeServer- let userAccessToken = ''++ let userAccessToken: string+ let editorToken: string+let accountName: stringlet channelId: numberlet channelName: string++ let channelId2: number+ let channelIdEditor: number+let video: VideoCreateResultlet privateVideo: VideoCreateResult@@ -46,12 +54,25 @@ describe('Test videos API validator', function () {await setDefaultVideoChannel([ server ])userAccessToken = await server.users.generateUserAndToken('user1')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel'){const body = await server.users.getMyInfo()channelId = body.videoChannels[0].idchannelName = body.videoChannels[0].nameaccountName = body.account.name + '@' + body.account.host++ const anotherChannel = await server.channels.create({+ attributes: {+ name: 'another_channel'+ }+ })++ channelId2 = anotherChannel.id+ }++ {+ channelIdEditor = await server.channels.getDefaultId({ token: editorToken })}{@@ -358,7 +379,11 @@ describe('Test videos API validator', function () {const fields = { ...baseCorrectParams, channelId: 545454 }const attaches = baseCorrectAttaches- await checkUploadVideoParam({ ...baseOptions(), attributes: { ...fields, ...attaches } })+ await checkUploadVideoParam({+ ...baseOptions(),+ attributes: { ...fields, ...attaches },+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })})it('Should fail with another user channel', async function () {@@ -378,7 +403,8 @@ describe('Test videos API validator', function () {await checkUploadVideoParam({...baseOptions(),token: userAccessToken,- attributes: { ...fields, ...attaches }+ attributes: { ...fields, ...attaches },+ expectedStatus: HttpStatusCode.FORBIDDEN_403})})@@ -558,6 +584,7 @@ describe('Test videos API validator', function () {await checkUploadVideoParam({...baseOptions(),+ token: editorToken,attributes: { ...fields, ...attaches, nsfw: true, nsfwFlags: NSFWFlag.EXPLICIT_SEX, nsfwSummary: 'toto' },expectedStatus: HttpStatusCode.OK_200})@@ -575,7 +602,7 @@ describe('Test videos API validator', function () {})describe('When updating a video', function () {- const baseCorrectParams = {+ const baseCorrectParams: VideoUpdate = {name: 'my super name',category: 5,licence: 2,@@ -680,7 +707,49 @@ describe('Test videos API validator', function () {it('Should fail with a bad channel', async function () {const fields = { ...baseCorrectParams, channelId: 545454 }- await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields })+ await makePutBodyRequest({+ url: server.url,+ path: path + video.shortUUID,+ token: server.accessToken,+ fields,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should fail with the channel of another user', async function () {+ const fields = { ...baseCorrectParams, channelId: channelIdEditor }++ for (const token of [ server.accessToken, editorToken ]) {+ await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token, fields })+ }+ })++ it('Should fail with another channel of the same user if the editor does not have the right on the target channel', async function () {+ const fields = { ...baseCorrectParams, channelId: channelId2 }++ await makePutBodyRequest({+ url: server.url,+ path: path + video.shortUUID,+ token: editorToken,+ fields,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with another channel of the same user if the editor does not have the right on the video', async function () {+ await server.videos.update({ id: video.id, attributes: { channelId: channelId2 } })++ const fields = { ...baseCorrectParams, channelId }++ await makePutBodyRequest({+ url: server.url,+ path: path + video.shortUUID,+ token: editorToken,+ fields,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })++ await server.videos.update({ id: video.id, attributes: { channelId } })})it('Should fail with too many tags', async function () {@@ -797,7 +866,7 @@ describe('Test videos API validator', function () {it('Should fail with a video of another server')- it('Shoud report the appropriate error', async function () {+ it('Should report the appropriate error', async function () {const fields = { ...baseCorrectParams, licence: 125 }const res = await makePutBodyRequest({ url: server.url, path: path + video.shortUUID, token: server.accessToken, fields })@@ -828,7 +897,7 @@ describe('Test videos API validator', function () {await makePutBodyRequest({url: server.url,path: path + video.shortUUID,- token: server.accessToken,+ token: editorToken,fields: {...fields,@@ -861,7 +930,11 @@ describe('Test videos API validator', function () {await server.videos.get({ id: '4da6fde3-88f7-4d16-b119-108df5630b06', expectedStatus: HttpStatusCode.NOT_FOUND_404 })})- it('Shoud report the appropriate error', async function () {+ it('SHould return 403 with a private video of another user', async function () {+ await server.videos.get({ id: privateVideo.uuid, token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ })++ it('Should report the appropriate error', async function () {const body = await server.videos.get({ id: 'hi', expectedStatus: HttpStatusCode.BAD_REQUEST_400 })const error = body as unknown as PeerTubeProblemDocument@@ -878,6 +951,7 @@ describe('Test videos API validator', function () {it('Should succeed with the correct parameters', async function () {await server.videos.get({ id: video.shortUUID })+ await server.videos.get({ id: privateVideo.uuid, token: editorToken })})})@@ -930,16 +1004,19 @@ describe('Test videos API validator', function () {})it('Should succeed with the correct parameters', async function () {- const fields = {- rating: 'like'+ const fields = { rating: 'like' }++ for (const id of [ videoId, privateVideo.shortUUID ]) {+ for (const token of [ server.accessToken, editorToken ]) {+ await makePutBodyRequest({+ url: server.url,+ path: path + id + '/rate',+ token,+ fields,+ expectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }}- await makePutBodyRequest({- url: server.url,- path: path + videoId + '/rate',- token: server.accessToken,- fields,- expectedStatus: HttpStatusCode.NO_CONTENT_204- })})})@@ -966,7 +1043,7 @@ describe('Test videos API validator', function () {it('Should fail with a video of another server')- it('Shoud report the appropriate error', async function () {+ it('Should report the appropriate error', async function () {const body = await server.videos.remove({ id: 'hello', expectedStatus: HttpStatusCode.BAD_REQUEST_400 })const error = body as PeerTubeProblemDocument@@ -982,7 +1059,11 @@ describe('Test videos API validator', function () {})it('Should succeed with the correct parameters', async function () {- await server.videos.remove({ id: video.uuid })+ for (const token of [ server.accessToken, editorToken ]) {+ await server.videos.remove({ id: video.uuid, token })++ video = await server.videos.quickUpload({ name: 'to delete' })+ }})})diff --git a/packages/tests/src/api/check-params/views.ts b/packages/tests/src/api/check-params/views-and-stats.tssimilarity index 91%rename from packages/tests/src/api/check-params/views.tsrename to packages/tests/src/api/check-params/views-and-stats.tsindex e6cffc7b3a..993477551b 100644--- a/packages/tests/src/api/check-params/views.ts+++ b/packages/tests/src/api/check-params/views-and-stats.ts@@ -15,7 +15,9 @@ describe('Test videos views API validators', function () {let liveVideoId: stringlet videoId: stringlet remoteVideoId: string+let userAccessToken: string+ let editorToken: stringbefore(async function () {this.timeout(240000)@@ -36,6 +38,7 @@ describe('Test videos views API validators', function () {}))userAccessToken = await servers[0].users.generateUserAndToken('user')+ editorToken = await servers[0].channelCollaborators.createEditor('editor', 'root_channel')await doubleFollow(servers[0], servers[1])})@@ -136,15 +139,18 @@ describe('Test videos views API validators', function () {})it('Should succeed with the correct parameters', async function () {- await testEndpoint({- videoId,- startDate: new Date().toISOString(),- endDate: new Date().toISOString()- })+ for (const token of [ editorToken, servers[0].accessToken ]) {+ await testEndpoint({+ videoId,+ token,+ startDate: new Date().toISOString(),+ endDate: new Date().toISOString()+ })+ }})})- describe('When getting timeserie stats', function () {+ describe('When getting timeseries stats', function () {it('Should fail with a remote video', async function () {await servers[0].videoStats.getTimeserieStats({videoId: remoteVideoId,@@ -224,7 +230,9 @@ describe('Test videos views API validators', function () {})it('Should succeed with the correct parameters', async function () {- await servers[0].videoStats.getTimeserieStats({ videoId, metric: 'viewers' })+ for (const token of [ editorToken, servers[0].accessToken ]) {+ await servers[0].videoStats.getTimeserieStats({ videoId, token, metric: 'viewers' })+ }})})@@ -257,7 +265,9 @@ describe('Test videos views API validators', function () {})it('Should succeed with the correct parameters', async function () {- await servers[0].videoStats.getRetentionStats({ videoId })+ for (const token of [ editorToken, servers[0].accessToken ]) {+ await servers[0].videoStats.getRetentionStats({ videoId, token })+ }})})diff --git a/packages/tests/src/api/notifications/admin-notifications.ts b/packages/tests/src/api/notifications/admin-notifications.tsindex b9d35b280a..71db9e2e4a 100644--- a/packages/tests/src/api/notifications/admin-notifications.ts+++ b/packages/tests/src/api/notifications/admin-notifications.ts@@ -1,13 +1,15 @@/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { expect } from 'chai'import { wait } from '@peertube/peertube-core-utils'import { PluginType, UserNotification, UserNotificationType } from '@peertube/peertube-models'import { cleanupTests, PeerTubeServer } from '@peertube/peertube-server-commands'import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'import { MockJoinPeerTubeVersions } from '@tests/shared/mock-servers/mock-joinpeertube-versions.js'-import { CheckerBaseParams, prepareNotificationsTest, checkNewPeerTubeVersion, checkNewPluginVersion } from '@tests/shared/notifications.js'+import { checkNewPeerTubeVersion, checkNewPluginVersion } from '@tests/shared/notifications/check-admin-notifications.js'+import { prepareNotificationsTest } from '@tests/shared/notifications/notifications-common.js'+import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'import { SQLCommand } from '@tests/shared/sql-command.js'+import { expect } from 'chai'describe('Test admin notifications', function () {let server: PeerTubeServerdiff --git a/packages/tests/src/api/notifications/caption-notifications.ts b/packages/tests/src/api/notifications/caption-notifications.tsindex 56c6f99d01..27449f8230 100644--- a/packages/tests/src/api/notifications/caption-notifications.ts+++ b/packages/tests/src/api/notifications/caption-notifications.ts@@ -3,7 +3,10 @@import { UserNotification } from '@peertube/peertube-models'import { PeerTubeServer, cleanupTests, waitJobs } from '@peertube/peertube-server-commands'import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'-import { CheckerBaseParams, checkMyVideoTranscriptionGenerated, prepareNotificationsTest } from '@tests/shared/notifications.js'+import { checkMyVideoTranscriptionGenerated } from '@tests/shared/notifications/check-video-notifications.js'+import { prepareNotificationsTest } from '@tests/shared/notifications/notifications-common.js'+import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'+import { join } from 'path'describe('Test caption notifications', function () {diff --git a/packages/tests/src/api/notifications/channel-collaborators-notification.ts b/packages/tests/src/api/notifications/channel-collaborators-notification.tsnew file mode 100644index 0000000000..3bdc2cc1ab--- /dev/null+++ b/packages/tests/src/api/notifications/channel-collaborators-notification.ts@@ -0,0 +1,157 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { UserNotification, UserNotificationType } from '@peertube/peertube-models'+import { cleanupTests, PeerTubeServer, waitJobs } from '@peertube/peertube-server-commands'+import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'+import {+ checkAcceptedToCollaborateToChannel,+ CheckChannelCollaboratorOptions,+ checkInvitedToCollaborateToChannel,+ checkRefusedToCollaborateToChannel+} from '@tests/shared/notifications/check-channel-notifications.js'+import { prepareNotificationsTest } from '@tests/shared/notifications/notifications-common.js'+import { expect } from 'chai'++type BaseParam = Omit<CheckChannelCollaboratorOptions, 'checkType'>++describe('Test channel collaborators notifications', function () {+ let server: PeerTubeServer++ let userNotifications: UserNotification[] = []+ let adminNotifications: UserNotification[] = []+ let emails: object[] = []++ let baseAdminParams: BaseParam+ let baseUserParams: BaseParam++ let userAccessToken: string+ let collaboratorId: number++ const userEmail = '[email protected]'++ before(async function () {+ this.timeout(120000)++ const res = await prepareNotificationsTest(1)+ emails = res.emails+ userAccessToken = res.userAccessToken+ server = res.servers[0]+ userNotifications = res.userNotifications+ adminNotifications = res.adminNotifications++ baseAdminParams = {+ server,+ emails,+ to: server.adminEmail,+ token: server.accessToken,+ socketNotifications: adminNotifications,+ channelDisplayName: 'Main root channel',+ targetDisplayName: 'User 1',+ sourceDisplayName: 'root'+ }+ baseUserParams = {+ server,+ emails,+ to: userEmail,+ token: userAccessToken,+ socketNotifications: userNotifications,+ channelDisplayName: 'Main root channel',+ targetDisplayName: 'User 1',+ sourceDisplayName: 'root'+ }+ })++ describe('Common workflow', function () {+ it('Should send a notification when a user is invited to collaborate to a channel', async function () {+ const res = await server.channelCollaborators.invite({ channel: 'root_channel', target: 'user_1' })+ collaboratorId = res.id++ await waitJobs([ server ])++ await checkInvitedToCollaborateToChannel({ ...baseUserParams, checkType: 'presence' })+ await checkInvitedToCollaborateToChannel({ ...baseAdminParams, checkType: 'absence' })+ })++ it('Should send a notification when a user accepts to collaborate to a channel', async function () {+ await server.channelCollaborators.accept({ id: collaboratorId, token: userAccessToken, channel: 'root_channel' })+ await waitJobs([ server ])++ await checkAcceptedToCollaborateToChannel({ ...baseUserParams, checkType: 'absence' })+ await checkAcceptedToCollaborateToChannel({ ...baseAdminParams, checkType: 'presence' })+ })++ it('Should send a notification when a user refuses to collaborate to a channel', async function () {+ // Re-invite the user+ {+ await server.channelCollaborators.remove({ channel: 'root_channel', id: collaboratorId })+ const res = await server.channelCollaborators.invite({ channel: 'root_channel', target: 'user_1' })+ collaboratorId = res.id+ }++ await server.channelCollaborators.reject({ id: collaboratorId, channel: 'root_channel', token: userAccessToken })+ await waitJobs([ server ])++ await checkRefusedToCollaborateToChannel({ ...baseUserParams, checkType: 'absence' })+ await checkRefusedToCollaborateToChannel({ ...baseAdminParams, checkType: 'presence' })+ })+ })++ describe('With a muted account', function () {+ let muterToken: string+ let checkOptions: Omit<Parameters<typeof checkInvitedToCollaborateToChannel>[0], 'checkType'>+ let collaboratorId: number++ before(async function () {+ muterToken = await server.users.generateUserAndToken('muted_user')++ checkOptions = {+ server,+ emails,+ to: server.adminEmail,+ token: server.accessToken,+ socketNotifications: adminNotifications,+ channelDisplayName: 'Main muted_user channel',+ targetDisplayName: 'root',+ sourceDisplayName: 'muted_user'+ }+ })++ it('Should not send the notification is the source account is muted', async function () {+ await server.users.updateMyAvatar({ token: muterToken, fixture: 'avatar.png' })+ await server.channels.updateImage({ token: muterToken, channelName: 'muted_user_channel', type: 'avatar', fixture: 'avatar.png' })++ await server.blocklist.addToMyBlocklist({ account: 'muted_user' })++ const { id } = await server.channelCollaborators.invite({ channel: 'muted_user_channel', target: 'root', token: muterToken })+ collaboratorId = id++ await waitJobs(server)+ await checkInvitedToCollaborateToChannel({ ...checkOptions, checkType: 'absence' })+ })++ it('Should remove notifications from muted accounts', async function () {+ await server.blocklist.removeFromMyBlocklist({ account: 'muted_user' })++ await server.channelCollaborators.reject({ channel: 'muted_user_channel', id: collaboratorId })+ await server.channelCollaborators.invite({ channel: 'muted_user_channel', target: 'root', token: muterToken })++ await waitJobs(server)+ await checkInvitedToCollaborateToChannel({ ...checkOptions, checkType: 'presence' })++ await server.blocklist.addToMyBlocklist({ account: 'muted_user' })++ const { data } = await server.notifications.list({ token: server.accessToken })++ const notification = data.find(n =>+ n.type === UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL && n.videoChannelCollaborator.channelOwner.name === 'muted_user'+ )+ expect(notification).to.be.undefined+ })+ })++ after(async function () {+ await MockSmtpServer.Instance.kill()++ await cleanupTests([ server ])+ })+})diff --git a/packages/tests/src/api/notifications/comments-notifications.ts b/packages/tests/src/api/notifications/comments-notifications.tsindex a1976fe53c..dfdfa991f7 100644--- a/packages/tests/src/api/notifications/comments-notifications.ts+++ b/packages/tests/src/api/notifications/comments-notifications.ts@@ -3,7 +3,9 @@import { UserNotification, UserNotificationType, VideoCommentPolicy } from '@peertube/peertube-models'import { PeerTubeServer, cleanupTests, setDefaultAccountAvatar, waitJobs } from '@peertube/peertube-server-commands'import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'-import { CheckerBaseParams, checkCommentMention, checkNewCommentOnMyVideo, prepareNotificationsTest } from '@tests/shared/notifications.js'+import { checkCommentMention, checkNewCommentOnMyVideo } from '@tests/shared/notifications/check-comment-notifications.js'+import { prepareNotificationsTest } from '@tests/shared/notifications/notifications-common.js'+import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'import { expect } from 'chai'describe('Test comments notifications', function () {diff --git a/packages/tests/src/api/notifications/index.ts b/packages/tests/src/api/notifications/index.tsindex 3975eb317d..35b0066f90 100644--- a/packages/tests/src/api/notifications/index.ts+++ b/packages/tests/src/api/notifications/index.ts@@ -1,5 +1,6 @@import './admin-notifications.js'import './caption-notifications.js'+import './channel-collaborators-notification.js'import './comments-notifications.js'import './moderation-notifications.js'import './notifications-api.js'diff --git a/packages/tests/src/api/notifications/moderation-notifications.ts b/packages/tests/src/api/notifications/moderation-notifications.tsindex c16f394f2d..1a5fb6959a 100644--- a/packages/tests/src/api/notifications/moderation-notifications.ts+++ b/packages/tests/src/api/notifications/moderation-notifications.ts@@ -6,21 +6,19 @@ import { buildUUID } from '@peertube/peertube-node-utils'import { cleanupTests, PeerTubeServer, waitJobs } from '@peertube/peertube-server-commands'import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'import { MockInstancesIndex } from '@tests/shared/mock-servers/mock-instances-index.js'+import { checkAutoInstanceFollowing, checkNewInstanceFollower } from '@tests/shared/notifications/check-follow-notifications.js'import {- prepareNotificationsTest,- CheckerBaseParams,- checkNewVideoAbuseForModerators,- checkNewCommentAbuseForModerators,- checkNewAccountAbuseForModerators,checkAbuseStateChange,checkNewAbuseMessage,+ checkNewAccountAbuseForModerators,checkNewBlacklistOnMyVideo,- checkNewInstanceFollower,- checkAutoInstanceFollowing,- checkVideoAutoBlacklistForModerators,- checkMyVideoIsPublished,- checkNewVideoFromSubscription-} from '@tests/shared/notifications.js'+ checkNewCommentAbuseForModerators,+ checkNewVideoAbuseForModerators,+ checkVideoAutoBlacklistForModerators+} from '@tests/shared/notifications/check-moderation-notifications.js'+import { checkMyVideoIsPublished, checkNewVideoFromSubscription } from '@tests/shared/notifications/check-video-notifications.js'+import { prepareNotificationsTest } from '@tests/shared/notifications/notifications-common.js'+import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'describe('Test moderation notifications', function () {let servers: PeerTubeServer[] = []diff --git a/packages/tests/src/api/notifications/notifications-api.ts b/packages/tests/src/api/notifications/notifications-api.tsindex 9530d1fe73..44a9145962 100644--- a/packages/tests/src/api/notifications/notifications-api.ts+++ b/packages/tests/src/api/notifications/notifications-api.ts@@ -1,15 +1,12 @@/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { expect } from 'chai'import { UserNotification, UserNotificationSettingValue, UserNotificationType } from '@peertube/peertube-models'import { cleanupTests, PeerTubeServer, waitJobs } from '@peertube/peertube-server-commands'import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'-import {- prepareNotificationsTest,- CheckerBaseParams,- getAllNotificationsSettings,- checkNewVideoFromSubscription-} from '@tests/shared/notifications.js'+import { checkNewVideoFromSubscription } from '@tests/shared/notifications/check-video-notifications.js'+import { getAllNotificationsSettings, prepareNotificationsTest } from '@tests/shared/notifications/notifications-common.js'+import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'+import { expect } from 'chai'describe('Test notifications API', function () {let server: PeerTubeServerdiff --git a/packages/tests/src/api/notifications/registrations-notifications.ts b/packages/tests/src/api/notifications/registrations-notifications.tsindex f96c197e51..a15272fa20 100644--- a/packages/tests/src/api/notifications/registrations-notifications.ts+++ b/packages/tests/src/api/notifications/registrations-notifications.ts@@ -3,7 +3,9 @@import { UserNotification } from '@peertube/peertube-models'import { cleanupTests, PeerTubeServer, waitJobs } from '@peertube/peertube-server-commands'import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'-import { CheckerBaseParams, prepareNotificationsTest, checkUserRegistered, checkRegistrationRequest } from '@tests/shared/notifications.js'+import { checkRegistrationRequest, checkUserRegistered } from '@tests/shared/notifications/check-moderation-notifications.js'+import { prepareNotificationsTest } from '@tests/shared/notifications/notifications-common.js'+import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'describe('Test registrations notifications', function () {let server: PeerTubeServerdiff --git a/packages/tests/src/api/notifications/user-notifications.ts b/packages/tests/src/api/notifications/user-notifications.tsindex 1be70802df..82f80cf0d5 100644--- a/packages/tests/src/api/notifications/user-notifications.ts+++ b/packages/tests/src/api/notifications/user-notifications.ts@@ -6,17 +6,16 @@ import { buildUUID } from '@peertube/peertube-node-utils'import { cleanupTests, findExternalSavedVideo, PeerTubeServer, stopFfmpeg, waitJobs } from '@peertube/peertube-server-commands'import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'+import { checkNewActorFollow } from '@tests/shared/notifications/check-follow-notifications.js'import {- CheckerBaseParams,checkMyVideoImportIsFinished,checkMyVideoIsPublished,- checkNewActorFollow,checkNewLiveFromSubscription,checkNewVideoFromSubscription,- checkVideoStudioEditionIsFinished,- prepareNotificationsTest,- waitUntilNotification-} from '@tests/shared/notifications.js'+ checkVideoStudioEditionIsFinished+} from '@tests/shared/notifications/check-video-notifications.js'+import { prepareNotificationsTest, waitUntilNotification } from '@tests/shared/notifications/notifications-common.js'+import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'import { uploadRandomVideoOnServers } from '@tests/shared/videos.js'import { expect } from 'chai'diff --git a/packages/tests/src/api/object-storage/video-static-file-privacy.ts b/packages/tests/src/api/object-storage/video-static-file-privacy.tsindex 2d719b162e..0f002793f0 100644--- a/packages/tests/src/api/object-storage/video-static-file-privacy.ts+++ b/packages/tests/src/api/object-storage/video-static-file-privacy.ts@@ -34,7 +34,9 @@ describe('Object storage for video static file privacy', function () {let server: PeerTubeServerlet sqlCommand: SQLCommand+let userToken: string+ let editorToken: string// ---------------------------------------------------------------------------@@ -44,7 +46,9 @@ describe('Object storage for video static file privacy', function () {for (const file of video.files) {expectStartWith(file.fileUrl, server.url + '/object-storage-proxy/web-videos/private/')- await makeRawRequest({ url: file.fileUrl, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ for (const token of [ server.accessToken, editorToken ]) {+ await makeRawRequest({ url: file.fileUrl, token, expectedStatus: HttpStatusCode.OK_200 })+ }}for (const file of getAllFiles(video)) {@@ -66,13 +70,15 @@ describe('Object storage for video static file privacy', function () {expectStartWith(url, server.url + '/object-storage-proxy/streaming-playlists/hls/private/')}- await makeRawRequest({ url: hls.playlistUrl, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })- await makeRawRequest({ url: hls.segmentsSha256Url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ for (const token of [ server.accessToken, editorToken ]) {+ await makeRawRequest({ url: hls.playlistUrl, token, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url: hls.segmentsSha256Url, token, expectedStatus: HttpStatusCode.OK_200 })- for (const file of hls.files) {- expectStartWith(file.fileUrl, server.url + '/object-storage-proxy/streaming-playlists/hls/private/')+ for (const file of hls.files) {+ expectStartWith(file.fileUrl, server.url + '/object-storage-proxy/streaming-playlists/hls/private/')- await makeRawRequest({ url: file.fileUrl, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url: file.fileUrl, token, expectedStatus: HttpStatusCode.OK_200 })+ }}await checkPlaylistInfohash({ video, files: hls.files, sqlCommand })@@ -110,7 +116,8 @@ describe('Object storage for video static file privacy', function () {await server.config.enableMinimumTranscoding()- userToken = await server.users.generateUserAndToken('user1')+ userToken = await server.users.generateUserAndToken('user')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')sqlCommand = new SQLCommand(server)})@@ -183,7 +190,7 @@ describe('Object storage for video static file privacy', function () {await checkPublicVODFiles(publicVideoUUID)})- it('Should not get files without appropriate OAuth token', async function () {+ it('Should not get files without appropriate user token', async function () {this.timeout(60000)const { webVideoFile, hlsFile } = await getSampleFileUrls(privateVideoUUID)@@ -195,7 +202,7 @@ describe('Object storage for video static file privacy', function () {await makeRawRequest({ url: hlsFile, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })})- it('Should not get files without appropriate password or appropriate OAuth token', async function () {+ it('Should not get files without appropriate password or appropriate user token', async function () {this.timeout(60000)const { webVideoFile, hlsFile } = await getSampleFileUrls(passwordProtectedVideoUUID)@@ -244,30 +251,35 @@ describe('Object storage for video static file privacy', function () {await makeRawRequest({ url: goodUrl, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })})- it('Should correctly check OAuth, video file token of private video', async function () {+ it('Should correctly check user token, video file token of private video', async function () {this.timeout(60000)- const badVideoFileToken = await server.videoToken.getVideoFileToken({ token: userToken, videoId: userPrivateVideoUUID })- const goodVideoFileToken = await server.videoToken.getVideoFileToken({ videoId: privateVideoUUID })+ const userFileToken = await server.videoToken.getVideoFileToken({ token: userToken, videoId: userPrivateVideoUUID })+ const editorFileToken = await server.videoToken.getVideoFileToken({ token: editorToken, videoId: privateVideoUUID })+ const adminFileToken = await server.videoToken.getVideoFileToken({ videoId: privateVideoUUID })const { webVideoFile, hlsFile } = await getSampleFileUrls(privateVideoUUID)for (const url of [ webVideoFile, hlsFile ]) {- await makeRawRequest({ url, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })+await makeRawRequest({ url, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: userFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, query: { videoFileToken: badVideoFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, query: { videoFileToken: goodVideoFileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: adminFileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, token: editorToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: editorFileToken }, expectedStatus: HttpStatusCode.OK_200 })}})- it('Should correctly check OAuth, video file token or video password of password protected video', async function () {+ it('Should correctly check user token, video file token or video password of password protected video', async function () {this.timeout(60000)- const badVideoFileToken = await server.videoToken.getVideoFileToken({ token: userToken, videoId: userPrivateVideoUUID })- const goodVideoFileToken = await server.videoToken.getVideoFileToken({+ const userFileToken = await server.videoToken.getVideoFileToken({ token: userToken, videoId: userPrivateVideoUUID })+ const adminFileToken = await server.videoToken.getVideoFileToken({+ token: undefined,videoId: passwordProtectedVideoUUID,videoPassword: correctPassword})@@ -275,18 +287,20 @@ describe('Object storage for video static file privacy', function () {const { webVideoFile, hlsFile } = await getSampleFileUrls(passwordProtectedVideoUUID)for (const url of [ hlsFile, webVideoFile ]) {- await makeRawRequest({ url, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })+await makeRawRequest({ url, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: userFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, query: { videoFileToken: badVideoFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, query: { videoFileToken: goodVideoFileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: adminFileToken }, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({url,headers: incorrectPasswordHeader,expectedStatus: HttpStatusCode.FORBIDDEN_403})+await makeRawRequest({ url, headers: correctPasswordHeader, expectedStatus: HttpStatusCode.OK_200 })}})@@ -350,6 +364,8 @@ describe('Object storage for video static file privacy', function () {? await server.videoToken.getVideoFileToken({ token: null, videoId: video.uuid, videoPassword }): await server.videoToken.getVideoFileToken({ videoId: video.uuid })+ const editorFileToken = await server.videoToken.getVideoFileToken({ videoId: video.uuid, token: editorToken })+const hls = video.streamingPlaylists[0]for (const url of [ hls.playlistUrl, hls.segmentsSha256Url ]) {@@ -359,10 +375,12 @@ describe('Object storage for video static file privacy', function () {await makeRawRequest({ url: hls.segmentsSha256Url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, token: editorToken, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url, query: { videoFileToken: fileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: editorFileToken }, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })await makeRawRequest({ url, query: { videoFileToken: unrelatedFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })if (videoPassword) {@@ -385,16 +403,20 @@ describe('Object storage for video static file privacy', function () {async function checkReplay (replay: VideoDetails) {const fileToken = await server.videoToken.getVideoFileToken({ videoId: replay.uuid })+ const editorFileToken = await server.videoToken.getVideoFileToken({ videoId: replay.uuid, token: editorToken })const hls = replay.streamingPlaylists[0]expect(hls.files).to.not.have.lengthOf(0)for (const file of hls.files) {await makeRawRequest({ url: file.fileUrl, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url: file.fileUrl, token: editorToken, expectedStatus: HttpStatusCode.OK_200 })+await makeRawRequest({ url: file.fileUrl, query: { videoFileToken: fileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url: file.fileUrl, query: { videoFileToken: editorFileToken }, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url: file.fileUrl, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url: file.fileUrl, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url: file.fileUrl, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })await makeRawRequest({url: file.fileUrl,query: { videoFileToken: unrelatedFileToken },@@ -406,10 +428,13 @@ describe('Object storage for video static file privacy', function () {expectStartWith(url, server.url + '/object-storage-proxy/streaming-playlists/hls/private/')await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, token: editorToken, expectedStatus: HttpStatusCode.OK_200 })+await makeRawRequest({ url, query: { videoFileToken: fileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: editorFileToken }, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })await makeRawRequest({ url, query: { videoFileToken: unrelatedFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })}}diff --git a/packages/tests/src/api/users/user-export.ts b/packages/tests/src/api/users/user-export.tsindex 81d8c7da28..35c4feb365 100644--- a/packages/tests/src/api/users/user-export.ts+++ b/packages/tests/src/api/users/user-export.ts@@ -100,6 +100,16 @@ function runTest (withObjectStorage: boolean) {server,remoteServer} = await prepareImportExportTests({ emails, objectStorage, withBlockedServer: false }))++ // Create collaboration to ensure we don't export them+ const userToken = await server.users.generateUserAndToken('user')+ const { id } = await server.channelCollaborators.invite({ target: 'noah', channel: 'user_channel', token: userToken })+ await server.channelCollaborators.accept({ id, channel: 'user_channel', token: noahToken })+ await server.videos.quickUpload({+ name: 'collab video',+ token: userToken,+ channelId: await server.channels.getIdOf({ channelName: 'user_channel' })+ })})it('Should export root account', async function () {@@ -145,6 +155,9 @@ function runTest (withObjectStorage: boolean) {await waitJobs([ server ])})+ it('Should not export collaborations', async function () {+ })+it('Should have received an email on archive creation', async function () {const email = emails.find(e => {return e['to'][0]['address'] === 'admin' + server.internalServerNumber + '@example.com' &&diff --git a/packages/tests/src/api/users/user-import.ts b/packages/tests/src/api/users/user-import.tsindex 1445f0519f..6bdf125d04 100644--- a/packages/tests/src/api/users/user-import.ts+++ b/packages/tests/src/api/users/user-import.ts@@ -510,7 +510,7 @@ function runTest (withObjectStorage: boolean) {const liveVideo = data.find(v => v.name === 'noah live video')expect(liveVideo).to.exist- await remoteServer.videos.get({ id: liveVideo.uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await remoteServer.videos.get({ id: liveVideo.uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })const video = await remoteServer.videos.getWithPassword({ id: liveVideo.uuid, password: 'password1' })const live = await remoteServer.live.get({ videoId: liveVideo.uuid, token: remoteNoahToken })diff --git a/packages/tests/src/api/videos/channel-collaborators.ts b/packages/tests/src/api/videos/channel-collaborators.tsnew file mode 100644index 0000000000..af85486824--- /dev/null+++ b/packages/tests/src/api/videos/channel-collaborators.ts@@ -0,0 +1,563 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { BulkRemoveCommentsOfBody, HttpStatusCode, VideoChannelCollaboratorState, VideoPrivacy } from '@peertube/peertube-models'+import {+ cleanupTests,+ createMultipleServers,+ doubleFollow,+ PeerTubeServer,+ setAccessTokensToServers,+ setDefaultVideoChannel,+ waitJobs+} from '@peertube/peertube-server-commands'+import { checkActorImage } from '@tests/shared/actors.js'+import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'+import { expect } from 'chai'++describe('Test channel collaborators', function () {+ let servers: PeerTubeServer[]++ let collaborator1: string+ let collaborator2: string++ let collaboratorId1: number+ let collaboratorId2: number++ let channelCollabId: number+ let channelCollabId2: number++ async function expectMyChannels (token: string, owned: string[], collab: string[]) {+ const me = await servers[0].users.getMyInfo({ token })++ {+ expect(me.videoChannels.map(c => c.name)).to.have.members(owned)+ expect(me.videoChannelCollaborations.map(c => c.name)).to.have.members(collab)++ for (const c of [ ...me.videoChannels, ...me.videoChannelCollaborations ]) {+ expect(c).to.have.property('displayName')++ expect(c).to.have.property('description')+ expect(c).to.have.property('support')+ expect(c).to.have.property('isLocal')++ expect(c).to.have.property('updatedAt')++ expect(c).to.have.property('banners')+ expect(c).to.have.property('id')+ expect(c).to.have.property('url')+ expect(c).to.have.property('name')+ expect(c).to.have.property('host')+ expect(c).to.have.property('followingCount')+ expect(c).to.have.property('followersCount')+ expect(c).to.have.property('createdAt')+ expect(c).to.have.property('avatars')+ expect(c).to.have.property('ownerAccountId')+ }+ }++ {+ const names = [ ...owned, ...collab ]++ const { total, data } = await servers[0].channels.listByAccount({ accountName: me.username, token, includeCollaborations: true })+ expect(total).to.equal(names.length)+ expect(data).to.have.lengthOf(names.length)++ expect(data.map(c => c.name)).to.have.members(names)+ }++ {+ const { total, data } = await servers[0].channels.listByAccount({ accountName: me.username, token, includeCollaborations: false })+ expect(total).to.equal(owned.length)+ expect(data).to.have.lengthOf(owned.length)++ expect(data.map(c => c.name)).to.have.members(owned)+ }+ }++ before(async function () {+ this.timeout(60000)++ servers = await createMultipleServers(2)++ await setAccessTokensToServers(servers)+ await setDefaultVideoChannel(servers)+ await doubleFollow(servers[0], servers[1])++ await waitJobs(servers)++ collaborator1 = await servers[0].users.generateUserAndToken('collaborator1')+ collaborator2 = await servers[0].users.generateUserAndToken('collaborator2')++ await servers[0].users.updateMyAvatar({ fixture: 'avatar.png', token: collaborator1 })++ await waitJobs(servers)+ })++ describe('Manage collaborators', function () {+ it('Should not have collaborators by default', async function () {+ const collaborators = await servers[0].channelCollaborators.list({ channel: 'root_channel' })+ expect(collaborators.total).to.equal(0)+ expect(collaborators.data).to.have.lengthOf(0)+ })++ it('Should create a channel and invite a collaborator', async function () {+ const channel = await servers[0].channels.create({ attributes: { name: 'channel_collaboration1' } })+ channelCollabId = channel.id++ await servers[0].channels.updateImage({ channelName: 'channel_collaboration1', fixture: 'avatar.png', type: 'avatar' })++ const { id } = await servers[0].channelCollaborators.invite({ channel: 'channel_collaboration1', target: 'collaborator1' })+ collaboratorId1 = id++ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(1)+ expect(data).to.have.lengthOf(1)++ const collab = data[0]+ expect(collab.id).to.exist+ expect(collab.createdAt).to.exist+ expect(collab.updatedAt).to.exist+ expect(collab.state.id).to.equal(VideoChannelCollaboratorState.PENDING)+ expect(collab.state.label).to.equal('Pending')++ expect(collab.account.displayName).to.equal('collaborator1')+ expect(collab.account.host).to.equal(servers[0].host)+ expect(collab.account.id).to.exist+ expect(collab.account.name).to.equal('collaborator1')++ await checkActorImage(collab.account)+ })++ it('Should invite another collaborator', async function () {+ const { id } = await servers[0].channelCollaborators.invite({ channel: 'channel_collaboration1', target: 'collaborator2' })+ collaboratorId2 = id++ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(2)+ expect(data).to.have.lengthOf(2)++ expect(data[0].account.name).to.equal('collaborator2')+ expect(data[1].account.name).to.equal('collaborator1')+ })++ it('Should not list channels when collaboration is not yet accepted', async function () {+ await expectMyChannels(servers[0].accessToken, [ 'root_channel', 'channel_collaboration1' ], [])+ await expectMyChannels(collaborator1, [ 'collaborator1_channel' ], [])+ await expectMyChannels(collaborator2, [ 'collaborator2_channel' ], [])+ })++ it('Should accept an invitation', async function () {+ await servers[0].channelCollaborators.accept({ channel: 'channel_collaboration1', id: collaboratorId1, token: collaborator1 })++ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1', token: collaborator1 })+ expect(total).to.equal(2)+ expect(data).to.have.lengthOf(2)++ expect(data[0].account.name).to.equal('collaborator2')+ expect(data[0].state.id).to.equal(VideoChannelCollaboratorState.PENDING)+ expect(data[1].account.name).to.equal('collaborator1')+ expect(data[1].state.id).to.equal(VideoChannelCollaboratorState.ACCEPTED)+ expect(data[1].state.label).to.equal('Accepted')+ })++ it('Should list channel collaborations after having accepted an invitation', async function () {+ await expectMyChannels(servers[0].accessToken, [ 'root_channel', 'channel_collaboration1' ], [])+ await expectMyChannels(collaborator1, [ 'collaborator1_channel' ], [ 'channel_collaboration1' ])+ await expectMyChannels(collaborator2, [ 'collaborator2_channel' ], [])+ })++ it('Should reject an invitation', async function () {+ await servers[0].channelCollaborators.reject({ channel: 'channel_collaboration1', id: collaboratorId2, token: collaborator2 })++ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(1)+ expect(data).to.have.lengthOf(1)++ expect(data[0].account.name).to.equal('collaborator1')+ expect(data[0].state.id).to.equal(VideoChannelCollaboratorState.ACCEPTED)+ })++ it('Should be able to re-invite a rejected collaborator', async function () {+ const { id } = await servers[0].channelCollaborators.invite({ channel: 'channel_collaboration1', target: 'collaborator2' })+ collaboratorId2 = id++ {+ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(2)+ expect(data).to.have.lengthOf(2)+ }++ await servers[0].channelCollaborators.reject({ channel: 'channel_collaboration1', id: collaboratorId2, token: collaborator2 })++ {+ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(1)+ expect(data).to.have.lengthOf(1)+ }+ })++ it('Should list channel collaborations after having rejected an invitation', async function () {+ await expectMyChannels(servers[0].accessToken, [ 'root_channel', 'channel_collaboration1' ], [])+ await expectMyChannels(collaborator1, [ 'collaborator1_channel' ], [ 'channel_collaboration1' ])+ await expectMyChannels(collaborator2, [ 'collaborator2_channel' ], [])+ })++ it('Should delete a pending invitation', async function () {+ const { id } = await servers[0].channelCollaborators.invite({ channel: 'channel_collaboration1', target: 'collaborator2' })+ collaboratorId2 = id++ {+ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(2)+ expect(data).to.have.lengthOf(2)+ }++ await servers[0].channelCollaborators.remove({ channel: 'channel_collaboration1', id: collaboratorId2 })++ {+ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(1)+ expect(data).to.have.lengthOf(1)+ }++ await servers[0].channelCollaborators.accept({+ channel: 'channel_collaboration1',+ id: collaboratorId2,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should delete an accepted invitation', async function () {+ await servers[0].channelCollaborators.remove({ channel: 'channel_collaboration1', id: collaboratorId1 })++ const { total, data } = await servers[0].channelCollaborators.list({ channel: 'channel_collaboration1' })+ expect(total).to.equal(0)+ expect(data).to.have.lengthOf(0)+ })++ it('Should not list collab channels anymore', async function () {+ await expectMyChannels(servers[0].accessToken, [ 'root_channel', 'channel_collaboration1' ], [])+ await expectMyChannels(collaborator1, [ 'collaborator1_channel' ], [])+ await expectMyChannels(collaborator2, [ 'collaborator2_channel' ], [])+ })+ })++ describe('With a collaborator', function () {+ let user1: string+ let external: string+ let videoId: string+ let playlistId: string++ before(async function () {+ user1 = await servers[0].users.generateUserAndToken('user1')+ external = await servers[0].users.generateUserAndToken('external')++ {+ const { id } = await servers[0].channelCollaborators.invite({ channel: 'channel_collaboration1', target: 'collaborator1' })+ await servers[0].channelCollaborators.accept({ channel: 'channel_collaboration1', id, token: collaborator1 })+ }++ {+ const { id } = await servers[0].channelCollaborators.invite({ channel: 'channel_collaboration1', target: 'collaborator2' })+ await servers[0].channelCollaborators.accept({ channel: 'channel_collaboration1', id, token: collaborator2 })+ }++ {+ const { id } = await servers[0].channelCollaborators.invite({ channel: 'user1_channel', target: 'collaborator1', token: user1 })+ await servers[0].channelCollaborators.accept({ channel: 'user1_channel', id, token: collaborator1 })+ }+ })++ describe('Listing entities', function () {+ it('Should list videos from collab channels', async function () {+ const { uuid } = await servers[0].videos.upload({+ attributes: { name: 'video collab 1', channelId: channelCollabId },+ token: collaborator1+ })+ videoId = uuid++ await servers[0].videos.quickUpload({ name: 'video collab 2', channelId: channelCollabId, privacy: VideoPrivacy.PRIVATE })++ for (const token of [ collaborator1, collaborator2 ]) {+ {+ const videos = await servers[0].videos.listMyVideos({ token, includeCollaborations: true })++ expect(videos.total).to.equal(2)+ expect(videos.data).to.have.lengthOf(2)+ expect(videos.data[0].name).to.equal('video collab 2')+ expect(videos.data[1].name).to.equal('video collab 1')+ }++ {+ const videos = await servers[0].videos.listMyVideos({ token, includeCollaborations: false })++ expect(videos.total).to.equal(0)+ expect(videos.data).to.have.lengthOf(0)+ }+ }++ for (const token of [ external, user1 ]) {+ const videos = await servers[0].videos.listMyVideos({ token, includeCollaborations: true })+ expect(videos.total).to.equal(0)+ expect(videos.data).to.have.lengthOf(0)+ }+ })++ it('Should list comments from collab channels', async function () {+ await servers[0].comments.createThread({ token: external, videoId, text: 'A thread from collab channel' })+ await servers[0].comments.addReplyToLastThread({ token: external, text: 'A reply from collab channel' })++ for (const token of [ collaborator1, collaborator2 ]) {+ for (+ const comments of [+ await servers[0].comments.listCommentsOnMyVideos({ token, includeCollaborations: true, videoChannelId: channelCollabId }),+ await servers[0].comments.listCommentsOnMyVideos({ token, includeCollaborations: true, videoChannelId: channelCollabId })+ ]+ ) {+ expect(comments.total).to.equal(2)+ expect(comments.data).to.have.lengthOf(2)+ expect(comments.data[0].text).to.equal('A reply from collab channel')+ expect(comments.data[1].text).to.equal('A thread from collab channel')+ }++ const { total, data } = await servers[0].comments.listCommentsOnMyVideos({+ token,+ includeCollaborations: false,+ videoChannelId: channelCollabId+ })+ expect(total).to.equal(0)+ expect(data).to.have.lengthOf(0)+ }++ for (const token of [ external, user1 ]) {+ const comments = await servers[0].comments.listCommentsOnMyVideos({ token, includeCollaborations: true })+ expect(comments.total).to.equal(0)+ expect(comments.data).to.have.lengthOf(0)+ }+ })++ it('Should list playlists from collab channels', async function () {+ for (const displayName of [ 'playlist1', 'playlist2' ]) {+ const playlist = await servers[0].playlists.create({+ token: collaborator1,+ attributes: { displayName, privacy: VideoPrivacy.PUBLIC, videoChannelId: channelCollabId }+ })+ playlistId = playlist.uuid+ }++ await servers[0].playlists.addElement({ playlistId, attributes: { videoId }, token: collaborator2 })++ for (const token of [ collaborator1, collaborator2, servers[0].accessToken ]) {+ const me = await servers[0].users.getMyInfo({ token })++ {+ const playlists = await servers[0].playlists.listByAccount({ token, handle: me.username, includeCollaborations: true })+ expect(playlists.total).to.equal(3)+ expect(playlists.data).to.have.lengthOf(3)+ expect(playlists.data[0].displayName).to.equal('playlist2')+ expect(playlists.data[1].displayName).to.equal('playlist1')+ expect(playlists.data[2].displayName).to.equal('Watch later')+ }+ }++ // Filter out collaborated channels+ {+ const playlists = await servers[0].playlists.listByAccount({+ token: collaborator2,+ handle: 'collaborator2',+ includeCollaborations: false+ })+ expect(playlists.data.map(p => p.displayName)).to.have.members([ 'Watch later' ])+ }++ for (const token of [ external, user1 ]) {+ const me = await servers[0].users.getMyInfo({ token })++ const playlists = await servers[0].playlists.listByAccount({ token, handle: me.username, includeCollaborations: true })+ expect(playlists.total).to.equal(1)+ expect(playlists.data).to.have.lengthOf(1)+ expect(playlists.data[0].displayName).to.equal('Watch later')+ }+ })++ it('Should list imports from collab channels', async function () {+ const { video: rootVideo } = await servers[0].videoImports.quickImport({+ name: 'root import',+ targetUrl: FIXTURE_URLS.goodVideo,+ channelId: channelCollabId+ })++ const { video: collabVideo } = await servers[0].videoImports.quickImport({+ name: 'collab import',+ targetUrl: FIXTURE_URLS.goodVideo,+ token: collaborator1,+ channelId: channelCollabId+ })++ await waitJobs(servers)++ for (const token of [ servers[0].accessToken, collaborator1 ]) {+ const { total, data } = await servers[0].videoImports.listMyVideoImports({ token, includeCollaborations: true })+ expect(total).to.equal(2)+ expect(data).to.have.lengthOf(2)+ expect(data.map(i => i.video.name)).to.have.members([ 'root import', 'collab import' ])+ }++ // Filter out collaborated channels+ const { total, data } = await servers[0].videoImports.listMyVideoImports({ token: collaborator1, includeCollaborations: false })+ expect(total).to.equal(1)+ expect(data.map(i => i.video.name)).to.have.members([ 'collab import' ])++ // We delete the root video+ await servers[0].videos.remove({ id: rootVideo.id, token: collaborator1 })++ // Root still sees its import but collab doesn't see it anymore+ {+ const { data } = await servers[0].videoImports.listMyVideoImports({ token: collaborator1, includeCollaborations: true })+ expect(data.map(i => i.video.name)).to.have.members([ 'collab import' ])+ }++ {+ const { data } = await servers[0].videoImports.listMyVideoImports({ token: servers[0].accessToken, includeCollaborations: true })+ expect(data.map(i => i.video?.name)).to.have.members([ undefined, 'collab import' ])+ }++ // We delete the editor+ await servers[0].videos.remove({ id: collabVideo.id })++ // Collab still sees its import but root doesn't see it anymore+ {+ const { data } = await servers[0].videoImports.listMyVideoImports({ token: collaborator1, includeCollaborations: true })+ expect(data.map(i => i.video?.name)).to.have.members([ undefined ])+ }++ {+ const { data } = await servers[0].videoImports.listMyVideoImports({ token: servers[0].accessToken, includeCollaborations: true })+ expect(data.map(i => i.video?.name)).to.have.members([ undefined ])+ }+ })++ it('Should list syncs from collab channels', async function () {+ await servers[0].config.enableChannelSync()++ await servers[0].channelSyncs.create({+ attributes: {+ externalChannelUrl: FIXTURE_URLS.youtubeChannel,+ videoChannelId: channelCollabId+ },+ token: collaborator1+ })++ {+ const { data, total } = await servers[0].channelSyncs.listByAccount({+ accountName: 'collaborator1',+ token: collaborator1,+ includeCollaborations: false+ })+ expect(total).to.equal(0)+ expect(data).to.have.lengthOf(0)+ }++ {+ for (const token of [ collaborator1, collaborator2, servers[0].accessToken ]) {+ const me = await servers[0].users.getMyInfo({ token })++ const { data, total } = await servers[0].channelSyncs.listByAccount({+ accountName: me.username,+ token,+ includeCollaborations: true+ })+ expect(total).to.equal(1)+ expect(data).to.have.lengthOf(1)+ }+ }+ })+ })++ describe('Managing entities', function () {+ it('Should have federated objects created by collaborators', async function () {+ await waitJobs(servers)++ const video = await servers[1].videos.get({ id: videoId })+ expect(video.name).to.equal('video collab 1')++ const playlist = await servers[1].playlists.get({ playlistId })+ expect(playlist.displayName).to.equal('playlist2')+ })++ it('Should update the channel of a video', async function () {+ const channel = await servers[0].channels.create({ attributes: { name: 'channel_collaboration2' } })+ channelCollabId2 = channel.id++ const { id } = await servers[0].channelCollaborators.invite({ channel: 'channel_collaboration2', target: 'collaborator1' })+ await servers[0].channelCollaborators.accept({ channel: 'channel_collaboration2', id, token: collaborator1 })++ await servers[0].videos.update({ id: videoId, attributes: { channelId: channelCollabId2 }, token: collaborator1 })++ await waitJobs(servers)++ for (const server of servers) {+ const video = await server.videos.get({ id: videoId })+ expect(video.channel.name).to.equal('channel_collaboration2')+ }+ })++ it('Should update the channel of a playlist', async function () {+ await servers[0].playlists.update({ playlistId, attributes: { videoChannelId: channelCollabId2 }, token: collaborator1 })++ await waitJobs(servers)++ for (const server of servers) {+ const playlist = await server.playlists.get({ playlistId })+ expect(playlist.videoChannel.name).to.equal('channel_collaboration2')+ }+ })++ it('Should bulk delete comments from collab channels', async function () {+ const channel = await servers[0].channels.create({ attributes: { name: 'channel_collaboration3' } })+ const editor = await servers[0].channelCollaborators.createEditor('comment_editor', 'channel_collaboration3')+ const { uuid } = await servers[0].videos.quickUpload({ name: 'video to comment', token: editor, channelId: channel.id })++ const commenter = await servers[0].users.generateUserAndToken('commenter')+ await servers[0].comments.createThread({ token: commenter, videoId: uuid, text: 'commenter' })++ const checkComments = async (total: number) => {+ const comments = await servers[0].comments.listCommentsOnMyVideos({+ token: editor,+ includeCollaborations: true,+ videoChannelId: channel.id+ })++ expect(comments.total).to.equal(total)+ }++ const deleteComments = async (accountName: string, scope: BulkRemoveCommentsOfBody['scope']) => {+ await servers[0].bulk.removeCommentsOf({+ token: editor,+ attributes: {+ accountName,+ scope+ }+ })++ await waitJobs(servers)+ }++ await checkComments(1)++ await deleteComments('commenter', 'my-videos')+ await checkComments(1)++ await deleteComments('root', 'my-videos-and-collaborations')+ await checkComments(1)++ await deleteComments('commenter', 'my-videos-and-collaborations')+ await checkComments(0)+ })+ })+ })++ after(async function () {+ await cleanupTests(servers)+ })+})diff --git a/packages/tests/src/api/videos/channel-import-videos.ts b/packages/tests/src/api/videos/channel-import-videos.tsindex d89ce34483..5174936d32 100644--- a/packages/tests/src/api/videos/channel-import-videos.ts+++ b/packages/tests/src/api/videos/channel-import-videos.ts@@ -17,7 +17,6 @@ describe('Test videos import in a channel', function () {if (areYoutubeImportTestsDisabled()) returnfunction runSuite (mode: 'youtube-dl' | 'yt-dlp') {-describe('Import using ' + mode, function () {let server: PeerTubeServer@@ -43,7 +42,7 @@ describe('Test videos import in a channel', function () {})it('These imports should not have a sync id', async function () {- const { total, data } = await server.videoImports.getMyVideoImports()+ const { total, data } = await server.videoImports.listMyVideoImports()expect(total).to.equal(2)expect(data).to.have.lengthOf(2)@@ -84,7 +83,7 @@ describe('Test videos import in a channel', function () {})it('These imports should have a sync id', async function () {- const { total, data } = await server.videoImports.getMyVideoImports()+ const { total, data } = await server.videoImports.listMyVideoImports()expect(total).to.equal(4)expect(data).to.have.lengthOf(4)@@ -99,7 +98,7 @@ describe('Test videos import in a channel', function () {})it('Should be able to filter imports by this sync id', async function () {- const { total, data } = await server.videoImports.getMyVideoImports({ videoChannelSyncId: server.store.videoChannelSync.id })+ const { total, data } = await server.videoImports.listMyVideoImports({ videoChannelSyncId: server.store.videoChannelSync.id })expect(total).to.equal(2)expect(data).to.have.lengthOf(2)diff --git a/packages/tests/src/api/videos/index.ts b/packages/tests/src/api/videos/index.tsindex 4b542619f0..ead5abe2f9 100644--- a/packages/tests/src/api/videos/index.ts+++ b/packages/tests/src/api/videos/index.ts@@ -21,8 +21,8 @@ import './video-schedule-update.js'import './video-source.js'import './video-static-file-privacy.js'import './video-storyboard.js'-import './video-storyboard-remote-runner.js'import './video-transcription.js'import './videos-common-filters.js'import './videos-history.js'import './videos-overview.js'+import './channel-collaborators.js'diff --git a/packages/tests/src/api/videos/video-channel-syncs.ts b/packages/tests/src/api/videos/video-channel-syncs.tsindex c79b156514..e7ba73a91d 100644--- a/packages/tests/src/api/videos/video-channel-syncs.ts+++ b/packages/tests/src/api/videos/video-channel-syncs.ts@@ -212,7 +212,7 @@ describe('Test channel synchronizations', function () {})it('Should list imports of a channel synchronization', async function () {- const { total, data } = await servers[0].videoImports.getMyVideoImports({ videoChannelSyncId: rootChannelSyncId })+ const { total, data } = await servers[0].videoImports.listMyVideoImports({ videoChannelSyncId: rootChannelSyncId })expect(total).to.equal(1)expect(data).to.have.lengthOf(1)diff --git a/packages/tests/src/api/videos/video-comments.ts b/packages/tests/src/api/videos/video-comments.tsindex 260d160f41..9923eaa8c8 100644--- a/packages/tests/src/api/videos/video-comments.ts+++ b/packages/tests/src/api/videos/video-comments.ts@@ -273,6 +273,8 @@ describe('Test video comments', function () {expect(data[0].account.name).to.equal('root')expect(data[0].account.displayName).to.equal('root')expect(data[0].account.avatars).to.have.lengthOf(4)+ expect(data[0].video.uuid).to.equal(videoUUID)+ expect(data[0].video.channel.name).to.equal('root_channel')}for (const fn of listFunctions()) {diff --git a/packages/tests/src/api/videos/video-imports.ts b/packages/tests/src/api/videos/video-imports.tsindex 306f4e1677..6579edbe0c 100644--- a/packages/tests/src/api/videos/video-imports.ts+++ b/packages/tests/src/api/videos/video-imports.ts@@ -118,15 +118,16 @@ describe('Test video imports', function () {expect(video.name).to.equal('small video - youtube'){- expect(video.thumbnailPath).to.match(new RegExp(`^/lazy-static/thumbnails/.+.jpg$`))- expect(video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.jpg$`))+ expect(video.thumbnailPath).to.match(new RegExp(`^/lazy-static/thumbnails/.+.webp$`))+ expect(video.previewPath).to.match(new RegExp(`^/lazy-static/previews/.+.webp$`))- const suffix = mode === 'yt-dlp'- ? '_yt_dlp'- : ''+ // FIXME: re-enable when we'll support webp pixel match+ // const suffix = mode === 'yt-dlp'+ // ? '_yt_dlp'+ // : ''- await testImageGeneratedByFFmpeg(servers[0].url, 'video_import_thumbnail' + suffix, video.thumbnailPath)- await testImageGeneratedByFFmpeg(servers[0].url, 'video_import_preview' + suffix, video.previewPath)+ // await testImageGeneratedByFFmpeg(servers[0].url, 'video_import_thumbnail' + suffix, video.thumbnailPath)+ // await testImageGeneratedByFFmpeg(servers[0].url, 'video_import_preview' + suffix, video.previewPath)}const bodyCaptions = await servers[0].captions.list({ videoId: video.id })@@ -204,7 +205,7 @@ describe('Test video imports', function () {it('Should list the videos to import in my imports on server 1', async function () {if (areYoutubeImportTestsDisabled()) return- const { total, data: videoImports } = await servers[0].videoImports.getMyVideoImports({ sort: '-createdAt' })+ const { total, data: videoImports } = await servers[0].videoImports.listMyVideoImports({ sort: '-createdAt' })const totalExpected = areYoutubeImportTestsDisabled()? 2@@ -244,7 +245,7 @@ describe('Test video imports', function () {it('Should filter my imports on target URL', async function () {if (areYoutubeImportTestsDisabled()) return- const { total, data: videoImports } = await servers[0].videoImports.getMyVideoImports({ targetUrl: FIXTURE_URLS.youtube })+ const { total, data: videoImports } = await servers[0].videoImports.listMyVideoImports({ targetUrl: FIXTURE_URLS.youtube })expect(total).to.equal(1)expect(videoImports).to.have.lengthOf(1)@@ -253,7 +254,7 @@ describe('Test video imports', function () {it('Should search in my imports', async function () {{- const { total, data } = await servers[0].videoImports.getMyVideoImports({ search: 'peertube2' })+ const { total, data } = await servers[0].videoImports.listMyVideoImports({ search: 'peertube2' })expect(total).to.equal(1)expect(data).to.have.lengthOf(1)@@ -262,7 +263,7 @@ describe('Test video imports', function () {}{- const { total, data } = await servers[0].videoImports.getMyVideoImports({ search: FIXTURE_URLS.magnet })+ const { total, data } = await servers[0].videoImports.listMyVideoImports({ search: FIXTURE_URLS.magnet })expect(total).to.equal(1)expect(data).to.have.lengthOf(1)@@ -558,7 +559,7 @@ describe('Test video imports', function () {await server.jobs.pauseJobQueue()pendingImportId = await importVideo('pending')- const { data } = await server.videoImports.getMyVideoImports()+ const { data } = await server.videoImports.listMyVideoImports()expect(data).to.have.lengthOf(2)finishedVideo = data.find(i => i.id === finishedImportId).video@@ -567,7 +568,7 @@ describe('Test video imports', function () {it('Should delete a video import', async function () {await server.videoImports.delete({ importId: finishedImportId })- const { data } = await server.videoImports.getMyVideoImports()+ const { data } = await server.videoImports.listMyVideoImports()expect(data).to.have.lengthOf(1)expect(data[0].id).to.equal(pendingImportId)expect(data[0].state.id).to.equal(VideoImportState.PENDING)@@ -582,7 +583,7 @@ describe('Test video imports', function () {it('Should cancel a video import', async function () {await server.videoImports.cancel({ importId: pendingImportId })- const { data } = await server.videoImports.getMyVideoImports()+ const { data } = await server.videoImports.listMyVideoImports()expect(data).to.have.lengthOf(1)expect(data[0].id).to.equal(pendingImportId)expect(data[0].state.id).to.equal(VideoImportState.CANCELLED)@@ -595,7 +596,7 @@ describe('Test video imports', function () {await waitJobs([ server ])- const { data } = await server.videoImports.getMyVideoImports()+ const { data } = await server.videoImports.listMyVideoImports()expect(data).to.have.lengthOf(1)expect(data[0].id).to.equal(pendingImportId)expect(data[0].state.id).to.equal(VideoImportState.CANCELLED)@@ -604,7 +605,7 @@ describe('Test video imports', function () {it('Should delete the cancelled video import', async function () {await server.videoImports.delete({ importId: pendingImportId })- const { data } = await server.videoImports.getMyVideoImports()+ const { data } = await server.videoImports.listMyVideoImports()expect(data).to.have.lengthOf(0)})diff --git a/packages/tests/src/api/videos/video-playlists.ts b/packages/tests/src/api/videos/video-playlists.tsindex 757b5c0761..72823f88b2 100644--- a/packages/tests/src/api/videos/video-playlists.ts+++ b/packages/tests/src/api/videos/video-playlists.ts@@ -3,6 +3,7 @@import { wait } from '@peertube/peertube-core-utils'import {HttpStatusCode,+ ResultList,VideoPlaylist,VideoPlaylistCreateResult,VideoPlaylistElementType,@@ -70,6 +71,7 @@ describe('Test video playlists', function () {let nsfwVideoServer1: numberlet userTokenServer1: string+ let editorToken: stringlet commands: PlaylistsCommand[]@@ -113,6 +115,8 @@ describe('Test video playlists', function () {userTokenServer1 = await servers[0].users.generateUserAndToken('user1')+ editorToken = await servers[0].channelCollaborators.createEditor('editor', 'root_channel')+await waitJobs(servers)})@@ -205,20 +209,23 @@ describe('Test video playlists', function () {it('Should get private playlist for a classic user', async function () {const token = await servers[0].users.generateUserAndToken('toto')- const body = await commands[0].listByAccount({ token, handle: 'toto' })-- expect(body.total).to.equal(1)- expect(body.data).to.have.lengthOf(1)+ for (+ const body of [+ await commands[0].listByAccount({ token, handle: 'toto' }),+ await commands[0].listByAccount({ token, handle: 'toto', sort: 'updatedAt' })+ ]+ ) {+ expect(body.total).to.equal(1)+ expect(body.data).to.have.lengthOf(1)- const playlistId = body.data[0].id- await commands[0].listVideos({ token, playlistId })+ const playlistId = body.data[0].id+ await commands[0].listVideos({ token, playlistId })+ }})})describe('Create and federate playlists', function () {it('Should create a playlist on server 1 and have the playlist on server 2 and 3', async function () {- this.timeout(30000)-await commands[0].create({attributes: {displayName: 'my super playlist',@@ -230,8 +237,6 @@ describe('Test video playlists', function () {})await waitJobs(servers)- // Processing a playlist by the receiver could be long- await wait(3000)for (const server of servers) {const body = await server.playlists.list({ start: 0, count: 5 })@@ -267,8 +272,6 @@ describe('Test video playlists', function () {})it('Should create a playlist on server 2 and have the playlist on server 1 but not on server 3', async function () {- this.timeout(30000)-{const playlist = await servers[1].playlists.create({attributes: {@@ -306,7 +309,6 @@ describe('Test video playlists', function () {}await waitJobs(servers)- await wait(3000)for (const server of [ servers[0], servers[1] ]) {const body = await server.playlists.list({ start: 0, count: 5 })@@ -369,8 +371,8 @@ describe('Test video playlists', function () {it('Should list video channel playlists', async function () {this.timeout(30000)- {- const body = await commands[0].listByChannel({ handle: 'root_channel', start: 0, count: 2, sort: '-createdAt' })+ for (const token of [ undefined, editorToken ]) {+ const body = await commands[0].listByChannel({ handle: 'root_channel', start: 0, count: 2, sort: '-createdAt', token })expect(body.total).to.equal(1)const data = body.data@@ -417,33 +419,64 @@ describe('Test video playlists', function () {expect(data).to.have.lengthOf(0)}})++ it('Should filter on channels when listing account playlists', async function () {+ {+ const { total, data } = await servers[1].playlists.listByAccount({ handle: 'root', channelNameOneOf: [ 'root_channel' ] })+ expect(total).to.equal(2)+ expect(data.map(p => p.displayName)).to.have.members([ 'playlist 2', 'playlist 3' ])+ }++ {+ const { total, data } = await servers[1].playlists.listByAccount({ handle: 'root', channelNameOneOf: [ 'toto' ] })+ expect(total).to.equal(0)+ expect(data).to.have.lengthOf(0)+ }++ {+ const { total, data } = await servers[1].playlists.listByAccount({ handle: 'root', channelNameOneOf: [ 'toto', 'root_channel' ] })+ expect(total).to.equal(2)+ expect(data.map(p => p.displayName)).to.have.members([ 'playlist 2', 'playlist 3' ])+ }+ })})describe('Playlist rights', function () {let unlistedPlaylist: VideoPlaylistCreateResultlet privatePlaylist: VideoPlaylistCreateResult+ let privatePlaylistWithChannel: VideoPlaylistCreateResult++ let editorTokenServer2: string+ let editorServer2AccountId: numberbefore(async function () {this.timeout(30000)- {- unlistedPlaylist = await servers[1].playlists.create({- attributes: {- displayName: 'playlist unlisted',- privacy: VideoPlaylistPrivacy.UNLISTED,- videoChannelId: servers[1].store.channel.id- }- })- }+ unlistedPlaylist = await servers[1].playlists.create({+ attributes: {+ displayName: 'playlist unlisted',+ privacy: VideoPlaylistPrivacy.UNLISTED,+ videoChannelId: servers[1].store.channel.id+ }+ })- {- privatePlaylist = await servers[1].playlists.create({- attributes: {- displayName: 'playlist private',- privacy: VideoPlaylistPrivacy.PRIVATE- }- })- }+ privatePlaylist = await servers[1].playlists.create({+ attributes: {+ displayName: 'playlist private',+ privacy: VideoPlaylistPrivacy.PRIVATE+ }+ })++ privatePlaylistWithChannel = await servers[1].playlists.create({+ attributes: {+ displayName: 'playlist private with channel',+ privacy: VideoPlaylistPrivacy.PRIVATE,+ videoChannelId: servers[1].store.channel.id+ }+ })++ editorTokenServer2 = await servers[1].channelCollaborators.createEditor('editor', 'root_channel')+ editorServer2AccountId = (await servers[1].users.getMyInfo({ token: editorTokenServer2 })).idawait waitJobs(servers)await wait(3000)@@ -452,12 +485,24 @@ describe('Test video playlists', function () {it('Should not list unlisted or private playlists', async function () {for (const server of servers) {const results = [+ await server.playlists.listByChannel({ handle: 'root_channel@' + servers[1].host, sort: '-createdAt' }),await server.playlists.listByAccount({ handle: 'root@' + servers[1].host, sort: '-createdAt' }),++ await server.playlists.listByChannel({+ handle: 'root_channel@' + servers[1].host,+ sort: '-createdAt',+ includeCollaborations: true+ }),+ await server.playlists.listByAccount({ handle: 'root@' + servers[1].host, sort: '-createdAt', includeCollaborations: true }),+await server.playlists.list({ start: 0, count: 2, sort: '-createdAt' })]expect(results[0].total).to.equal(2)- expect(results[1].total).to.equal(3)+ expect(results[1].total).to.equal(2)+ expect(results[2].total).to.equal(2)+ expect(results[3].total).to.equal(2)+ expect(results[4].total).to.equal(3)for (const body of results) {const data = body.data@@ -468,6 +513,106 @@ describe('Test video playlists', function () {}})+ it('Should list unlisted or private playlists with appropriate tokens', async function () {+ const checkAllResult = (result: ResultList<VideoPlaylist>) => {+ expect(result.total).to.equal(6)+ expect(result.data).to.have.lengthOf(6)++ expect(result.data.map(p => p.displayName)).to.have.members([+ 'Watch later',+ 'playlist 2',+ 'playlist 3',+ 'playlist unlisted',+ 'playlist private',+ 'playlist private with channel'+ ])+ }++ // Owner token+ {+ const result = await servers[1].playlists.listByAccount({ handle: 'root@' + servers[1].host, token: servers[1].accessToken })+ checkAllResult(result)+ }++ {+ const result = await servers[1].playlists.listByAccount({+ handle: 'root@' + servers[1].host,+ channelNameOneOf: [ 'root_channel' ],+ token: servers[1].accessToken+ })+ expect(result.total).to.equal(4)+ expect(result.data).to.have.lengthOf(4)++ expect(result.data.map(p => p.displayName)).to.have.members([+ 'playlist 2',+ 'playlist 3',+ 'playlist unlisted',+ 'playlist private with channel'+ ])+ }++ // Editor token+ {+ const result = await servers[1].playlists.listByAccount({+ handle: 'editor@' + servers[1].host,+ token: editorTokenServer2,+ includeCollaborations: false+ })+ expect(result.total).to.equal(1)+ expect(result.data).to.have.lengthOf(1)+ }++ {+ const result = await servers[1].playlists.listByAccount({+ handle: 'editor@' + servers[1].host,+ token: editorTokenServer2,+ includeCollaborations: true+ })++ expect(result.total).to.equal(5)+ expect(result.data).to.have.lengthOf(5)++ expect(result.data.map(p => p.displayName)).to.have.members([+ 'playlist 2',+ 'playlist 3',+ 'playlist unlisted',+ 'playlist private with channel',+ 'Watch later'+ ])++ expect(result.data.find(p => p.type.id === VideoPlaylistType.WATCH_LATER).ownerAccount.id === editorServer2AccountId)+ }++ {+ const result = await servers[1].playlists.listByAccount({+ handle: 'editor@' + servers[1].host,+ channelNameOneOf: [ 'root_channel' ],+ token: editorTokenServer2+ })+ expect(result.total).to.equal(0)+ expect(result.data).to.have.lengthOf(0)+ }++ {+ const result = await servers[1].playlists.listByAccount({+ handle: 'editor@' + servers[1].host,+ channelNameOneOf: [ 'root_channel' ],+ token: editorTokenServer2,+ includeCollaborations: true+ })++ expect(result.total).to.equal(4)+ expect(result.data).to.have.lengthOf(4)++ expect(result.data.map(p => p.displayName)).to.have.members([+ 'playlist 2',+ 'playlist 3',+ 'playlist unlisted',+ 'playlist private with channel'+ ])+ }+ })+it('Should not get unlisted playlist using only the id', async function () {await servers[1].playlists.get({ playlistId: unlistedPlaylist.id, expectedStatus: 404 })})@@ -483,11 +628,22 @@ describe('Test video playlists', function () {}})- it('Should get private playlist with a token', async function () {+ it('Should get private playlist with the owner token', async function () {for (const id of [ privatePlaylist.id, privatePlaylist.uuid, privatePlaylist.shortUUID ]) {await servers[1].playlists.get({ token: servers[1].accessToken, playlistId: id })}})++ it('Should get private playlist with the editor token', async function () {+ for (const id of [ privatePlaylist.id, privatePlaylist.uuid, privatePlaylist.shortUUID ]) {+ await servers[1].playlists.get({ token: editorTokenServer2, playlistId: id, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ }++ for (const id of [ privatePlaylistWithChannel.id, privatePlaylistWithChannel.uuid, privatePlaylistWithChannel.shortUUID ]) {+ await servers[1].playlists.get({ token: editorTokenServer2, playlistId: id })+ await servers[1].playlists.listVideos({ token: editorTokenServer2, playlistId: id })+ }+ })})describe('Update playlists', function () {diff --git a/packages/tests/src/api/videos/video-static-file-privacy.ts b/packages/tests/src/api/videos/video-static-file-privacy.tsindex 0b5c3f27be..fff3b2c006 100644--- a/packages/tests/src/api/videos/video-static-file-privacy.ts+++ b/packages/tests/src/api/videos/video-static-file-privacy.ts@@ -15,12 +15,13 @@ import {waitJobs} from '@peertube/peertube-server-commands'import { expectStartWith } from '@tests/shared/checks.js'-import { checkVideoFileTokenReinjection } from '@tests/shared/streaming-playlists.js'import { magnetUriDecode, parseTorrentVideo } from '@tests/shared/p2p.js'+import { checkVideoFileTokenReinjection } from '@tests/shared/streaming-playlists.js'import { expect } from 'chai'describe('Test video static file privacy', function () {let server: PeerTubeServer+ let editorToken: stringlet userToken: stringbefore(async function () {@@ -30,13 +31,12 @@ describe('Test video static file privacy', function () {await setAccessTokensToServers([ server ])await setDefaultVideoChannel([ server ])- userToken = await server.users.generateUserAndToken('user1')+ userToken = await server.users.generateUserAndToken('user')+ editorToken = await server.channelCollaborators.createEditor('editor', 'root_channel')})describe('VOD static file path', function () {-function runSuite () {-async function checkPrivateFiles (uuid: string) {const video = await server.videos.getWithToken({ id: uuid })@@ -178,7 +178,6 @@ describe('Test video static file privacy', function () {})describe('With transcoding', function () {-before(async function () {await server.config.enableMinimumTranscoding()})@@ -202,30 +201,28 @@ describe('Test video static file privacy', function () {const video = await server.videos.getWithToken({ id })for (const file of getAllFiles(video)) {- await makeRawRequest({ url: file.fileUrl, token, expectedStatus })- await makeRawRequest({ url: file.fileDownloadUrl, token, expectedStatus })+ for (const url of [ file.fileUrl, file.fileDownloadUrl ]) {+ await makeRawRequest({ url, token, expectedStatus })- await makeRawRequest({ url: file.fileUrl, query: { videoFileToken }, expectedStatus })- await makeRawRequest({ url: file.fileDownloadUrl, query: { videoFileToken }, expectedStatus })+ await makeRawRequest({ url, query: { videoFileToken }, expectedStatus })- if (videoPassword) {- const headers = { 'x-peertube-video-password': videoPassword }- await makeRawRequest({ url: file.fileUrl, headers, expectedStatus })- await makeRawRequest({ url: file.fileDownloadUrl, headers, expectedStatus })+ if (videoPassword) {+ const headers = { 'x-peertube-video-password': videoPassword }+ await makeRawRequest({ url, headers, expectedStatus })+ }}}const hls = video.streamingPlaylists[0]- await makeRawRequest({ url: hls.playlistUrl, token, expectedStatus })- await makeRawRequest({ url: hls.segmentsSha256Url, token, expectedStatus })- await makeRawRequest({ url: hls.playlistUrl, query: { videoFileToken }, expectedStatus })- await makeRawRequest({ url: hls.segmentsSha256Url, query: { videoFileToken }, expectedStatus })+ for (const url of [ hls.playlistUrl, hls.segmentsSha256Url ]) {+ await makeRawRequest({ url, token, expectedStatus })+ await makeRawRequest({ url, query: { videoFileToken }, expectedStatus })- if (videoPassword) {- const headers = { 'x-peertube-video-password': videoPassword }- await makeRawRequest({ url: hls.playlistUrl, token: null, headers, expectedStatus })- await makeRawRequest({ url: hls.segmentsSha256Url, token: null, headers, expectedStatus })+ if (videoPassword) {+ const headers = { 'x-peertube-video-password': videoPassword }+ await makeRawRequest({ url, token: null, headers, expectedStatus })+ }}}@@ -236,16 +233,16 @@ describe('Test video static file privacy', function () {unrelatedFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid })})- it('Should not be able to access a private video files without OAuth token and file token', async function () {+ it('Should not be able to access a private video files without user token and file token', async function () {this.timeout(120000)const { uuid } = await server.videos.quickUpload({ name: 'video', privacy: VideoPrivacy.PRIVATE })await waitJobs([ server ])- await checkVideoFiles({ id: uuid, expectedStatus: HttpStatusCode.FORBIDDEN_403, token: null, videoFileToken: null })+ await checkVideoFiles({ id: uuid, expectedStatus: HttpStatusCode.UNAUTHORIZED_401, token: null, videoFileToken: null })})- it('Should not be able to access password protected video files without OAuth token, file token and password', async function () {+ it('Should not be able to access password protected video files without user token, file token and password', async function () {this.timeout(120000)const videoPassword = 'my super password'@@ -258,14 +255,14 @@ describe('Test video static file privacy', function () {await checkVideoFiles({id: uuid,- expectedStatus: HttpStatusCode.FORBIDDEN_403,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401,token: null,videoFileToken: null,videoPassword: null})})- it('Should not be able to access an password video files with incorrect OAuth token, file token and password', async function () {+ it('Should not be able to access an password video files with incorrect user token, file token and password', async function () {this.timeout(120000)const videoPassword = 'my super password'@@ -285,7 +282,7 @@ describe('Test video static file privacy', function () {})})- it('Should not be able to access an private video files without appropriate OAuth token and file token', async function () {+ it('Should not be able to access an private video files without appropriate user token and file token', async function () {this.timeout(120000)const { uuid } = await server.videos.quickUpload({ name: 'video', privacy: VideoPrivacy.PRIVATE })@@ -299,18 +296,20 @@ describe('Test video static file privacy', function () {})})- it('Should be able to access a private video files with appropriate OAuth token or file token', async function () {+ it('Should be able to access a private video files with appropriate user token or file token', async function () {this.timeout(120000)const { uuid } = await server.videos.quickUpload({ name: 'video', privacy: VideoPrivacy.PRIVATE })- const videoFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid })-await waitJobs([ server ])- await checkVideoFiles({ id: uuid, expectedStatus: HttpStatusCode.OK_200, token: server.accessToken, videoFileToken })+ for (const token of [ server.accessToken, editorToken ]) {+ const videoFileToken = await server.videoToken.getVideoFileToken({ videoId: uuid, token })++ await checkVideoFiles({ id: uuid, expectedStatus: HttpStatusCode.OK_200, token, videoFileToken })+ }})- it('Should be able to access a password protected video files with appropriate OAuth token or file token', async function () {+ it('Should be able to access a password protected video files with appropriate user token or file token', async function () {this.timeout(120000)const videoPassword = 'my super password'@@ -325,6 +324,7 @@ describe('Test video static file privacy', function () {await waitJobs([ server ])await checkVideoFiles({ id: uuid, expectedStatus: HttpStatusCode.OK_200, token: server.accessToken, videoFileToken, videoPassword })+ await checkVideoFiles({ id: uuid, expectedStatus: HttpStatusCode.OK_200, token: editorToken, videoFileToken, videoPassword })})it('Should reinject video file token', async function () {@@ -355,7 +355,7 @@ describe('Test video static file privacy', function () {}})- it('Should be able to access a private video of another user with an admin OAuth token or file token', async function () {+ it('Should be able to access a private video of another user with an admin user token or file token', async function () {this.timeout(120000)const { uuid } = await server.videos.quickUpload({ name: 'video', token: userToken, privacy: VideoPrivacy.PRIVATE })@@ -389,6 +389,7 @@ describe('Test video static file privacy', function () {const video = await server.videos.getWithToken({ id: liveId })const fileToken = await server.videoToken.getVideoFileToken({ videoId: video.uuid })+ const editorFileToken = await server.videoToken.getVideoFileToken({ videoId: video.uuid, token: editorToken })const hls = video.streamingPlaylists[0]@@ -398,8 +399,11 @@ describe('Test video static file privacy', function () {await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url, query: { videoFileToken: fileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, token: editorToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: editorFileToken }, expectedStatus: HttpStatusCode.OK_200 })+await makeRawRequest({ url, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })await makeRawRequest({ url, query: { videoFileToken: unrelatedFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })if (videoPassword) {@@ -410,7 +414,6 @@ describe('Test video static file privacy', function () {expectedStatus: HttpStatusCode.FORBIDDEN_403})}-}await stopFfmpeg(ffmpegCommand)@@ -418,6 +421,7 @@ describe('Test video static file privacy', function () {async function checkReplay (replay: VideoDetails) {const fileToken = await server.videoToken.getVideoFileToken({ videoId: replay.uuid })+ const editorFileToken = await server.videoToken.getVideoFileToken({ videoId: replay.uuid, token: editorToken })const hls = replay.streamingPlaylists[0]expect(hls.files).to.not.have.lengthOf(0)@@ -426,8 +430,11 @@ describe('Test video static file privacy', function () {await makeRawRequest({ url: file.fileUrl, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url: file.fileUrl, query: { videoFileToken: fileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url: file.fileUrl, token: editorToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url: file.fileUrl, query: { videoFileToken: editorFileToken }, expectedStatus: HttpStatusCode.OK_200 })+await makeRawRequest({ url: file.fileUrl, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url: file.fileUrl, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url: file.fileUrl, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })await makeRawRequest({url: file.fileUrl,query: { videoFileToken: unrelatedFileToken },@@ -441,8 +448,11 @@ describe('Test video static file privacy', function () {await makeRawRequest({ url, token: server.accessToken, expectedStatus: HttpStatusCode.OK_200 })await makeRawRequest({ url, query: { videoFileToken: fileToken }, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, token: editorToken, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url, query: { videoFileToken: editorFileToken }, expectedStatus: HttpStatusCode.OK_200 })+await makeRawRequest({ url, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })- await makeRawRequest({ url, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 })await makeRawRequest({ url, query: { videoFileToken: unrelatedFileToken }, expectedStatus: HttpStatusCode.FORBIDDEN_403 })}}diff --git a/packages/tests/src/plugins/filter-hooks.ts b/packages/tests/src/plugins/filter-hooks.tsindex c6c3b5d235..f2be66fada 100644--- a/packages/tests/src/plugins/filter-hooks.ts+++ b/packages/tests/src/plugins/filter-hooks.ts@@ -262,7 +262,7 @@ describe('Test plugin filter hooks', function () {await waitJobs(servers){- const body = await servers[0].videoImports.getMyVideoImports()+ const body = await servers[0].videoImports.listMyVideoImports()const videoImports = body.dataconst videoImport = videoImports.find(i => i.id === videoImportId)@@ -291,7 +291,7 @@ describe('Test plugin filter hooks', function () {await waitJobs(servers){- const { data: videoImports } = await servers[0].videoImports.getMyVideoImports()+ const { data: videoImports } = await servers[0].videoImports.listMyVideoImports()const videoImport = videoImports.find(i => i.id === videoImportId)diff --git a/packages/tests/src/server-helpers/mentions.ts b/packages/tests/src/server-helpers/mentions.tsindex 11cb7b6fe1..e95b93b7bb 100644--- a/packages/tests/src/server-helpers/mentions.ts+++ b/packages/tests/src/server-helpers/mentions.ts@@ -8,9 +8,9 @@ describe('Comment model', function () {const text = '@florian @jean@localhost:9000 @flo @another@localhost:9000 @[email protected] hello ' +'email@localhost:9000 coucou.com no? @chocobozzz @chocobozzz @end'- const isOwned = true+ const isLocal = true- const result = extractMentions(text, isOwned).sort((a, b) => a.localeCompare(b))+ const result = extractMentions(text, isLocal).sort((a, b) => a.localeCompare(b))expect(result).to.deep.equal([ 'another', 'chocobozzz', 'end', 'flo', 'florian', 'jean' ])})diff --git a/packages/tests/src/shared/actors.ts b/packages/tests/src/shared/actors.tsindex 02d507a490..f1f102be46 100644--- a/packages/tests/src/shared/actors.ts+++ b/packages/tests/src/shared/actors.ts@@ -1,12 +1,12 @@/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */+import { Account, AccountSummary, HttpStatusCode, VideoChannel, VideoChannelSummary } from '@peertube/peertube-models'+import { makeRawRequest, PeerTubeServer } from '@peertube/peertube-server-commands'import { expect } from 'chai'import { pathExists } from 'fs-extra/esm'import { readdir } from 'fs/promises'-import { Account, VideoChannel } from '@peertube/peertube-models'-import { PeerTubeServer } from '@peertube/peertube-server-commands'-async function expectChannelsFollows (options: {+export async function expectChannelsFollows (options: {server: PeerTubeServerhandle: stringfollowers: number@@ -18,7 +18,7 @@ async function expectChannelsFollows (options: {return expectActorFollow({ ...options, data })}-async function expectAccountFollows (options: {+export async function expectAccountFollows (options: {server: PeerTubeServerhandle: stringfollowers: number@@ -30,7 +30,7 @@ async function expectAccountFollows (options: {return expectActorFollow({ ...options, data })}-async function checkActorFilesWereRemoved (filename: string, server: PeerTubeServer) {+export async function checkActorFilesWereRemoved (filename: string, server: PeerTubeServer) {for (const directory of [ 'avatars' ]) {const directoryPath = server.getDirectoryPath(directory)@@ -44,12 +44,22 @@ async function checkActorFilesWereRemoved (filename: string, server: PeerTubeSer}}-export {- expectAccountFollows,- expectChannelsFollows,- checkActorFilesWereRemoved+export async function checkActorImage (actor: AccountSummary | VideoChannelSummary) {+ expect(actor.avatars).to.have.lengthOf(4)++ for (const avatar of actor.avatars) {+ expect(avatar.createdAt).to.exist+ expect(avatar.fileUrl).to.exist+ expect(avatar.height).to.be.greaterThan(0)+ expect(avatar.width).to.be.greaterThan(0)+ expect(avatar.updatedAt).to.exist++ await makeRawRequest({ url: avatar.fileUrl, expectedStatus: HttpStatusCode.OK_200 })+ }}+// ---------------------------------------------------------------------------+// Private// ---------------------------------------------------------------------------function expectActorFollow (options: {diff --git a/packages/tests/src/shared/import-export.ts b/packages/tests/src/shared/import-export.tsindex c6ab6e97ac..7e98721513 100644--- a/packages/tests/src/shared/import-export.ts+++ b/packages/tests/src/shared/import-export.ts@@ -33,7 +33,7 @@ import { tmpdir } from 'os'import { basename, join, resolve } from 'path'import { testFileExistsOnFSOrNot } from './checks.js'import { MockSmtpServer } from './mock-servers/mock-email.js'-import { getAllNotificationsSettings } from './notifications.js'+import { getAllNotificationsSettings } from './notifications/notifications-common.js'type ExportOutbox = ActivityPubOrderedCollection<ActivityCreate<VideoObject | VideoCommentObject>>diff --git a/packages/tests/src/shared/mock-servers/mock-email.ts b/packages/tests/src/shared/mock-servers/mock-email.tsindex 4093637b94..766b011edd 100644--- a/packages/tests/src/shared/mock-servers/mock-email.ts+++ b/packages/tests/src/shared/mock-servers/mock-email.ts@@ -66,7 +66,7 @@ class MockSmtpServer {async kill () {if (!this.maildev) return- if (this.relayingEmail) {+ if (this.relayingEmail !== undefined) {await this.relayingEmail}diff --git a/packages/tests/src/shared/notifications.ts b/packages/tests/src/shared/notifications.tsdeleted file mode 100644index 39fa4169c7..0000000000--- a/packages/tests/src/shared/notifications.ts+++ /dev/null@@ -1,1036 +0,0 @@-/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */--import {- AbuseState,- AbuseStateType,- PluginType_Type,- UserNotification,- UserNotificationSetting,- UserNotificationSettingValue,- UserNotificationType,- UserNotificationType_Type-} from '@peertube/peertube-models'-import {- ConfigCommand,- PeerTubeServer,- createMultipleServers,- doubleFollow,- setAccessTokensToServers,- setDefaultAccountAvatar,- setDefaultChannelAvatar,- setDefaultVideoChannel,- waitJobs-} from '@peertube/peertube-server-commands'-import { expect } from 'chai'-import { inspect } from 'util'-import { MockSmtpServer } from './mock-servers/index.js'-import { wait } from '@peertube/peertube-core-utils'--type CheckerBaseParams = {- server: PeerTubeServer- emails: any[]- socketNotifications: UserNotification[]- token: string- check?: { web: boolean, mail: boolean }-}--type CheckerType = 'presence' | 'absence'--function getAllNotificationsSettings (): UserNotificationSetting {- return {- newVideoFromSubscription: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- newCommentOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- myVideoImportFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- myVideoPublished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- commentMention: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- newFollow: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- newUserRegistration: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- newInstanceFollower: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- autoInstanceFollowing: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- myVideoStudioEditionFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- newPluginVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL- }-}--async function waitUntilNotification (options: {- server: PeerTubeServer- notificationType: UserNotificationType_Type- token: string- fromDate: Date-}) {- const { server, fromDate, notificationType, token } = options-- do {- const { data } = await server.notifications.list({ start: 0, count: 5, token })- if (data.some(n => n.type === notificationType && new Date(n.createdAt) >= fromDate)) break-- await wait(500)- } while (true)-- await waitJobs([ server ])-}--async function checkNewVideoFromSubscription (- options: CheckerBaseParams & {- videoName: string- shortUUID: string- checkType: CheckerType- }-) {- const { videoName, shortUUID } = options- const notificationType = UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkVideo(notification.video, videoName, shortUUID)- checkActor(notification.video.channel)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n === undefined || n.type !== UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION || n.video.name !== videoName- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']- return text.indexOf(shortUUID) !== -1 && text.indexOf('Your subscription') !== -1- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkNewLiveFromSubscription (- options: CheckerBaseParams & {- videoName: string- shortUUID: string- checkType: CheckerType- }-) {- const { videoName, shortUUID } = options- const notificationType = UserNotificationType.NEW_LIVE_FROM_SUBSCRIPTION-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkVideo(notification.video, videoName, shortUUID)- checkActor(notification.video.channel)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n === undefined || n.type !== UserNotificationType.NEW_LIVE_FROM_SUBSCRIPTION || n.video.name !== videoName- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']- return text.indexOf(shortUUID) !== -1 && text.indexOf('Your subscription') !== -1- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkMyVideoIsPublished (- options: CheckerBaseParams & {- videoName: string- shortUUID: string- checkType: CheckerType- }-) {- const { videoName, shortUUID } = options- const notificationType = UserNotificationType.MY_VIDEO_PUBLISHED-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkVideo(notification.video, videoName, shortUUID)- checkActor(notification.video.channel)- } else {- expect(notification.video).to.satisfy(v => v === undefined || v.name !== videoName)- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']- return text.includes(shortUUID) && text.includes('Your video')- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkVideoStudioEditionIsFinished (- options: CheckerBaseParams & {- videoName: string- shortUUID: string- checkType: CheckerType- }-) {- const { videoName, shortUUID } = options- const notificationType = UserNotificationType.MY_VIDEO_STUDIO_EDITION_FINISHED-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkVideo(notification.video, videoName, shortUUID)- checkActor(notification.video.channel)- } else {- expect(notification.video).to.satisfy(v => v === undefined || v.name !== videoName)- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']- return text.includes(shortUUID) && text.includes('Edition of your video')- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkMyVideoImportIsFinished (- options: CheckerBaseParams & {- videoName: string- shortUUID: string- url: string- success: boolean- checkType: CheckerType- }-) {- const { videoName, shortUUID, url, success } = options-- const notificationType = success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.videoImport.targetUrl).to.equal(url)-- if (success) checkVideo(notification.videoImport.video, videoName, shortUUID)- } else {- expect(notification.videoImport).to.satisfy(i => i === undefined || i.targetUrl !== url)- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']- const toFind = success- ? /\bfinished\b/- : /\berror\b/-- return text.includes(url) && !!text.match(toFind)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--// -----------------------------------------------------------------------------async function checkUserRegistered (- options: CheckerBaseParams & {- username: string- checkType: CheckerType- }-) {- const { username } = options- const notificationType = UserNotificationType.NEW_USER_REGISTRATION-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkActor(notification.account, { withAvatar: false })- expect(notification.account.name).to.equal(username)- } else {- expect(notification).to.satisfy(n => n.type !== notificationType || n.account.name !== username)- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']-- return text.includes(' registered.') && text.includes(username)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkRegistrationRequest (- options: CheckerBaseParams & {- username: string- registrationReason: string- checkType: CheckerType- }-) {- const { username, registrationReason } = options- const notificationType = UserNotificationType.NEW_USER_REGISTRATION_REQUEST-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.registration.username).to.equal(username)- } else {- expect(notification).to.satisfy(n => n.type !== notificationType || n.registration.username !== username)- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']-- return text.includes(' wants to register ') && text.includes(username) && text.includes(registrationReason)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--// -----------------------------------------------------------------------------async function checkNewActorFollow (- options: CheckerBaseParams & {- followType: 'channel' | 'account'- followerName: string- followerDisplayName: string- followingDisplayName: string- checkType: CheckerType- }-) {- const { followType, followerName, followerDisplayName, followingDisplayName } = options- const notificationType = UserNotificationType.NEW_FOLLOW-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkActor(notification.actorFollow.follower)- expect(notification.actorFollow.follower.displayName).to.equal(followerDisplayName)- expect(notification.actorFollow.follower.name).to.equal(followerName)- expect(notification.actorFollow.follower.host).to.not.be.undefined-- const following = notification.actorFollow.following- expect(following.displayName).to.equal(followingDisplayName)- expect(following.type).to.equal(followType)- } else {- expect(notification).to.satisfy(n => {- return n.type !== notificationType ||- (n.actorFollow.follower.name !== followerName && n.actorFollow.following !== followingDisplayName)- })- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']-- return text.includes(followType) && text.includes(followingDisplayName) && text.includes(followerDisplayName)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkNewInstanceFollower (- options: CheckerBaseParams & {- followerHost: string- checkType: CheckerType- }-) {- const { followerHost } = options- const notificationType = UserNotificationType.NEW_INSTANCE_FOLLOWER-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkActor(notification.actorFollow.follower, { withAvatar: false })- expect(notification.actorFollow.follower.name).to.equal('peertube')- expect(notification.actorFollow.follower.host).to.equal(followerHost)-- expect(notification.actorFollow.following.name).to.equal('peertube')- } else {- expect(notification).to.satisfy(n => {- return n.type !== notificationType || n.actorFollow.follower.host !== followerHost- })- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']-- return text.includes('PeerTube has a new follower') && text.includes(followerHost)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkAutoInstanceFollowing (- options: CheckerBaseParams & {- followerHost: string- followingHost: string- checkType: CheckerType- }-) {- const { followerHost, followingHost } = options- const notificationType = UserNotificationType.AUTO_INSTANCE_FOLLOWING-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- const following = notification.actorFollow.following-- checkActor(following, { withAvatar: false })- expect(following.name).to.equal('peertube')- expect(following.host).to.equal(followingHost)-- expect(notification.actorFollow.follower.name).to.equal('peertube')- expect(notification.actorFollow.follower.host).to.equal(followerHost)- } else {- expect(notification).to.satisfy(n => {- return n.type !== notificationType || n.actorFollow.following.host !== followingHost- })- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']-- return text.match(/\bautomatically followed\b/) && text.includes(followingHost)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkCommentMention (- options: CheckerBaseParams & {- shortUUID: string- commentId: number- threadId: number- byAccountDisplayName: string- checkType: CheckerType- }-) {- const { shortUUID, commentId, threadId, byAccountDisplayName } = options- const notificationType = UserNotificationType.COMMENT_MENTION-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkComment(notification.comment, commentId, threadId)- checkActor(notification.comment.account)- expect(notification.comment.account.displayName).to.equal(byAccountDisplayName)-- checkVideo(notification.comment.video, undefined, shortUUID)- } else {- expect(notification).to.satisfy(n => n.type !== notificationType || n.comment.id !== commentId)- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']-- return text.match(/\bmentioned\b/) && text.includes(shortUUID) && text.includes(byAccountDisplayName)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--let lastEmailCount = 0--async function checkNewCommentOnMyVideo (- options: CheckerBaseParams & {- shortUUID: string- commentId: number- threadId: number- checkType: CheckerType- approval?: boolean // default false- }-) {- const { server, shortUUID, commentId, threadId, checkType, emails, approval = false } = options- const notificationType = UserNotificationType.NEW_COMMENT_ON_MY_VIDEO-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- checkComment(notification.comment, commentId, threadId)- checkActor(notification.comment.account)- checkVideo(notification.comment.video, undefined, shortUUID)-- expect(notification.comment.heldForReview).to.equal(approval)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.comment === undefined || n.comment.id !== commentId- })- }- }-- const commentUrl = approval- ? `${server.url}/my-account/videos/comments?search=heldForReview:true`- : `${server.url}/w/${shortUUID};threadId=${threadId}`-- function emailNotificationFinder (email: object) {- const text = email['text']-- return text.includes(commentUrl) &&- (approval && text.includes('requires approval')) ||- (!approval && !text.includes('requires approval'))- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-- if (checkType === 'presence') {- // We cannot detect email duplicates, so check we received another email- expect(emails).to.have.length.above(lastEmailCount)- lastEmailCount = emails.length- }-}--async function checkNewVideoAbuseForModerators (- options: CheckerBaseParams & {- shortUUID: string- videoName: string- checkType: CheckerType- }-) {- const { shortUUID, videoName } = options- const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.abuse.id).to.be.a('number')- checkVideo(notification.abuse.video, videoName, shortUUID)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.abuse === undefined || n.abuse.video.shortUUID !== shortUUID- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']- return text.indexOf(shortUUID) !== -1 && text.indexOf('abuse') !== -1- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkNewAbuseMessage (- options: CheckerBaseParams & {- abuseId: number- message: string- toEmail: string- checkType: CheckerType- }-) {- const { abuseId, message, toEmail } = options- const notificationType = UserNotificationType.ABUSE_NEW_MESSAGE-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.abuse.id).to.equal(abuseId)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n === undefined || n.type !== notificationType || n.abuse === undefined || n.abuse.id !== abuseId- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']- const to = email['to'].filter(t => t.address === toEmail)-- return text.indexOf(message) !== -1 && to.length !== 0- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkAbuseStateChange (- options: CheckerBaseParams & {- abuseId: number- state: AbuseStateType- checkType: CheckerType- }-) {- const { abuseId, state } = options- const notificationType = UserNotificationType.ABUSE_STATE_CHANGE-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.abuse.id).to.equal(abuseId)- expect(notification.abuse.state).to.equal(state)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.abuse === undefined || n.abuse.id !== abuseId- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']-- const contains = state === AbuseState.ACCEPTED- ? ' accepted'- : ' rejected'-- return text.indexOf(contains) !== -1- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkNewCommentAbuseForModerators (- options: CheckerBaseParams & {- shortUUID: string- videoName: string- checkType: CheckerType- }-) {- const { shortUUID, videoName } = options- const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.abuse.id).to.be.a('number')- checkVideo(notification.abuse.comment.video, videoName, shortUUID)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.abuse === undefined || n.abuse.comment.video.shortUUID !== shortUUID- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']- return text.indexOf(shortUUID) !== -1 && text.indexOf('abuse') !== -1- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkNewAccountAbuseForModerators (- options: CheckerBaseParams & {- displayName: string- checkType: CheckerType- }-) {- const { displayName } = options- const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.abuse.id).to.be.a('number')- expect(notification.abuse.account.displayName).to.equal(displayName)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.abuse === undefined || n.abuse.account.displayName !== displayName- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']- return text.indexOf(displayName) !== -1 && text.indexOf('abuse') !== -1- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkVideoAutoBlacklistForModerators (- options: CheckerBaseParams & {- shortUUID: string- videoName: string- checkType: CheckerType- }-) {- const { shortUUID, videoName } = options- const notificationType = UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.videoBlacklist.video.id).to.be.a('number')- checkVideo(notification.videoBlacklist.video, videoName, shortUUID)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.video === undefined || n.video.shortUUID !== shortUUID- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']- return text.indexOf(shortUUID) !== -1 && email['text'].indexOf('moderation/video-blocks/list') !== -1- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkNewBlacklistOnMyVideo (- options: CheckerBaseParams & {- shortUUID: string- videoName: string- blacklistType: 'blacklist' | 'unblacklist'- }-) {- const { videoName, shortUUID, blacklistType } = options- const notificationType = blacklistType === 'blacklist'- ? UserNotificationType.BLACKLIST_ON_MY_VIDEO- : UserNotificationType.UNBLACKLIST_ON_MY_VIDEO-- function notificationChecker (notification: UserNotification) {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- const video = blacklistType === 'blacklist' ? notification.videoBlacklist.video : notification.video-- checkVideo(video, videoName, shortUUID)- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']-- const blacklistReg = blacklistType === 'blacklist'- ? /\bblocked\b/- : /\bunblocked\b/-- return text.includes(shortUUID) && !!text.match(blacklistReg)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder, checkType: 'presence' })-}--async function checkNewPeerTubeVersion (- options: CheckerBaseParams & {- latestVersion: string- checkType: CheckerType- }-) {- const { latestVersion } = options- const notificationType = UserNotificationType.NEW_PEERTUBE_VERSION-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.peertube).to.exist- expect(notification.peertube.latestVersion).to.equal(latestVersion)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.peertube === undefined || n.peertube.latestVersion !== latestVersion- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']-- return text.includes(latestVersion)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkNewPluginVersion (- options: CheckerBaseParams & {- pluginType: PluginType_Type- pluginName: string- checkType: CheckerType- }-) {- const { pluginName, pluginType } = options- const notificationType = UserNotificationType.NEW_PLUGIN_VERSION-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.plugin.name).to.equal(pluginName)- expect(notification.plugin.type).to.equal(pluginType)- } else {- expect(notification).to.satisfy((n: UserNotification) => {- return n?.plugin === undefined || n.plugin.name !== pluginName- })- }- }-- function emailNotificationFinder (email: object) {- const text = email['text']-- return text.includes(pluginName)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function checkMyVideoTranscriptionGenerated (- options: CheckerBaseParams & {- videoName: string- shortUUID: string- language: {- id: string- label: string- }- checkType: CheckerType- }-) {- const { videoName, shortUUID, language } = options- const notificationType = UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED-- function notificationChecker (notification: UserNotification, checkType: CheckerType) {- if (checkType === 'presence') {- expect(notification).to.not.be.undefined- expect(notification.type).to.equal(notificationType)-- expect(notification.videoCaption).to.exist- expect(notification.videoCaption.language.id).to.equal(language.id)- expect(notification.videoCaption.language.label).to.equal(language.label)- checkVideo(notification.videoCaption.video, videoName, shortUUID)- } else {- expect(notification.videoCaption).to.satisfy(c => c === undefined || c.Video.shortUUID !== shortUUID)- }- }-- function emailNotificationFinder (email: object) {- const text: string = email['text']- return text.includes(shortUUID) && text.includes('Transcription in ' + language.label)- }-- await checkNotification({ ...options, notificationChecker, emailNotificationFinder })-}--async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: any = {}) {- const userNotifications: UserNotification[] = []- const adminNotifications: UserNotification[] = []- const adminNotificationsServer2: UserNotification[] = []- const emails: object[] = []-- const port = await MockSmtpServer.Instance.collectEmails(emails)-- const overrideConfig = {- ...ConfigCommand.getEmailOverrideConfig(port),-- signup: {- limit: 20- }- }- const servers = await createMultipleServers(serversCount, Object.assign(overrideConfig, overrideConfigArg))-- await setAccessTokensToServers(servers)- await setDefaultVideoChannel(servers)- await setDefaultChannelAvatar(servers)- await setDefaultAccountAvatar(servers)-- if (servers[1]) {- await servers[1].config.enableStudio()- await servers[1].config.enableLive({ allowReplay: true, transcoding: false })- }-- if (serversCount > 1) {- await doubleFollow(servers[0], servers[1])- }-- const user = { username: 'user_1', password: 'super password' }- await servers[0].users.create({ ...user, videoQuota: 10 * 1000 * 1000 })- const userAccessToken = await servers[0].login.getAccessToken(user)-- await servers[0].notifications.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() })- await servers[0].users.updateMyAvatar({ token: userAccessToken, fixture: 'avatar.png' })- await servers[0].channels.updateImage({ channelName: 'user_1_channel', token: userAccessToken, fixture: 'avatar.png', type: 'avatar' })-- await servers[0].notifications.updateMySettings({ settings: getAllNotificationsSettings() })-- if (serversCount > 1) {- await servers[1].notifications.updateMySettings({ settings: getAllNotificationsSettings() })- }-- {- const socket = servers[0].socketIO.getUserNotificationSocket({ token: userAccessToken })- socket.on('new-notification', n => userNotifications.push(n))- }- {- const socket = servers[0].socketIO.getUserNotificationSocket()- socket.on('new-notification', n => adminNotifications.push(n))- }-- if (serversCount > 1) {- const socket = servers[1].socketIO.getUserNotificationSocket()- socket.on('new-notification', n => adminNotificationsServer2.push(n))- }-- const { videoChannels } = await servers[0].users.getMyInfo()- const channelId = videoChannels[0].id-- return {- userNotifications,- adminNotifications,- adminNotificationsServer2,- userAccessToken,- emails,- servers,- channelId,- baseOverrideConfig: overrideConfig- }-}--// -----------------------------------------------------------------------------export {- type CheckerType,- type CheckerBaseParams,- getAllNotificationsSettings,- waitUntilNotification,- checkMyVideoImportIsFinished,- checkUserRegistered,- checkAutoInstanceFollowing,- checkMyVideoIsPublished,- checkNewLiveFromSubscription,- checkNewVideoFromSubscription,- checkNewActorFollow,- checkNewCommentOnMyVideo,- checkNewBlacklistOnMyVideo,- checkCommentMention,- checkNewVideoAbuseForModerators,- checkVideoAutoBlacklistForModerators,- checkNewAbuseMessage,- checkAbuseStateChange,- checkNewInstanceFollower,- prepareNotificationsTest,- checkNewCommentAbuseForModerators,- checkNewAccountAbuseForModerators,- checkNewPeerTubeVersion,- checkNewPluginVersion,- checkVideoStudioEditionIsFinished,- checkRegistrationRequest,- checkMyVideoTranscriptionGenerated-}--// -----------------------------------------------------------------------------async function checkNotification (- options: CheckerBaseParams & {- notificationChecker: (notification: UserNotification, checkType: CheckerType) => void- emailNotificationFinder: (email: object) => boolean- checkType: CheckerType- }-) {- const { server, token, checkType, notificationChecker, emailNotificationFinder, socketNotifications, emails } = options-- const check = options.check || { web: true, mail: true }-- if (check.web) {- const notification = await server.notifications.getLatest({ token })-- if (notification || checkType !== 'absence') {- notificationChecker(notification, checkType)- }-- const socketNotification = socketNotifications.find(n => {- try {- notificationChecker(n, 'presence')- return true- } catch {- return false- }- })-- if (checkType === 'presence') {- const obj = inspect(socketNotifications, { depth: 5 })- expect(socketNotification, 'The socket notification is absent when it should be present. ' + obj).to.not.be.undefined- } else {- const obj = inspect(socketNotification, { depth: 5 })- expect(socketNotification, 'The socket notification is present when it should not be present. ' + obj).to.be.undefined- }- }-- if (check.mail) {- // Last email- const email = emails.slice()- .reverse()- .find(e => emailNotificationFinder(e))-- if (checkType === 'presence') {- const texts = emails.map(e => e.text)- expect(email, 'The email is absent when is should be present. ' + inspect(texts)).to.not.be.undefined- } else {- expect(email, 'The email is present when is should not be present. ' + inspect(email)).to.be.undefined- }- }-}--function checkVideo (video: any, videoName?: string, shortUUID?: string) {- if (videoName) {- expect(video.name).to.be.a('string')- expect(video.name).to.not.be.empty- expect(video.name).to.equal(videoName)- }-- if (shortUUID) {- expect(video.shortUUID).to.be.a('string')- expect(video.shortUUID).to.not.be.empty- expect(video.shortUUID).to.equal(shortUUID)- }-- expect(video.state).to.exist- expect(video.id).to.be.a('number')-}--function checkActor (actor: any, options: { withAvatar?: boolean } = {}) {- const { withAvatar = true } = options-- expect(actor.displayName).to.be.a('string')- expect(actor.displayName).to.not.be.empty- expect(actor.host).to.not.be.undefined-- if (withAvatar) {- expect(actor.avatars).to.be.an('array')- expect(actor.avatars).to.have.lengthOf(4)- expect(actor.avatars[0].path).to.exist.and.not.empty- }-}--function checkComment (comment: any, commentId: number, threadId: number) {- expect(comment.id).to.equal(commentId)- expect(comment.threadId).to.equal(threadId)-}diff --git a/packages/tests/src/shared/notifications/check-admin-notifications.ts b/packages/tests/src/shared/notifications/check-admin-notifications.tsnew file mode 100644index 0000000000..8ff828f881--- /dev/null+++ b/packages/tests/src/shared/notifications/check-admin-notifications.ts@@ -0,0 +1,70 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { PluginType_Type, UserNotification, UserNotificationType } from '@peertube/peertube-models'+import { expect } from 'chai'+import { CheckerBaseParams, CheckerType, checkNotification } from './shared/notification-checker.js'++export async function checkNewPeerTubeVersion (+ options: CheckerBaseParams & {+ latestVersion: string+ checkType: CheckerType+ }+) {+ const { latestVersion } = options+ const notificationType = UserNotificationType.NEW_PEERTUBE_VERSION++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.peertube).to.exist+ expect(notification.peertube.latestVersion).to.equal(latestVersion)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.peertube === undefined || n.peertube.latestVersion !== latestVersion+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']++ return text.includes(latestVersion)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkNewPluginVersion (+ options: CheckerBaseParams & {+ pluginType: PluginType_Type+ pluginName: string+ checkType: CheckerType+ }+) {+ const { pluginName, pluginType } = options+ const notificationType = UserNotificationType.NEW_PLUGIN_VERSION++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.plugin.name).to.equal(pluginName)+ expect(notification.plugin.type).to.equal(pluginType)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.plugin === undefined || n.plugin.name !== pluginName+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']++ return text.includes(pluginName)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}diff --git a/packages/tests/src/shared/notifications/check-channel-notifications.ts b/packages/tests/src/shared/notifications/check-channel-notifications.tsnew file mode 100644index 0000000000..cc89d7814f--- /dev/null+++ b/packages/tests/src/shared/notifications/check-channel-notifications.ts@@ -0,0 +1,164 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import {+ UserNotification,+ UserNotificationType,+ UserNotificationType_Type,+ VideoChannelCollaboratorState,+ VideoChannelCollaboratorStateType+} from '@peertube/peertube-models'+import { expect } from 'chai'+import { checkActor, CheckerBaseParams, CheckerType, checkNotification } from './shared/notification-checker.js'++export type CheckChannelCollaboratorOptions = CheckerBaseParams & {+ channelDisplayName: string+ targetDisplayName: string+ sourceDisplayName: string+ checkType: CheckerType+ to: string+}++export async function checkInvitedToCollaborateToChannel (options: CheckChannelCollaboratorOptions) {+ const { channelDisplayName, targetDisplayName, sourceDisplayName, to } = options+ const notificationType = UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ checkCollaboratorNotification({+ notification,+ notificationType,+ channelDisplayName,+ targetDisplayName,+ sourceDisplayName,+ state: VideoChannelCollaboratorState.PENDING+ })+ } else {+ expect(notification).to.satisfy(c => isNotificationAbsent(c))+ }+ }++ function emailNotificationFinder (email: object) {+ if (email['to'][0]['address'] !== to) return false++ const text: string = email['text']+ return text.includes(`${sourceDisplayName} invited you`) &&+ text.includes(`of channel ${channelDisplayName}`)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkAcceptedToCollaborateToChannel (options: CheckChannelCollaboratorOptions) {+ const { channelDisplayName, targetDisplayName, sourceDisplayName, to } = options+ const notificationType = UserNotificationType.ACCEPTED_TO_COLLABORATE_TO_CHANNEL++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ checkCollaboratorNotification({+ notification,+ notificationType,+ channelDisplayName,+ targetDisplayName,+ sourceDisplayName,+ state: VideoChannelCollaboratorState.ACCEPTED+ })+ } else {+ expect(notification).to.satisfy(c => isNotificationAbsent(c))+ }+ }++ function emailNotificationFinder (email: object) {+ if (email['to'][0]['address'] !== to) return false++ const text: string = email['text']+ return text.includes(`${targetDisplayName} accepted`) &&+ text.includes(`of ${channelDisplayName}`)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkRefusedToCollaborateToChannel (options: CheckChannelCollaboratorOptions) {+ const { channelDisplayName, targetDisplayName, sourceDisplayName, to } = options+ const notificationType = UserNotificationType.REFUSED_TO_COLLABORATE_TO_CHANNEL++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ checkCollaboratorNotification({+ notification,+ notificationType,+ channelDisplayName,+ targetDisplayName,+ sourceDisplayName,+ state: VideoChannelCollaboratorState.REJECTED+ })+ } else {+ expect(notification).to.satisfy(c => isNotificationAbsent(c))+ }+ }++ function emailNotificationFinder (email: object) {+ if (email['to'][0]['address'] !== to) return false++ const text: string = email['text']+ return text.includes(`${targetDisplayName} refused`) &&+ text.includes(`of ${channelDisplayName}`)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------++function checkCollaboratorNotification (options: {+ notification: UserNotification+ notificationType: UserNotificationType_Type+ channelDisplayName: string+ targetDisplayName: string+ sourceDisplayName: string+ state?: VideoChannelCollaboratorStateType+}) {+ const { channelDisplayName, targetDisplayName, notificationType, notification, state, sourceDisplayName } = options++ expect(notification).to.exist+ expect(notification.type).to.equal(notificationType)++ const collaborator = notification.videoChannelCollaborator++ expect(collaborator.channel.avatars).to.have.lengthOf(4)+ expect(collaborator.account.avatars).to.have.lengthOf(4)+ expect(collaborator.id).to.exist+ expect(collaborator.state.id).to.equal(state)+ expect(collaborator.account.displayName).to.equal(targetDisplayName)+ expect(collaborator.channel.displayName).to.equal(channelDisplayName)+ expect(collaborator.channelOwner.displayName).to.equal(sourceDisplayName)++ expect(collaborator.account.name).to.exist+ expect(collaborator.channel.name).to.exist+ expect(collaborator.channelOwner.name).to.exist++ checkActor(collaborator.account)+ checkActor(collaborator.channel)+}++function isNotificationAbsent (options: {+ notification: UserNotification+ notificationType: UserNotificationType_Type+ channelDisplayName: string+ targetDisplayName: string+}) {+ const { notification: n, notificationType, channelDisplayName, targetDisplayName } = options++ if (!n) return true+ if (!n.videoChannelCollaborator) return true+ if (n.type !== notificationType) return true++ if (+ n.videoChannelCollaborator.account.displayName !== targetDisplayName &&+ n.videoChannelCollaborator.channel.displayName !== channelDisplayName+ ) return true++ return false+}diff --git a/packages/tests/src/shared/notifications/check-comment-notifications.ts b/packages/tests/src/shared/notifications/check-comment-notifications.tsnew file mode 100644index 0000000000..0bfe82742c--- /dev/null+++ b/packages/tests/src/shared/notifications/check-comment-notifications.ts@@ -0,0 +1,93 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { UserNotification, UserNotificationType } from '@peertube/peertube-models'+import { expect } from 'chai'+import { checkActor, checkComment, CheckerBaseParams, CheckerType, checkNotification, checkVideo } from './shared/notification-checker.js'++export async function checkCommentMention (+ options: CheckerBaseParams & {+ shortUUID: string+ commentId: number+ threadId: number+ byAccountDisplayName: string+ checkType: CheckerType+ }+) {+ const { shortUUID, commentId, threadId, byAccountDisplayName } = options+ const notificationType = UserNotificationType.COMMENT_MENTION++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkComment(notification.comment, commentId, threadId)+ checkActor(notification.comment.account)+ expect(notification.comment.account.displayName).to.equal(byAccountDisplayName)++ checkVideo(notification.comment.video, undefined, shortUUID)+ } else {+ expect(notification).to.satisfy(n => n.type !== notificationType || n.comment.id !== commentId)+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ return text.match(/\bmentioned\b/) && text.includes(shortUUID) && text.includes(byAccountDisplayName)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++let lastEmailCount = 0++export async function checkNewCommentOnMyVideo (+ options: CheckerBaseParams & {+ shortUUID: string+ commentId: number+ threadId: number+ checkType: CheckerType+ approval?: boolean // default false+ }+) {+ const { server, shortUUID, commentId, threadId, checkType, emails, approval = false } = options+ const notificationType = UserNotificationType.NEW_COMMENT_ON_MY_VIDEO++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkComment(notification.comment, commentId, threadId)+ checkActor(notification.comment.account)+ checkVideo(notification.comment.video, undefined, shortUUID)++ expect(notification.comment.heldForReview).to.equal(approval)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.comment === undefined || n.comment.id !== commentId+ })+ }+ }++ const commentUrl = approval+ ? `${server.url}/my-account/videos/comments?search=heldForReview:true`+ : `${server.url}/w/${shortUUID};threadId=${threadId}`++ function emailNotificationFinder (email: object) {+ const text = email['text']++ return text.includes(commentUrl) &&+ (approval && text.includes('requires approval')) ||+ (!approval && !text.includes('requires approval'))+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })++ if (checkType === 'presence') {+ // We cannot detect email duplicates, so check we received another email+ expect(emails).to.have.length.above(lastEmailCount)+ lastEmailCount = emails.length+ }+}diff --git a/packages/tests/src/shared/notifications/check-follow-notifications.ts b/packages/tests/src/shared/notifications/check-follow-notifications.tsnew file mode 100644index 0000000000..fffe236c44--- /dev/null+++ b/packages/tests/src/shared/notifications/check-follow-notifications.ts@@ -0,0 +1,121 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { UserNotification, UserNotificationType } from '@peertube/peertube-models'+import { expect } from 'chai'+import { checkActor, CheckerBaseParams, CheckerType, checkNotification } from './shared/notification-checker.js'++export async function checkNewActorFollow (+ options: CheckerBaseParams & {+ followType: 'channel' | 'account'+ followerName: string+ followerDisplayName: string+ followingDisplayName: string+ checkType: CheckerType+ }+) {+ const { followType, followerName, followerDisplayName, followingDisplayName } = options+ const notificationType = UserNotificationType.NEW_FOLLOW++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkActor(notification.actorFollow.follower)+ expect(notification.actorFollow.follower.displayName).to.equal(followerDisplayName)+ expect(notification.actorFollow.follower.name).to.equal(followerName)+ expect(notification.actorFollow.follower.host).to.not.be.undefined++ const following = notification.actorFollow.following+ expect(following.displayName).to.equal(followingDisplayName)+ expect(following.type).to.equal(followType)+ } else {+ expect(notification).to.satisfy(n => {+ return n.type !== notificationType ||+ (n.actorFollow.follower.name !== followerName && n.actorFollow.following !== followingDisplayName)+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ return text.includes(followType) && text.includes(followingDisplayName) && text.includes(followerDisplayName)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkNewInstanceFollower (+ options: CheckerBaseParams & {+ followerHost: string+ checkType: CheckerType+ }+) {+ const { followerHost } = options+ const notificationType = UserNotificationType.NEW_INSTANCE_FOLLOWER++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkActor(notification.actorFollow.follower, { withAvatar: false })+ expect(notification.actorFollow.follower.name).to.equal('peertube')+ expect(notification.actorFollow.follower.host).to.equal(followerHost)++ expect(notification.actorFollow.following.name).to.equal('peertube')+ } else {+ expect(notification).to.satisfy(n => {+ return n.type !== notificationType || n.actorFollow.follower.host !== followerHost+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ return text.includes('PeerTube has a new follower') && text.includes(followerHost)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkAutoInstanceFollowing (+ options: CheckerBaseParams & {+ followerHost: string+ followingHost: string+ checkType: CheckerType+ }+) {+ const { followerHost, followingHost } = options+ const notificationType = UserNotificationType.AUTO_INSTANCE_FOLLOWING++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ const following = notification.actorFollow.following++ checkActor(following, { withAvatar: false })+ expect(following.name).to.equal('peertube')+ expect(following.host).to.equal(followingHost)++ expect(notification.actorFollow.follower.name).to.equal('peertube')+ expect(notification.actorFollow.follower.host).to.equal(followerHost)+ } else {+ expect(notification).to.satisfy(n => {+ return n.type !== notificationType || n.actorFollow.following.host !== followingHost+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ return text.match(/\bautomatically followed\b/) && text.includes(followingHost)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}diff --git a/packages/tests/src/shared/notifications/check-moderation-notifications.ts b/packages/tests/src/shared/notifications/check-moderation-notifications.tsnew file mode 100644index 0000000000..a75788a7eb--- /dev/null+++ b/packages/tests/src/shared/notifications/check-moderation-notifications.ts@@ -0,0 +1,297 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { AbuseState, AbuseStateType, UserNotification, UserNotificationType } from '@peertube/peertube-models'+import { expect } from 'chai'+import { checkActor, CheckerBaseParams, CheckerType, checkNotification, checkVideo } from './shared/notification-checker.js'++export async function checkNewVideoAbuseForModerators (+ options: CheckerBaseParams & {+ shortUUID: string+ videoName: string+ checkType: CheckerType+ }+) {+ const { shortUUID, videoName } = options+ const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.abuse.id).to.be.a('number')+ checkVideo(notification.abuse.video, videoName, shortUUID)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.abuse === undefined || n.abuse.video.shortUUID !== shortUUID+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']+ return text.indexOf(shortUUID) !== -1 && text.indexOf('abuse') !== -1+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkNewAbuseMessage (+ options: CheckerBaseParams & {+ abuseId: number+ message: string+ toEmail: string+ checkType: CheckerType+ }+) {+ const { abuseId, message, toEmail } = options+ const notificationType = UserNotificationType.ABUSE_NEW_MESSAGE++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.abuse.id).to.equal(abuseId)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n === undefined || n.type !== notificationType || n.abuse === undefined || n.abuse.id !== abuseId+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']+ const to = email['to'].filter(t => t.address === toEmail)++ return text.indexOf(message) !== -1 && to.length !== 0+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkAbuseStateChange (+ options: CheckerBaseParams & {+ abuseId: number+ state: AbuseStateType+ checkType: CheckerType+ }+) {+ const { abuseId, state } = options+ const notificationType = UserNotificationType.ABUSE_STATE_CHANGE++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.abuse.id).to.equal(abuseId)+ expect(notification.abuse.state).to.equal(state)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.abuse === undefined || n.abuse.id !== abuseId+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']++ const contains = state === AbuseState.ACCEPTED+ ? ' accepted'+ : ' rejected'++ return text.indexOf(contains) !== -1+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkNewCommentAbuseForModerators (+ options: CheckerBaseParams & {+ shortUUID: string+ videoName: string+ checkType: CheckerType+ }+) {+ const { shortUUID, videoName } = options+ const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.abuse.id).to.be.a('number')+ checkVideo(notification.abuse.comment.video, videoName, shortUUID)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.abuse === undefined || n.abuse.comment.video.shortUUID !== shortUUID+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']+ return text.indexOf(shortUUID) !== -1 && text.indexOf('abuse') !== -1+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkNewAccountAbuseForModerators (+ options: CheckerBaseParams & {+ displayName: string+ checkType: CheckerType+ }+) {+ const { displayName } = options+ const notificationType = UserNotificationType.NEW_ABUSE_FOR_MODERATORS++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.abuse.id).to.be.a('number')+ expect(notification.abuse.account.displayName).to.equal(displayName)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.abuse === undefined || n.abuse.account.displayName !== displayName+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']+ return text.indexOf(displayName) !== -1 && text.indexOf('abuse') !== -1+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkVideoAutoBlacklistForModerators (+ options: CheckerBaseParams & {+ shortUUID: string+ videoName: string+ checkType: CheckerType+ }+) {+ const { shortUUID, videoName } = options+ const notificationType = UserNotificationType.VIDEO_AUTO_BLACKLIST_FOR_MODERATORS++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.videoBlacklist.video.id).to.be.a('number')+ checkVideo(notification.videoBlacklist.video, videoName, shortUUID)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n?.video === undefined || n.video.shortUUID !== shortUUID+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']+ return text.indexOf(shortUUID) !== -1 && email['text'].indexOf('moderation/video-blocks/list') !== -1+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkNewBlacklistOnMyVideo (+ options: CheckerBaseParams & {+ shortUUID: string+ videoName: string+ blacklistType: 'blacklist' | 'unblacklist'+ }+) {+ const { videoName, shortUUID, blacklistType } = options+ const notificationType = blacklistType === 'blacklist'+ ? UserNotificationType.BLACKLIST_ON_MY_VIDEO+ : UserNotificationType.UNBLACKLIST_ON_MY_VIDEO++ function notificationChecker (notification: UserNotification) {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ const video = blacklistType === 'blacklist' ? notification.videoBlacklist.video : notification.video++ checkVideo(video, videoName, shortUUID)+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ const blacklistReg = blacklistType === 'blacklist'+ ? /\bblocked\b/+ : /\bunblocked\b/++ return text.includes(shortUUID) && !!text.match(blacklistReg)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder, checkType: 'presence' })+}++export async function checkUserRegistered (+ options: CheckerBaseParams & {+ username: string+ checkType: CheckerType+ }+) {+ const { username } = options+ const notificationType = UserNotificationType.NEW_USER_REGISTRATION++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkActor(notification.account, { withAvatar: false })+ expect(notification.account.name).to.equal(username)+ } else {+ expect(notification).to.satisfy(n => n.type !== notificationType || n.account.name !== username)+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ return text.includes(' registered.') && text.includes(username)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkRegistrationRequest (+ options: CheckerBaseParams & {+ username: string+ registrationReason: string+ checkType: CheckerType+ }+) {+ const { username, registrationReason } = options+ const notificationType = UserNotificationType.NEW_USER_REGISTRATION_REQUEST++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.registration.username).to.equal(username)+ } else {+ expect(notification).to.satisfy(n => n.type !== notificationType || n.registration.username !== username)+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ return text.includes(' wants to register ') && text.includes(username) && text.includes(registrationReason)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}diff --git a/packages/tests/src/shared/notifications/check-video-notifications.ts b/packages/tests/src/shared/notifications/check-video-notifications.tsnew file mode 100644index 0000000000..06ddb08922--- /dev/null+++ b/packages/tests/src/shared/notifications/check-video-notifications.ts@@ -0,0 +1,203 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { UserNotification, UserNotificationType } from '@peertube/peertube-models'+import { expect } from 'chai'+import { checkActor, CheckerBaseParams, CheckerType, checkNotification, checkVideo } from './shared/notification-checker.js'++export async function checkNewVideoFromSubscription (+ options: CheckerBaseParams & {+ videoName: string+ shortUUID: string+ checkType: CheckerType+ }+) {+ const { videoName, shortUUID } = options+ const notificationType = UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkVideo(notification.video, videoName, shortUUID)+ checkActor(notification.video.channel)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n === undefined || n.type !== UserNotificationType.NEW_VIDEO_FROM_SUBSCRIPTION || n.video.name !== videoName+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']+ return text.indexOf(shortUUID) !== -1 && text.indexOf('Your subscription') !== -1+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkNewLiveFromSubscription (+ options: CheckerBaseParams & {+ videoName: string+ shortUUID: string+ checkType: CheckerType+ }+) {+ const { videoName, shortUUID } = options+ const notificationType = UserNotificationType.NEW_LIVE_FROM_SUBSCRIPTION++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkVideo(notification.video, videoName, shortUUID)+ checkActor(notification.video.channel)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ return n === undefined || n.type !== UserNotificationType.NEW_LIVE_FROM_SUBSCRIPTION || n.video.name !== videoName+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text = email['text']+ return text.indexOf(shortUUID) !== -1 && text.indexOf('Your subscription') !== -1+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkMyVideoIsPublished (+ options: CheckerBaseParams & {+ videoName: string+ shortUUID: string+ checkType: CheckerType+ }+) {+ const { videoName, shortUUID } = options+ const notificationType = UserNotificationType.MY_VIDEO_PUBLISHED++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkVideo(notification.video, videoName, shortUUID)+ checkActor(notification.video.channel)+ } else {+ expect(notification.video).to.satisfy(v => v === undefined || v.name !== videoName)+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']+ return text.includes(shortUUID) && text.includes('Your video')+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkVideoStudioEditionIsFinished (+ options: CheckerBaseParams & {+ videoName: string+ shortUUID: string+ checkType: CheckerType+ }+) {+ const { videoName, shortUUID } = options+ const notificationType = UserNotificationType.MY_VIDEO_STUDIO_EDITION_FINISHED++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ checkVideo(notification.video, videoName, shortUUID)+ checkActor(notification.video.channel)+ } else {+ expect(notification.video).to.satisfy(v => v === undefined || v.name !== videoName)+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']+ return text.includes(shortUUID) && text.includes('Edition of your video')+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkMyVideoImportIsFinished (+ options: CheckerBaseParams & {+ videoName: string+ shortUUID: string+ url: string+ success: boolean+ checkType: CheckerType+ }+) {+ const { videoName, shortUUID, url, success } = options++ const notificationType = success ? UserNotificationType.MY_VIDEO_IMPORT_SUCCESS : UserNotificationType.MY_VIDEO_IMPORT_ERROR++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.videoImport.targetUrl).to.equal(url)++ if (success) checkVideo(notification.videoImport.video, videoName, shortUUID)+ } else {+ expect(notification.videoImport).to.satisfy(i => i === undefined || i.targetUrl !== url)+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']+ const toFind = success+ ? /\bfinished\b/+ : /\berror\b/++ return text.includes(url) && !!text.match(toFind)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}++export async function checkMyVideoTranscriptionGenerated (+ options: CheckerBaseParams & {+ videoName: string+ shortUUID: string+ language: {+ id: string+ label: string+ }+ checkType: CheckerType+ }+) {+ const { videoName, shortUUID, language } = options+ const notificationType = UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.videoCaption).to.exist+ expect(notification.videoCaption.language.id).to.equal(language.id)+ expect(notification.videoCaption.language.label).to.equal(language.label)+ checkVideo(notification.videoCaption.video, videoName, shortUUID)+ } else {+ expect(notification.videoCaption).to.satisfy(c => c === undefined || c.Video.shortUUID !== shortUUID)+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']+ return text.includes(shortUUID) && text.includes('Transcription in ' + language.label)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}diff --git a/packages/tests/src/shared/notifications/notifications-common.ts b/packages/tests/src/shared/notifications/notifications-common.tsnew file mode 100644index 0000000000..7901351d48--- /dev/null+++ b/packages/tests/src/shared/notifications/notifications-common.ts@@ -0,0 +1,137 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { wait } from '@peertube/peertube-core-utils'+import {+ UserNotification,+ UserNotificationSetting,+ UserNotificationSettingValue,+ UserNotificationType_Type+} from '@peertube/peertube-models'+import {+ ConfigCommand,+ createMultipleServers,+ doubleFollow,+ PeerTubeServer,+ setAccessTokensToServers,+ setDefaultAccountAvatar,+ setDefaultChannelAvatar,+ setDefaultVideoChannel,+ waitJobs+} from '@peertube/peertube-server-commands'+import { MockSmtpServer } from '../mock-servers/mock-email.js'++export function getAllNotificationsSettings (): UserNotificationSetting {+ return {+ newVideoFromSubscription: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ newCommentOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ abuseAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ videoAutoBlacklistAsModerator: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ blacklistOnMyVideo: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ myVideoImportFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ myVideoPublished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ commentMention: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ newFollow: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ newUserRegistration: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ newInstanceFollower: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ abuseNewMessage: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ abuseStateChange: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ autoInstanceFollowing: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ myVideoStudioEditionFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ newPluginVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ }+}++export async function waitUntilNotification (options: {+ server: PeerTubeServer+ notificationType: UserNotificationType_Type+ token: string+ fromDate: Date+}) {+ const { server, fromDate, notificationType, token } = options++ do {+ const { data } = await server.notifications.list({ start: 0, count: 5, token })+ if (data.some(n => n.type === notificationType && new Date(n.createdAt) >= fromDate)) break++ await wait(500)+ } while (true)++ await waitJobs([ server ])+}++export async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: any = {}) {+ const userNotifications: UserNotification[] = []+ const adminNotifications: UserNotification[] = []+ const adminNotificationsServer2: UserNotification[] = []+ const emails: object[] = []++ const port = await MockSmtpServer.Instance.collectEmails(emails)++ const overrideConfig = {+ ...ConfigCommand.getEmailOverrideConfig(port),++ signup: {+ limit: 20+ }+ }+ const servers = await createMultipleServers(serversCount, Object.assign(overrideConfig, overrideConfigArg))++ await setAccessTokensToServers(servers)+ await setDefaultVideoChannel(servers)+ await setDefaultChannelAvatar(servers)+ await setDefaultAccountAvatar(servers)++ if (servers[1]) {+ await servers[1].config.enableStudio()+ await servers[1].config.enableLive({ allowReplay: true, transcoding: false })+ }++ if (serversCount > 1) {+ await doubleFollow(servers[0], servers[1])+ }++ const user = { username: 'user_1', password: 'super password' }+ await servers[0].users.create({ ...user, videoQuota: 10 * 1000 * 1000 })+ const userAccessToken = await servers[0].login.getAccessToken(user)+ await servers[0].users.updateMe({ token: userAccessToken, displayName: 'User 1' })++ await servers[0].notifications.updateMySettings({ token: userAccessToken, settings: getAllNotificationsSettings() })+ await servers[0].users.updateMyAvatar({ token: userAccessToken, fixture: 'avatar.png' })+ await servers[0].channels.updateImage({ channelName: 'user_1_channel', token: userAccessToken, fixture: 'avatar.png', type: 'avatar' })++ await servers[0].notifications.updateMySettings({ settings: getAllNotificationsSettings() })++ if (serversCount > 1) {+ await servers[1].notifications.updateMySettings({ settings: getAllNotificationsSettings() })+ }++ {+ const socket = servers[0].socketIO.getUserNotificationSocket({ token: userAccessToken })+ socket.on('new-notification', n => userNotifications.push(n))+ }+ {+ const socket = servers[0].socketIO.getUserNotificationSocket()+ socket.on('new-notification', n => adminNotifications.push(n))+ }++ if (serversCount > 1) {+ const socket = servers[1].socketIO.getUserNotificationSocket()+ socket.on('new-notification', n => adminNotificationsServer2.push(n))+ }++ const { videoChannels } = await servers[0].users.getMyInfo()+ const channelId = videoChannels[0].id++ return {+ userNotifications,+ adminNotifications,+ adminNotificationsServer2,+ userAccessToken,+ emails,+ servers,+ channelId,+ baseOverrideConfig: overrideConfig+ }+}diff --git a/packages/tests/src/shared/notifications/shared/notification-checker.ts b/packages/tests/src/shared/notifications/shared/notification-checker.tsnew file mode 100644index 0000000000..b2667ae59d--- /dev/null+++ b/packages/tests/src/shared/notifications/shared/notification-checker.ts@@ -0,0 +1,108 @@+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { UserNotification } from '@peertube/peertube-models'+import { PeerTubeServer } from '@peertube/peertube-server-commands'+import { expect } from 'chai'+import { inspect } from 'util'++export type CheckerBaseParams = {+ server: PeerTubeServer+ emails: any[]+ socketNotifications: UserNotification[]+ token: string+ check?: { web: boolean, mail: boolean }+}++export type CheckerType = 'presence' | 'absence'++export async function checkNotification (+ options: CheckerBaseParams & {+ notificationChecker: (notification: UserNotification, checkType: CheckerType) => void+ emailNotificationFinder: (email: object) => boolean+ checkType: CheckerType+ }+) {+ const { server, token, checkType, notificationChecker, emailNotificationFinder, socketNotifications, emails } = options++ const check = options.check || { web: true, mail: true }++ if (check.web) {+ const notification = await server.notifications.getLatest({ token })++ if (notification || checkType !== 'absence') {+ notificationChecker(notification, checkType)+ }++ const socketNotification = socketNotifications.find(n => {+ try {+ notificationChecker(n, 'presence')+ return true+ } catch {+ return false+ }+ })++ if (checkType === 'presence') {+ const obj = inspect(socketNotifications, { depth: 5 })+ expect(socketNotification, 'The socket notification is absent when it should be present. ' + obj).to.not.be.undefined+ } else {+ const obj = inspect(socketNotification, { depth: 5 })+ expect(socketNotification, 'The socket notification is present when it should not be present. ' + obj).to.be.undefined+ }+ }++ if (check.mail) {+ // Last email+ const email = emails.slice()+ .reverse()+ .map(e => ({+ ...e,++ text: (e.text as string).replaceAll('\n', ' ')+ }))+ .find(e => emailNotificationFinder(e))++ if (checkType === 'presence') {+ const texts = emails.map(e => (e.text as string).replaceAll('\n', ' '))+ expect(email, 'The email is absent when is should be present. ' + inspect(texts)).to.not.be.undefined+ } else {+ expect(email, 'The email is present when is should not be present. ' + inspect(email)).to.be.undefined+ }+ }+}++export function checkVideo (video: any, videoName?: string, shortUUID?: string) {+ if (videoName) {+ expect(video.name).to.be.a('string')+ expect(video.name).to.not.be.empty+ expect(video.name).to.equal(videoName)+ }++ if (shortUUID) {+ expect(video.shortUUID).to.be.a('string')+ expect(video.shortUUID).to.not.be.empty+ expect(video.shortUUID).to.equal(shortUUID)+ }++ expect(video.state).to.exist+ expect(video.id).to.be.a('number')+}++export function checkActor (actor: any, options: { withAvatar?: boolean } = {}) {+ const { withAvatar = true } = options++ expect(actor.displayName).to.be.a('string')+ expect(actor.displayName).to.not.be.empty+ expect(actor.host).to.not.be.undefined++ if (withAvatar) {+ expect(actor.avatars).to.be.an('array')+ expect(actor.avatars).to.have.lengthOf(4)+ expect(actor.avatars[0].path).to.exist.and.not.empty+ }+}++export function checkComment (comment: any, commentId: number, threadId: number) {+ expect(comment.id).to.equal(commentId)+ expect(comment.threadId).to.equal(threadId)+}diff --git a/server/core/controllers/activitypub/client.ts b/server/core/controllers/activitypub/client.tsindex 3391f96ede..98a902fcd9 100644--- a/server/core/controllers/activitypub/client.ts+++ b/server/core/controllers/activitypub/client.ts@@ -61,28 +61,28 @@ activityPubClientRouter.get([ '/accounts?/:handle', '/accounts?/:handle/video-channels', '/a/:handle', '/a/:handle/video-channels' ],executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: false })),asyncMiddleware(accountController))activityPubClientRouter.get('/accounts?/:handle/followers',executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: false })),asyncMiddleware(accountFollowersController))activityPubClientRouter.get('/accounts?/:handle/following',executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: false })),asyncMiddleware(accountFollowingController))activityPubClientRouter.get('/accounts?/:handle/playlists',executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: false })),asyncMiddleware(accountPlaylistsController))activityPubClientRouter.get(@@ -212,35 +212,35 @@ activityPubClientRouter.get([ '/video-channels/:handle', '/video-channels/:handle/videos', '/c/:handle', '/c/:handle/videos' ],executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(videoChannelController))activityPubClientRouter.get('/video-channels/:handle/followers',executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(videoChannelFollowersController))activityPubClientRouter.get('/video-channels/:handle/following',executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(videoChannelFollowingController))activityPubClientRouter.get('/video-channels/:handle/playlists',executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(videoChannelPlaylistsController))activityPubClientRouter.get('/video-channels/:handle/player-settings',executeIfActivityPub,activityPubRateLimiter,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(channelPlayerSettingsController))@@ -462,7 +462,7 @@ async function videoCommentController (req: express.Request, res: express.Responconst videoComment = res.locals.videoCommentFullif (redirectIfNotOwned(videoComment.url, res)) return- if (videoComment.Video.isOwned() && videoComment.heldForReview === true) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)+ if (videoComment.Video.isLocal() && videoComment.heldForReview === true) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)const threadParentComments = await VideoCommentModel.listThreadParentComments({ comment: videoComment })@@ -484,7 +484,7 @@ async function videoCommentController (req: express.Request, res: express.Responasync function videoCommentApprovedController (req: express.Request, res: express.Response) {const comment = res.locals.videoCommentFull- if (!comment.Video.isOwned() || comment.heldForReview === true) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)+ if (!comment.Video.isLocal() || comment.heldForReview === true) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)const activity = buildApprovalActivity({ comment, type: 'ApproveReply' })diff --git a/server/core/controllers/activitypub/inbox.ts b/server/core/controllers/activitypub/inbox.tsindex cfbf2d2fa9..6d9777bdbb 100644--- a/server/core/controllers/activitypub/inbox.ts+++ b/server/core/controllers/activitypub/inbox.ts@@ -29,7 +29,7 @@ inboxRouter.post(activityPubRateLimiter,signatureValidator,asyncMiddleware(checkSignature),- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: false })),asyncMiddleware(activityPubValidator),inboxController)@@ -39,7 +39,7 @@ inboxRouter.post(activityPubRateLimiter,signatureValidator,asyncMiddleware(checkSignature),- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(activityPubValidator),inboxController)diff --git a/server/core/controllers/activitypub/outbox.ts b/server/core/controllers/activitypub/outbox.tsindex 40f36151d2..525f9214bf 100644--- a/server/core/controllers/activitypub/outbox.ts+++ b/server/core/controllers/activitypub/outbox.ts@@ -23,7 +23,7 @@ outboxRouter.get('/accounts/:handle/outbox',activityPubRateLimiter,apPaginationValidator,- accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: false }),+ accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: false }),asyncMiddleware(outboxController))@@ -31,7 +31,7 @@ outboxRouter.get('/video-channels/:handle/outbox',activityPubRateLimiter,apPaginationValidator,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(outboxController))diff --git a/server/core/controllers/api/accounts.ts b/server/core/controllers/api/accounts.tsindex 7aafc6e085..69cc6e3b41 100644--- a/server/core/controllers/api/accounts.ts+++ b/server/core/controllers/api/accounts.ts@@ -1,4 +1,4 @@-import { VideoPlaylistsListQuery } from '@peertube/peertube-models'+import { VideoPlaylistForAccountListQuery } from '@peertube/peertube-models'import { pickCommonVideoQuery } from '@server/helpers/query.js'import { ActorFollowModel } from '@server/models/actor/actor-follow.js'import { getServerActor } from '@server/models/application/application.js'@@ -26,12 +26,17 @@ import {accountHandleGetValidatorFactory,accountsFollowersSortValidator,accountsSortValidator,+ listAccountChannelsSyncValidator,+ listAccountChannelsValidator,videoChannelsSortValidator,- videoChannelStatsValidator,videoChannelSyncsSortValidator,videosSortValidator} from '../../middlewares/validators/index.js'-import { commonVideoPlaylistFiltersValidator, videoPlaylistsSearchValidator } from '../../middlewares/validators/videos/video-playlists.js'+import {+ commonVideoPlaylistFiltersValidator,+ videoPlaylistsAccountValidator,+ videoPlaylistsSearchValidator+} from '../../middlewares/validators/videos/video-playlists.js'import { AccountVideoRateModel } from '../../models/account/account-video-rate.js'import { AccountModel } from '../../models/account/account.js'import { guessAdditionalAttributesFromQuery } from '../../models/video/formatter/index.js'@@ -54,13 +59,13 @@ accountsRouter.get(accountsRouter.get('/:handle',- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkCanManage: false })),getAccount)accountsRouter.get('/:handle/videos',- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkCanManage: false })),paginationValidator,videosSortValidator,setDefaultVideosSort,@@ -72,8 +77,8 @@ accountsRouter.get(accountsRouter.get('/:handle/video-channels',- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkManage: false })),- videoChannelStatsValidator,+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkCanManage: false })),+ listAccountChannelsValidator,paginationValidator,videoChannelsSortValidator,setDefaultSort,@@ -84,31 +89,33 @@ accountsRouter.get(accountsRouter.get('/:handle/video-playlists',optionalAuthenticate,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkCanManage: false })),paginationValidator,videoPlaylistsSortValidator,setDefaultSort,setDefaultPagination,commonVideoPlaylistFiltersValidator,videoPlaylistsSearchValidator,+ videoPlaylistsAccountValidator,asyncMiddleware(listAccountPlaylists))accountsRouter.get('/:handle/video-channel-syncs',authenticate,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: true })),paginationValidator,videoChannelSyncsSortValidator,setDefaultSort,setDefaultPagination,+ listAccountChannelsSyncValidator,asyncMiddleware(listAccountChannelsSync))accountsRouter.get('/:handle/ratings',authenticate,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: true })),paginationValidator,videoRatesSortValidator,setDefaultSort,@@ -120,7 +127,7 @@ accountsRouter.get(accountsRouter.get('/:handle/followers',authenticate,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: true, checkCanManage: true })),paginationValidator,accountsFollowersSortValidator,setDefaultSort,@@ -153,16 +160,15 @@ async function listAccounts (req: express.Request, res: express.Response) {}async function listAccountChannels (req: express.Request, res: express.Response) {- const options = {+ const resultList = await VideoChannelModel.listByAccountForAPI({accountId: res.locals.account.id,start: req.query.start,count: req.query.count,sort: req.query.sort,withStats: req.query.withStats,+ includeCollaborations: req.query.includeCollaborations,search: req.query.search- }-- const resultList = await VideoChannelModel.listByAccountForAPI(options)+ })return res.json(getFormattedObjects(resultList.data, resultList.total))}@@ -173,7 +179,8 @@ async function listAccountChannelsSync (req: express.Request, res: express.Respostart: req.query.start,count: req.query.count,sort: req.query.sort,- search: req.query.search+ search: req.query.search,+ includeCollaborations: req.query.includeCollaborations}const resultList = await VideoChannelSyncModel.listByAccountForAPI(options)@@ -183,7 +190,7 @@ async function listAccountChannelsSync (req: express.Request, res: express.Respoasync function listAccountPlaylists (req: express.Request, res: express.Response) {const serverActor = await getServerActor()- const query = req.query as VideoPlaylistsListQuery+ const query = req.query as VideoPlaylistForAccountListQuery// Allow users to see their private/unlisted video playlistslet listMyPlaylists = false@@ -204,7 +211,13 @@ async function listAccountPlaylists (req: express.Request, res: express.Responsesort: query.sort,search: query.search,- type: query.playlistType+ type: query.playlistType,++ channelNameOneOf: req.query.channelNameOneOf,++ includeCollaborationsForAccount: listMyPlaylists && query.includeCollaborations+ ? res.locals.oauth.token.User.Account.id+ : undefined})return res.json(getFormattedObjects(resultList.data, resultList.total))@@ -260,7 +273,7 @@ async function listAccountRatings (req: express.Request, res: express.Response)async function listAccountFollowers (req: express.Request, res: express.Response) {const account = res.locals.account- const channels = await VideoChannelModel.listAllByAccount(account.id)+ const channels = await VideoChannelModel.listAllOwnedByAccount(account.id)const actorIds = [ account.actorId ].concat(channels.map(c => c.actorId))const resultList = await ActorFollowModel.listFollowersForApi({diff --git a/server/core/controllers/api/bulk.ts b/server/core/controllers/api/bulk.tsindex 829482b4a1..a8b6c9c47e 100644--- a/server/core/controllers/api/bulk.ts+++ b/server/core/controllers/api/bulk.ts@@ -9,11 +9,7 @@ const bulkRouter = express.Router()bulkRouter.use(apiRateLimiter)-bulkRouter.post('/remove-comments-of',- authenticate,- asyncMiddleware(bulkRemoveCommentsOfValidator),- asyncMiddleware(bulkRemoveCommentsOf)-)+bulkRouter.post('/remove-comments-of', authenticate, asyncMiddleware(bulkRemoveCommentsOfValidator), asyncMiddleware(bulkRemoveCommentsOf))// ---------------------------------------------------------------------------@@ -28,8 +24,8 @@ async function bulkRemoveCommentsOf (req: express.Request, res: express.Responseconst body = req.body as BulkRemoveCommentsOfBodyconst user = res.locals.oauth.token.User- const filter = body.scope === 'my-videos'- ? { onVideosOfAccount: user.Account }+ const filter = body.scope === 'my-videos' || body.scope === 'my-videos-and-collaborations'+ ? { onVideosOfAccount: user.Account, includeCollaborations: body.scope === 'my-videos-and-collaborations' }: {}const comments = await VideoCommentModel.listForBulkDelete(account, filter)diff --git a/server/core/controllers/api/index.ts b/server/core/controllers/api/index.tsindex a0a35b951b..8c541f77f8 100644--- a/server/core/controllers/api/index.ts+++ b/server/core/controllers/api/index.ts@@ -21,7 +21,7 @@ import { searchRouter } from './search/index.js'import { serverRouter } from './server/index.js'import { usersRouter } from './users/index.js'import { videoChannelSyncRouter } from './video-channel-sync.js'-import { videoChannelRouter } from './video-channel.js'+import { videoChannelRouter } from './video-channels/index.js'import { videoPlaylistRouter } from './video-playlist.js'import { videosRouter } from './videos/index.js'import { watchedWordsRouter } from './watched-words.js'diff --git a/server/core/controllers/api/player-settings.ts b/server/core/controllers/api/player-settings.tsindex 1475dfef2a..4155c965e6 100644--- a/server/core/controllers/api/player-settings.ts+++ b/server/core/controllers/api/player-settings.ts@@ -1,4 +1,5 @@import { PlayerChannelSettingsUpdate, PlayerVideoSettingsUpdate } from '@peertube/peertube-models'+import { sendUpdateChannelPlayerSettings, sendUpdateVideoPlayerSettings } from '@server/lib/activitypub/send/send-update.js'import { upsertPlayerSettings } from '@server/lib/player-settings.js'import {getChannelPlayerSettingsValidator,@@ -15,7 +16,6 @@ import {optionalAuthenticate,videoChannelsHandleValidatorFactory} from '../../middlewares/index.js'-import { sendUpdateChannelPlayerSettings, sendUpdateVideoPlayerSettings } from '@server/lib/activitypub/send/send-update.js'const playerSettingsRouter = express.Router()@@ -39,15 +39,15 @@ playerSettingsRouter.put(playerSettingsRouter.get('/video-channels/:handle',optionalAuthenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkManage: false })),- getChannelPlayerSettingsValidator,+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkCanManage: false, checkIsOwner: false })),+ asyncMiddleware(getChannelPlayerSettingsValidator),asyncMiddleware(getChannelPlayerSettings))playerSettingsRouter.put('/video-channels/:handle',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),updatePlayerSettingsValidatorFactory('channel'),asyncMiddleware(updateChannelPlayerSettings))diff --git a/server/core/controllers/api/search/search-video-channels.ts b/server/core/controllers/api/search/search-video-channels.tsindex 920b1a07a6..e263eb5522 100644--- a/server/core/controllers/api/search/search-video-channels.ts+++ b/server/core/controllers/api/search/search-video-channels.ts@@ -29,7 +29,8 @@ import { searchLocalUrl } from './shared/index.js'const searchChannelsRouter = express.Router()-searchChannelsRouter.get('/video-channels',+searchChannelsRouter.get(+ '/video-channels',openapiOperationDoc({ operationId: 'searchChannels' }),paginationValidator,setDefaultPagination,@@ -102,7 +103,7 @@ async function searchVideoChannelsDB (query: VideoChannelsSearchQueryAfterSaniti}, 'filter:api.search.video-channels.local.list.params')const resultList = await Hooks.wrapPromiseFun(- VideoChannelModel.searchForApi.bind(VideoChannelModel),+ VideoChannelModel.listForApi.bind(VideoChannelModel),apiOptions,'filter:api.search.video-channels.local.list.result')diff --git a/server/core/controllers/api/users/me.ts b/server/core/controllers/api/users/me.tsindex 5cd494617d..cf6e592c91 100644--- a/server/core/controllers/api/users/me.ts+++ b/server/core/controllers/api/users/me.ts@@ -38,9 +38,9 @@ import { updateAvatarValidator } from '../../../middlewares/validators/actor-imaimport {commonVideosFiltersValidator,deleteMeValidator,- getMyVideoImportsValidator,+ listMyVideoImportsValidator,listCommentsOnUserVideosValidator,- usersVideosValidator,+ listMyVideosValidator,videoImportsSortValidator,videosSortValidator} from '../../../middlewares/validators/index.js'@@ -56,10 +56,10 @@ const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_const meRouter = express.Router()-meRouter.get('/me', authenticate, asyncMiddleware(getUserInformation))+meRouter.get('/me', authenticate, asyncMiddleware(getMyInformation))meRouter.delete('/me', authenticate, deleteMeValidator, asyncMiddleware(deleteMe))-meRouter.get('/me/video-quota-used', authenticate, asyncMiddleware(getUserVideoQuotaUsed))+meRouter.get('/me/video-quota-used', authenticate, asyncMiddleware(getMyVideoQuotaUsed))meRouter.get('/me/videos/imports',@@ -68,8 +68,8 @@ meRouter.get(videoImportsSortValidator,setDefaultSort,setDefaultPagination,- getMyVideoImportsValidator,- asyncMiddleware(getUserVideoImports)+ listMyVideoImportsValidator,+ asyncMiddleware(listMyVideoImports))meRouter.get(@@ -91,15 +91,15 @@ meRouter.get(setDefaultVideosSort,setDefaultPagination,commonVideosFiltersValidator,- asyncMiddleware(usersVideosValidator),- asyncMiddleware(listUserVideos)+ asyncMiddleware(listMyVideosValidator),+ asyncMiddleware(listMyVideos))meRouter.get('/me/videos/:videoId/rating',authenticate,asyncMiddleware(usersVideoRatingValidator),- asyncMiddleware(getUserVideoRating)+ asyncMiddleware(getMyVideoRating))meRouter.put(@@ -131,7 +131,7 @@ export {// ----------------------------------------------------------------------------async function listUserVideos (req: express.Request, res: express.Response) {+async function listMyVideos (req: express.Request, res: express.Response) {const user = res.locals.oauth.token.Userconst countVideos = getCountVideos(req)const query = pickCommonVideoQuery(req.query)@@ -139,25 +139,29 @@ async function listUserVideos (req: express.Request, res: express.Response) {const include = (query.include || VideoInclude.NONE) | VideoInclude.BLACKLISTED | VideoInclude.NOT_PUBLISHED_STATE |VideoInclude.BLOCKED_OWNER- const apiOptions = await Hooks.wrapObject({- privacyOneOf: getAllPrivacies(),+ const apiOptions = await Hooks.wrapObject(+ {+ privacyOneOf: getAllPrivacies(),- ...query,+ ...query,- // Display all- nsfw: null,+ // Display all+ nsfw: null,- user,- accountId: user.Account.id,- displayOnlyForFollower: null,+ user,+ accountId: user.Account.id,+ displayOnlyForFollower: null,- videoChannelId: res.locals.videoChannel?.id,- channelNameOneOf: req.query.channelNameOneOf,+ videoChannelId: res.locals.videoChannel?.id,+ channelNameOneOf: req.query.channelNameOneOf,+ includeCollaborations: req.query.includeCollaborations || false,- countVideos,+ countVideos,- include- }, 'filter:api.user.me.videos.list.params')+ include+ } satisfies Parameters<typeof VideoModel.listForApi>[0],+ 'filter:api.user.me.videos.list.params'+ )const resultList = await Hooks.wrapPromiseFun(VideoModel.listForApi.bind(VideoModel),@@ -171,7 +175,7 @@ async function listUserVideos (req: express.Request, res: express.Response) {async function listCommentsOnUserVideos (req: express.Request, res: express.Response) {const userAccount = res.locals.oauth.token.User.Account- const options = {+ const resultList = await VideoCommentModel.listForApi({...pick(req.query, ['start','count',@@ -183,14 +187,15 @@ async function listCommentsOnUserVideos (req: express.Request, res: express.Resp]),autoTagOfAccountId: userAccount.id,+videoAccountOwnerId: userAccount.id,+ videoAccountOwnerIncludeCollaborations: req.query.includeCollaborations || false,+heldForReview: req.query.isHeldForReview,videoChannelOwnerId: res.locals.videoChannel?.id,videoId: res.locals.videoAll?.id- }-- const resultList = await VideoCommentModel.listCommentsForApi(options)+ })return res.json({total: resultList.total,@@ -198,18 +203,22 @@ async function listCommentsOnUserVideos (req: express.Request, res: express.Resp})}-async function getUserVideoImports (req: express.Request, res: express.Response) {+async function listMyVideoImports (req: express.Request, res: express.Response) {const user = res.locals.oauth.token.Userconst resultList = await VideoImportModel.listUserVideoImportsForApi({userId: user.id,- ...pick(req.query, [ 'targetUrl', 'start', 'count', 'sort', 'search', 'videoChannelSyncId' ])+ collaborationAccountId: req.query.includeCollaborations+ ? user.Account.id+ : undefined,++ ...pick(req.query, [ 'targetUrl', 'start', 'count', 'sort', 'search', 'videoChannelSyncId', 'includeCollaborations' ])})return res.json(getFormattedObjects(resultList.data, resultList.total))}-async function getUserInformation (req: express.Request, res: express.Response) {+async function getMyInformation (req: express.Request, res: express.Response) {// We did not load channels in res.locals.userconst user = await UserModel.loadForMeAPI(res.locals.oauth.token.user.id)@@ -222,7 +231,7 @@ async function getUserInformation (req: express.Request, res: express.Response)return res.json(result)}-async function getUserVideoQuotaUsed (req: express.Request, res: express.Response) {+async function getMyVideoQuotaUsed (req: express.Request, res: express.Response) {const user = res.locals.oauth.token.userconst videoQuotaUsed = await getOriginalVideoFileTotalFromUser(user)const videoQuotaUsedDaily = await getOriginalVideoFileTotalDailyFromUser(user)@@ -234,7 +243,7 @@ async function getUserVideoQuotaUsed (req: express.Request, res: express.Responsreturn res.json(data)}-async function getUserVideoRating (req: express.Request, res: express.Response) {+async function getMyVideoRating (req: express.Request, res: express.Response) {const videoId = res.locals.videoId.idconst accountId = +res.locals.oauth.token.User.Account.iddiff --git a/server/core/controllers/api/video-channel.ts b/server/core/controllers/api/video-channels/index.tssimilarity index 88%rename from server/core/controllers/api/video-channel.tsrename to server/core/controllers/api/video-channels/index.tsindex 9791820876..61eb53a9d0 100644--- a/server/core/controllers/api/video-channel.ts+++ b/server/core/controllers/api/video-channels/index.ts@@ -3,8 +3,8 @@ import {HttpStatusCode,VideoChannelCreate,VideoChannelUpdate,+ VideoPlaylistForAccountListQuery,VideoPlaylistReorder,- VideoPlaylistsListQuery,VideosImportInChannelCreate} from '@peertube/peertube-models'import { pickCommonVideoQuery } from '@server/helpers/query.js'@@ -14,17 +14,17 @@ import { ActorFollowModel } from '@server/models/actor/actor-follow.js'import { getServerActor } from '@server/models/application/application.js'import { MChannelBannerAccountDefault } from '@server/types/models/index.js'import express from 'express'-import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger.js'-import { resetSequelizeInstance } from '../../helpers/database-utils.js'-import { buildNSFWFilters, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils.js'-import { logger } from '../../helpers/logger.js'-import { getFormattedObjects } from '../../helpers/utils.js'-import { MIMETYPES } from '../../initializers/constants.js'-import { sequelizeTypescript } from '../../initializers/database.js'-import { sendUpdateActor } from '../../lib/activitypub/send/index.js'-import { JobQueue } from '../../lib/job-queue/index.js'-import { deleteLocalActorImageFile, updateLocalActorImageFiles } from '../../lib/local-actor.js'-import { createLocalVideoChannelWithoutKeys, federateAllVideosOfChannel } from '../../lib/video-channel.js'+import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../../helpers/audit-logger.js'+import { resetSequelizeInstance } from '../../../helpers/database-utils.js'+import { buildNSFWFilters, createReqFiles, getCountVideos, isUserAbleToSearchRemoteURI } from '../../../helpers/express-utils.js'+import { logger } from '../../../helpers/logger.js'+import { getFormattedObjects } from '../../../helpers/utils.js'+import { MIMETYPES } from '../../../initializers/constants.js'+import { sequelizeTypescript } from '../../../initializers/database.js'+import { sendUpdateActor } from '../../../lib/activitypub/send/index.js'+import { JobQueue } from '../../../lib/job-queue/index.js'+import { deleteLocalActorImageFile, updateLocalActorImageFiles } from '../../../lib/local-actor.js'+import { createLocalVideoChannelWithoutKeys, federateAllVideosOfChannel } from '../../../lib/video-channel.js'import {apiRateLimiter,asyncMiddleware,@@ -41,8 +41,8 @@ import {videoChannelsSortValidator,videoChannelsUpdateValidator,videoPlaylistsSortValidator-} from '../../middlewares/index.js'-import { updateAvatarValidator, updateBannerValidator } from '../../middlewares/validators/actor-image.js'+} from '../../../middlewares/index.js'+import { updateAvatarValidator, updateBannerValidator } from '../../../middlewares/validators/actor-image.js'import {ensureChannelOwnerCanUpload,videoChannelImportVideosValidator,@@ -50,16 +50,17 @@ import {videoChannelsHandleValidatorFactory,videoChannelsListValidator,videosSortValidator-} from '../../middlewares/validators/index.js'+} from '../../../middlewares/validators/index.js'import {commonVideoPlaylistFiltersValidator,videoPlaylistsReorderInChannelValidator-} from '../../middlewares/validators/videos/video-playlists.js'-import { AccountModel } from '../../models/account/account.js'-import { guessAdditionalAttributesFromQuery } from '../../models/video/formatter/index.js'-import { VideoChannelModel } from '../../models/video/video-channel.js'-import { VideoPlaylistModel } from '../../models/video/video-playlist.js'-import { VideoModel } from '../../models/video/video.js'+} from '../../../middlewares/validators/videos/video-playlists.js'+import { AccountModel } from '../../../models/account/account.js'+import { guessAdditionalAttributesFromQuery } from '../../../models/video/formatter/index.js'+import { VideoChannelModel } from '../../../models/video/video-channel.js'+import { VideoPlaylistModel } from '../../../models/video/video-playlist.js'+import { VideoModel } from '../../../models/video/video.js'+import { channelCollaborators } from './video-channel-collaborators.js'const auditLogger = auditLoggerFactory('channels')const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)@@ -68,6 +69,7 @@ const reqBannerFile = createReqFiles([ 'bannerfile' ], MIMETYPES.IMAGE.MIMETYPE_const videoChannelRouter = express.Router()videoChannelRouter.use(apiRateLimiter)+videoChannelRouter.use(channelCollaborators)videoChannelRouter.get('/',@@ -85,7 +87,7 @@ videoChannelRouter.post('/:handle/avatar/pick',authenticate,reqAvatarFile,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),updateAvatarValidator,asyncMiddleware(updateVideoChannelAvatar))@@ -94,7 +96,7 @@ videoChannelRouter.post('/:handle/banner/pick',authenticate,reqBannerFile,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),updateBannerValidator,asyncMiddleware(updateVideoChannelBanner))@@ -102,21 +104,21 @@ videoChannelRouter.post(videoChannelRouter.delete('/:handle/avatar',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),asyncMiddleware(deleteVideoChannelAvatar))videoChannelRouter.delete('/:handle/banner',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),asyncMiddleware(deleteVideoChannelBanner))videoChannelRouter.put('/:handle',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),videoChannelsUpdateValidator,asyncRetryTransactionMiddleware(updateVideoChannel))@@ -124,14 +126,14 @@ videoChannelRouter.put(videoChannelRouter.delete('/:handle',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: true })),asyncMiddleware(videoChannelsRemoveValidator),asyncRetryTransactionMiddleware(removeVideoChannel))videoChannelRouter.get('/:handle',- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkCanManage: false, checkIsOwner: false })),asyncMiddleware(getVideoChannel))@@ -140,7 +142,7 @@ videoChannelRouter.get(videoChannelRouter.get('/:handle/video-playlists',optionalAuthenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkCanManage: false, checkIsOwner: false })),paginationValidator,videoPlaylistsSortValidator,setDefaultSort,@@ -152,7 +154,7 @@ videoChannelRouter.get(videoChannelRouter.post('/:handle/video-playlists/reorder',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),asyncMiddleware(videoPlaylistsReorderInChannelValidator),asyncRetryTransactionMiddleware(reorderPlaylistsInChannel))@@ -161,7 +163,7 @@ videoChannelRouter.post(videoChannelRouter.get('/:handle/videos',- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkManage: false })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkCanManage: false, checkIsOwner: false })),paginationValidator,videosSortValidator,setDefaultVideosSort,@@ -174,7 +176,7 @@ videoChannelRouter.get(videoChannelRouter.get('/:handle/followers',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: false, checkCanManage: true, checkIsOwner: false })),paginationValidator,videoChannelsFollowersSortValidator,setDefaultSort,@@ -185,7 +187,7 @@ videoChannelRouter.get(videoChannelRouter.post('/:handle/import-videos',authenticate,- asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkManage: true })),+ asyncMiddleware(videoChannelsHandleValidatorFactory({ checkIsLocal: true, checkCanManage: true, checkIsOwner: false })),asyncMiddleware(videoChannelImportVideosValidator),asyncMiddleware(ensureChannelOwnerCanUpload),asyncMiddleware(importVideosInChannel)@@ -384,7 +386,7 @@ async function getVideoChannel (req: express.Request, res: express.Response) {async function listVideoChannelPlaylists (req: express.Request, res: express.Response) {const serverActor = await getServerActor()- const { count, playlistType, sort, start, search } = req.query as VideoPlaylistsListQuery+ const { count, playlistType, sort, start, search } = req.query as VideoPlaylistForAccountListQueryconst videoChannel = res.locals.videoChannel// Allow users to see their private/unlisted video playlistsdiff --git a/server/core/controllers/api/video-channels/video-channel-collaborators.ts b/server/core/controllers/api/video-channels/video-channel-collaborators.tsnew file mode 100644index 0000000000..d75626f19c--- /dev/null+++ b/server/core/controllers/api/video-channels/video-channel-collaborators.ts@@ -0,0 +1,128 @@+import { HttpStatusCode, VideoChannelCollaboratorState } from '@peertube/peertube-models'+import { deleteInTransactionWithRetries, retryTransactionWrapper, saveInTransactionWithRetries } from '@server/helpers/database-utils.js'+import { getFormattedObjects } from '@server/helpers/utils.js'+import { CONFIG } from '@server/initializers/config.js'+import { sequelizeTypescript } from '@server/initializers/database.js'+import { Notifier } from '@server/lib/notifier/notifier.js'+import {+ channelAcceptOrRejectInviteCollaboratorsValidator,+ channelDeleteCollaboratorsValidator,+ channelInviteCollaboratorsValidator,+ channelListCollaboratorsValidator+} from '@server/middlewares/validators/videos/video-channel-collaborators.js'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'+import { MChannelCollaboratorAccount } from '@server/types/models/index.js'+import express from 'express'+import { asyncMiddleware, authenticate } from '../../../middlewares/index.js'++const channelCollaborators = express.Router()++channelCollaborators.get(+ '/:handle/collaborators',+ authenticate,+ asyncMiddleware(channelListCollaboratorsValidator),+ asyncMiddleware(listCollaborators)+)++channelCollaborators.post(+ '/:handle/collaborators/invite',+ authenticate,+ asyncMiddleware(channelInviteCollaboratorsValidator),+ asyncMiddleware(inviteCollaborator)+)++channelCollaborators.post(+ '/:handle/collaborators/:collaboratorId/accept',+ authenticate,+ asyncMiddleware(channelAcceptOrRejectInviteCollaboratorsValidator),+ asyncMiddleware(acceptCollaboratorInvite)+)++channelCollaborators.post(+ '/:handle/collaborators/:collaboratorId/reject',+ authenticate,+ asyncMiddleware(channelAcceptOrRejectInviteCollaboratorsValidator),+ asyncMiddleware(rejectCollaboratorInvite)+)++channelCollaborators.delete(+ '/:handle/collaborators/:collaboratorId',+ authenticate,+ asyncMiddleware(channelDeleteCollaboratorsValidator),+ asyncMiddleware(removeCollaborator)+)++// ---------------------------------------------------------------------------++export {+ channelCollaborators+}++// ---------------------------------------------------------------------------++async function listCollaborators (req: express.Request, res: express.Response) {+ const resultList = await VideoChannelCollaboratorModel.listForApi({+ channelId: res.locals.videoChannel.id,+ start: 0,+ // Prefer to use limit of 100 to avoid issues with collaborators list if the admin lowered the config+ count: Math.max(CONFIG.VIDEO_CHANNELS.MAX_COLLABORATORS_PER_CHANNEL, 100),+ sort: '-createdAt'+ })++ return res.json(getFormattedObjects(resultList.data, resultList.total))+}++async function inviteCollaborator (req: express.Request, res: express.Response) {+ const collaborator = new VideoChannelCollaboratorModel({+ state: VideoChannelCollaboratorState.PENDING,+ accountId: res.locals.account.id,+ channelId: res.locals.videoChannel.id+ }) as MChannelCollaboratorAccount++ await retryTransactionWrapper(() => {+ return sequelizeTypescript.transaction(async transaction => {+ // Existing rejected collaborator+ if (res.locals.channelCollaborator) {+ await res.locals.channelCollaborator.destroy({ transaction })+ }++ await collaborator.save({ transaction })+ })+ })++ collaborator.Account = res.locals.account++ Notifier.Instance.notifyOfChannelCollaboratorInvitation(collaborator, res.locals.videoChannel)++ return res.json({ collaborator: collaborator.toFormattedJSON() })+}++async function acceptCollaboratorInvite (req: express.Request, res: express.Response) {+ const collaborator = res.locals.channelCollaborator+ collaborator.state = VideoChannelCollaboratorState.ACCEPTED++ await saveInTransactionWithRetries(collaborator)++ Notifier.Instance.notifyOfAcceptedChannelCollaborator(collaborator, res.locals.videoChannel)++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+}++async function rejectCollaboratorInvite (req: express.Request, res: express.Response) {+ const collaborator = res.locals.channelCollaborator+ collaborator.state = VideoChannelCollaboratorState.REJECTED++ await saveInTransactionWithRetries(collaborator)++ Notifier.Instance.notifyOfRefusedChannelCollaborator(collaborator, res.locals.videoChannel)++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+}++async function removeCollaborator (req: express.Request, res: express.Response) {+ const collaborator = res.locals.channelCollaborator++ await deleteInTransactionWithRetries(collaborator)++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+}diff --git a/server/core/controllers/api/video-playlist.ts b/server/core/controllers/api/video-playlist.tsindex fc8a3176b1..a9839f291e 100644--- a/server/core/controllers/api/video-playlist.ts+++ b/server/core/controllers/api/video-playlist.ts@@ -109,7 +109,7 @@ videoPlaylistRouter.get(paginationValidator,setDefaultPagination,optionalAuthenticate,- asyncMiddleware(getVideoPlaylistVideos)+ asyncMiddleware(listVideosOfPlaylist))videoPlaylistRouter.post(@@ -181,7 +181,7 @@ async function createVideoPlaylist (req: express.Request, res: express.Response)name: videoPlaylistInfo.displayName,description: videoPlaylistInfo.description,privacy: videoPlaylistInfo.privacy || VideoPlaylistPrivacy.PRIVATE,- ownerAccountId: user.Account.id+ ownerAccountId: res.locals.videoChannel?.Account.id ?? user.Account.id}) as MVideoPlaylistFullvideoPlaylist.url = getLocalVideoPlaylistActivityPubUrl(videoPlaylist) // We use the UUID, so set the URL after building the object@@ -517,7 +517,7 @@ async function reorderVideosOfPlaylist (req: express.Request, res: express.Resporeturn res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()}-async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {+async function listVideosOfPlaylist (req: express.Request, res: express.Response) {const videoPlaylistInstance = res.locals.videoPlaylistSummaryconst user = res.locals.oauth ? res.locals.oauth.token.User : undefinedconst server = await getServerActor()diff --git a/server/core/controllers/api/videos/comment.ts b/server/core/controllers/api/videos/comment.tsindex 8fa731db9b..f74c38cd6b 100644--- a/server/core/controllers/api/videos/comment.ts+++ b/server/core/controllers/api/videos/comment.ts@@ -42,7 +42,8 @@ import { VideoCommentModel } from '../../../models/video/video-comment.js'const auditLogger = auditLoggerFactory('comments')const videoCommentRouter = express.Router()-videoCommentRouter.get('/:videoId/comment-threads',+videoCommentRouter.get(+ '/:videoId/comment-threads',paginationValidator,videoCommentThreadsSortValidator,setDefaultSort,@@ -51,35 +52,41 @@ videoCommentRouter.get('/:videoId/comment-threads',optionalAuthenticate,asyncMiddleware(listVideoThreads))-videoCommentRouter.get('/:videoId/comment-threads/:threadId',+videoCommentRouter.get(+ '/:videoId/comment-threads/:threadId',asyncMiddleware(listVideoThreadCommentsValidator),optionalAuthenticate,asyncMiddleware(listVideoThreadComments))-videoCommentRouter.post('/:videoId/comment-threads',+videoCommentRouter.post(+ '/:videoId/comment-threads',authenticate,asyncMiddleware(addVideoCommentThreadValidator),asyncRetryTransactionMiddleware(addVideoCommentThread))-videoCommentRouter.post('/:videoId/comments/:commentId',+videoCommentRouter.post(+ '/:videoId/comments/:commentId',authenticate,asyncMiddleware(addVideoCommentReplyValidator),asyncRetryTransactionMiddleware(addVideoCommentReply))-videoCommentRouter.delete('/:videoId/comments/:commentId',+videoCommentRouter.delete(+ '/:videoId/comments/:commentId',authenticate,asyncMiddleware(removeVideoCommentValidator),asyncRetryTransactionMiddleware(removeVideoComment))-videoCommentRouter.post('/:videoId/comments/:commentId/approve',+videoCommentRouter.post(+ '/:videoId/comments/:commentId/approve',authenticate,asyncMiddleware(approveVideoCommentValidator),asyncMiddleware(approveVideoComment))-videoCommentRouter.get('/comments',+videoCommentRouter.get(+ '/comments',authenticate,ensureUserHasRight(UserRight.SEE_ALL_COMMENTS),paginationValidator,@@ -118,7 +125,7 @@ async function listComments (req: express.Request, res: express.Response) {heldForReview: undefined}- const resultList = await VideoCommentModel.listCommentsForApi(options)+ const resultList = await VideoCommentModel.listForApi(options)return res.json({total: resultList.total,diff --git a/server/core/controllers/api/videos/live.ts b/server/core/controllers/api/videos/live.tsindex 04bd6101b9..57859e50cb 100644--- a/server/core/controllers/api/videos/live.ts+++ b/server/core/controllers/api/videos/live.ts@@ -10,6 +10,7 @@ import { sequelizeTypescript } from '@server/initializers/database.js'import { federateVideoIfNeeded } from '@server/lib/activitypub/videos/index.js'import { LocalVideoCreator } from '@server/lib/local-video-creator.js'import { Hooks } from '@server/lib/plugins/hooks.js'+import { checkCanManageVideo } from '@server/middlewares/validators/shared/videos.js'import {videoLiveAddValidator,videoLiveFindReplaySessionValidator,@@ -44,21 +45,30 @@ liveRouter.get('/live/:videoId/sessions',authenticate,asyncMiddleware(videoLiveGetValidator),- videoLiveListSessionsValidator,+ asyncMiddleware(videoLiveListSessionsValidator),asyncMiddleware(getLiveVideoSessions))-liveRouter.get('/live/:videoId', optionalAuthenticate, asyncMiddleware(videoLiveGetValidator), getLiveVideo)+liveRouter.get(+ '/live/:videoId',+ optionalAuthenticate,+ asyncMiddleware(videoLiveGetValidator),+ asyncMiddleware(getLiveVideo)+)liveRouter.put('/live/:videoId',authenticate,asyncMiddleware(videoLiveGetValidator),- videoLiveUpdateValidator,+ asyncMiddleware(videoLiveUpdateValidator),asyncRetryTransactionMiddleware(updateLiveVideo))-liveRouter.get('/:videoId/live-session', asyncMiddleware(videoLiveFindReplaySessionValidator), getLiveReplaySession)+liveRouter.get(+ '/:videoId/live-session',+ asyncMiddleware(videoLiveFindReplaySessionValidator),+ getLiveReplaySession+)// ---------------------------------------------------------------------------@@ -68,10 +78,10 @@ export {// ----------------------------------------------------------------------------function getLiveVideo (req: express.Request, res: express.Response) {+async function getLiveVideo (req: express.Request, res: express.Response) {const videoLive = res.locals.videoLive- return res.json(videoLive.toFormattedJSON(canSeePrivateLiveInformation(res)))+ return res.json(videoLive.toFormattedJSON(await canSeePrivateLiveInformation(req, res)))}function getLiveReplaySession (req: express.Request, res: express.Response) {@@ -88,14 +98,16 @@ async function getLiveVideoSessions (req: express.Request, res: express.Responsereturn res.json(getFormattedObjects(data, data.length))}-function canSeePrivateLiveInformation (res: express.Response) {- const user = res.locals.oauth?.token.User- if (!user) return false-- if (user.hasRight(UserRight.GET_ANY_LIVE)) return true-- const video = res.locals.videoAll- return video.VideoChannel.Account.userId === user.id+function canSeePrivateLiveInformation (req: express.Request, res: express.Response) {+ return checkCanManageVideo({+ user: res.locals.oauth?.token.User,+ video: res.locals.videoAll,+ right: UserRight.GET_ANY_LIVE,+ req,+ res: null,+ checkIsLocal: true,+ checkIsOwner: false+ })}async function updateLiveVideo (req: express.Request, res: express.Response) {diff --git a/server/core/controllers/api/videos/ownership.ts b/server/core/controllers/api/videos/ownership.tsindex 77aefe5168..b3350441ac 100644--- a/server/core/controllers/api/videos/ownership.ts+++ b/server/core/controllers/api/videos/ownership.ts@@ -23,27 +23,31 @@ import { VideoModel } from '../../../models/video/video.js'const ownershipVideoRouter = express.Router()-ownershipVideoRouter.post('/:videoId/give-ownership',+ownershipVideoRouter.post(+ '/:videoId/give-ownership',authenticate,asyncMiddleware(videosChangeOwnershipValidator),asyncRetryTransactionMiddleware(giveVideoOwnership))-ownershipVideoRouter.get('/ownership',+ownershipVideoRouter.get(+ '/ownership',authenticate,paginationValidator,setDefaultPagination,asyncRetryTransactionMiddleware(listVideoOwnership))-ownershipVideoRouter.post('/ownership/:id/accept',+ownershipVideoRouter.post(+ '/ownership/:id/accept',authenticate,asyncMiddleware(videosTerminateChangeOwnershipValidator),asyncMiddleware(videosAcceptChangeOwnershipValidator),asyncRetryTransactionMiddleware(acceptOwnership))-ownershipVideoRouter.post('/ownership/:id/refuse',+ownershipVideoRouter.post(+ '/ownership/:id/refuse',authenticate,asyncMiddleware(videosTerminateChangeOwnershipValidator),asyncRetryTransactionMiddleware(refuseOwnership)@@ -82,8 +86,8 @@ async function giveVideoOwnership (req: express.Request, res: express.Response)logger.info('Ownership change for video %s created.', videoInstance.name)return res.type('json')- .status(HttpStatusCode.NO_CONTENT_204)- .end()+ .status(HttpStatusCode.NO_CONTENT_204)+ .end()}async function listVideoOwnership (req: express.Request, res: express.Response) {@@ -91,8 +95,8 @@ async function listVideoOwnership (req: express.Request, res: express.Response)const resultList = await VideoChangeOwnershipModel.listForApi(currentAccountId,- req.query.start || 0,- req.query.count || 10,+ req.query.start,+ req.query.count,req.query.sort || 'createdAt')diff --git a/server/core/controllers/api/videos/source.ts b/server/core/controllers/api/videos/source.tsindex 375a6b96e4..4e243b1fff 100644--- a/server/core/controllers/api/videos/source.ts+++ b/server/core/controllers/api/videos/source.ts@@ -1,5 +1,5 @@import { buildAspectRatio } from '@peertube/peertube-core-utils'-import { HttpStatusCode, UserRight, VideoState } from '@peertube/peertube-models'+import { HttpStatusCode, VideoState } from '@peertube/peertube-models'import { sequelizeTypescript } from '@server/initializers/database.js'import { CreateJobArgument, CreateJobOptions, JobQueue } from '@server/lib/job-queue/index.js'import { Hooks } from '@server/lib/plugins/hooks.js'@@ -20,7 +20,6 @@ import { logger, loggerTagsFactory } from '../../../helpers/logger.js'import {asyncMiddleware,authenticate,- ensureUserHasRight,replaceVideoSourceResumableInitValidator,replaceVideoSourceResumableValidator,videoSourceGetLatestValidator@@ -42,7 +41,6 @@ videoSourceRouter.delete('/:id/source/file',openapiOperationDoc({ operationId: 'deleteVideoSourceFile' }),authenticate,- ensureUserHasRight(UserRight.MANAGE_VIDEO_FILES),asyncMiddleware(videoSourceGetLatestValidator),asyncMiddleware(deleteVideoLatestSourceFile))diff --git a/server/core/controllers/services.ts b/server/core/controllers/services.tsindex 39593d0834..c2a7b9a761 100644--- a/server/core/controllers/services.ts+++ b/server/core/controllers/services.ts@@ -12,7 +12,7 @@ servicesRouter.use('/oembed', cors(), apiRateLimiter, asyncMiddleware(oembedValiservicesRouter.use('/redirect/accounts/:handle',apiRateLimiter,- asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkManage: false })),+ asyncMiddleware(accountHandleGetValidatorFactory({ checkIsLocal: false, checkCanManage: false })),redirectToAccountUrl)diff --git a/server/core/helpers/custom-validators/bulk.ts b/server/core/helpers/custom-validators/bulk.tsindex 9e0ce0be12..b6a81f7a90 100644--- a/server/core/helpers/custom-validators/bulk.ts+++ b/server/core/helpers/custom-validators/bulk.ts@@ -1,9 +1,5 @@-function isBulkRemoveCommentsOfScopeValid (value: string) {- return value === 'my-videos' || value === 'instance'-}--// ---------------------------------------------------------------------------+import { BulkRemoveCommentsOfBody } from '@peertube/peertube-models'-export {- isBulkRemoveCommentsOfScopeValid+export function isBulkRemoveCommentsOfScopeValid (value: BulkRemoveCommentsOfBody['scope']) {+ return value === 'my-videos' || value === 'instance' || value === 'my-videos-and-collaborations'}diff --git a/server/core/helpers/custom-validators/video-ownership.ts b/server/core/helpers/custom-validators/video-ownership.tsdeleted file mode 100644index 5961ed97cd..0000000000--- a/server/core/helpers/custom-validators/video-ownership.ts+++ /dev/null@@ -1,20 +0,0 @@-import { Response } from 'express'-import { HttpStatusCode } from '@peertube/peertube-models'-import { MUserId } from '@server/types/models/index.js'-import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership.js'--function checkUserCanTerminateOwnershipChange (user: MUserId, videoChangeOwnership: MVideoChangeOwnershipFull, res: Response) {- if (videoChangeOwnership.NextOwner.userId === user.id) {- return true- }-- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot terminate an ownership change of another user'- })- return false-}--export {- checkUserCanTerminateOwnershipChange-}diff --git a/server/core/helpers/custom-validators/webfinger.ts b/server/core/helpers/custom-validators/webfinger.tsindex c5f3544e96..10d0a04950 100644--- a/server/core/helpers/custom-validators/webfinger.ts+++ b/server/core/helpers/custom-validators/webfinger.ts@@ -2,7 +2,7 @@ import { REMOTE_SCHEME, WEBSERVER } from '../../initializers/constants.js'import { sanitizeHost } from '../core-utils.js'import { exists } from './misc.js'-function isWebfingerLocalResourceValid (value: string) {+export function isWebfingerLocalResourceValid (value: string) {if (!exists(value)) return falseif (value.startsWith('acct:') === false) return false@@ -13,9 +13,3 @@ function isWebfingerLocalResourceValid (value: string) {const host = actorParts[1]return sanitizeHost(host, REMOTE_SCHEME.HTTP) === WEBSERVER.HOST}--// -----------------------------------------------------------------------------export {- isWebfingerLocalResourceValid-}diff --git a/server/core/helpers/database-utils.ts b/server/core/helpers/database-utils.tsindex 94ab78e2fe..28fd20246b 100644--- a/server/core/helpers/database-utils.ts+++ b/server/core/helpers/database-utils.ts@@ -5,7 +5,7 @@ import { Model } from 'sequelize-typescript'import { sequelizeTypescript } from '@server/initializers/database.js'import { logger } from './logger.js'-function retryTransactionWrapper<T, A, B, C, D> (+export function retryTransactionWrapper<T, A, B, C, D> (functionToRetry: (arg1: A, arg2: B, arg3: C, arg4: D) => Promise<T>,arg1: A,arg2: B,@@ -13,29 +13,29 @@ function retryTransactionWrapper<T, A, B, C, D> (arg4: D): Promise<T>-function retryTransactionWrapper<T, A, B, C> (+export function retryTransactionWrapper<T, A, B, C> (functionToRetry: (arg1: A, arg2: B, arg3: C) => Promise<T>,arg1: A,arg2: B,arg3: C): Promise<T>-function retryTransactionWrapper<T, A, B> (+export function retryTransactionWrapper<T, A, B> (functionToRetry: (arg1: A, arg2: B) => Promise<T>,arg1: A,arg2: B): Promise<T>-function retryTransactionWrapper<T, A> (+export function retryTransactionWrapper<T, A> (functionToRetry: (arg1: A) => Promise<T>,arg1: A): Promise<T>-function retryTransactionWrapper<T> (+export function retryTransactionWrapper<T> (functionToRetry: () => Promise<T> | Bluebird<T>): Promise<T>-function retryTransactionWrapper<T> (+export function retryTransactionWrapper<T> (functionToRetry: (...args: any[]) => Promise<T>,...args: any[]): Promise<T> {@@ -50,7 +50,7 @@ function retryTransactionWrapper<T> (})}-function transactionRetryer<T> (func: (err: any, data: T) => any) {+export function transactionRetryer<T> (func: (err: any, data: T) => any) {return new Promise<T>((res, rej) => {retry({@@ -68,7 +68,7 @@ function transactionRetryer<T> (func: (err: any, data: T) => any) {})}-function saveInTransactionWithRetries<T extends Pick<Model, 'save' | 'changed'>> (model: T) {+export function saveInTransactionWithRetries<T extends Pick<Model, 'save' | 'changed'>> (model: T) {const changedKeys = model.changed() || []return retryTransactionWrapper(() => {@@ -87,46 +87,41 @@ function saveInTransactionWithRetries<T extends Pick<Model, 'save' | 'changed'>>})}+export function deleteInTransactionWithRetries<T extends Pick<Model, 'destroy'>> (model: T) {+ return retryTransactionWrapper(() => {+ return sequelizeTypescript.transaction(async transaction => {+ await model.destroy({ transaction })+ })+ })+}+// ----------------------------------------------------------------------------function resetSequelizeInstance<T> (instance: Model<T>) {+export function resetSequelizeInstance<T> (instance: Model<T>) {return instance.reload()}-function filterNonExistingModels<T extends { hasSameUniqueKeysThan(other: T): boolean }> (+export function filterNonExistingModels<T extends { hasSameUniqueKeysThan(other: T): boolean }> (fromDatabase: T[],newModels: T[]) {return fromDatabase.filter(f => !newModels.find(newModel => newModel.hasSameUniqueKeysThan(f)))}-function deleteAllModels<T extends Pick<Model, 'destroy'>> (models: T[], transaction: Transaction) {+export function deleteAllModels<T extends Pick<Model, 'destroy'>> (models: T[], transaction: Transaction) {return Promise.all(models.map(f => f.destroy({ transaction })))}// ----------------------------------------------------------------------------function runInReadCommittedTransaction<T> (fn: (t: Transaction) => Promise<T>) {+export function runInReadCommittedTransaction<T> (fn: (t: Transaction) => Promise<T>) {const options = { isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED }return sequelizeTypescript.transaction(options, t => fn(t))}-function afterCommitIfTransaction (t: Transaction, fn: Function) {+export function afterCommitIfTransaction (t: Transaction, fn: Function) {if (t) return t.afterCommit(() => fn())return fn()}--// -----------------------------------------------------------------------------export {- resetSequelizeInstance,- retryTransactionWrapper,- transactionRetryer,- saveInTransactionWithRetries,- afterCommitIfTransaction,- filterNonExistingModels,- deleteAllModels,- runInReadCommittedTransaction-}diff --git a/server/core/helpers/geo-ip.ts b/server/core/helpers/geo-ip.tsindex c6c7cbf541..d9833dbcb2 100644--- a/server/core/helpers/geo-ip.ts+++ b/server/core/helpers/geo-ip.ts@@ -30,7 +30,10 @@ export class GeoIP {if (CONFIG.GEO_IP.ENABLED === false) return emptyResulttry {- if (!this.initReadersPromise) this.initReadersPromise = this.initReadersIfNeeded()+ if (this.initReadersPromise === undefined) {+ this.initReadersPromise = this.initReadersIfNeeded()+ }+await this.initReadersPromisethis.initReadersPromise = undefineddiff --git a/server/core/helpers/mentions.ts b/server/core/helpers/mentions.tsindex 238e468eaa..829cf276f6 100644--- a/server/core/helpers/mentions.ts+++ b/server/core/helpers/mentions.ts@@ -3,13 +3,13 @@ import { WEBSERVER } from '@server/initializers/constants.js'import { actorNameAlphabet } from './custom-validators/activitypub/actor.js'import { regexpCapture } from './regexp.js'-export function extractMentions (text: string, isOwned: boolean) {+export function extractMentions (text: string, isLocal: boolean) {let result: string[] = []const localMention = `@(${actorNameAlphabet}+)`const remoteMention = `${localMention}@${WEBSERVER.HOST}`- const mentionRegex = isOwned+ const mentionRegex = isLocal? '(?:(?:' + remoteMention + ')|(?:' + localMention + '))' // Include local mentions?: '(?:' + remoteMention + ')'@@ -20,16 +20,14 @@ export function extractMentions (text: string, isOwned: boolean) {result = result.concat(regexpCapture(text, firstMentionRegex).map(([ , username1, username2 ]) => username1 || username2),-regexpCapture(text, endMentionRegex).map(([ , username1, username2 ]) => username1 || username2),-regexpCapture(text, remoteMentionsRegex).map(([ , username ]) => username))// Include local mentions- if (isOwned) {+ if (isLocal) {const localMentionsRegex = new RegExp(' ' + localMention + ' ', 'g')result = result.concat(diff --git a/server/core/initializers/config.ts b/server/core/initializers/config.tsindex d691ac07b5..48f08f2602 100644--- a/server/core/initializers/config.ts+++ b/server/core/initializers/config.ts@@ -552,6 +552,9 @@ const CONFIG = {VIDEO_CHANNELS: {get MAX_PER_USER () {return config.get<number>('video_channels.max_per_user')+ },+ get MAX_COLLABORATORS_PER_CHANNEL () {+ return config.get<number>('video_channels.max_collaborators_per_channel')}},TRANSCODING: {diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.tsindex 32b2effcdb..b8d282c973 100644--- a/server/core/initializers/constants.ts+++ b/server/core/initializers/constants.ts@@ -20,6 +20,8 @@ import {UserImportStateType,UserRegistrationState,UserRegistrationStateType,+ VideoChannelCollaboratorState,+ VideoChannelCollaboratorStateType,VideoChannelSyncState,VideoChannelSyncStateType,VideoCommentPolicy,@@ -52,7 +54,7 @@ import { CONFIG, registerConfigChangedHandler } from './config.js'// ----------------------------------------------------------------------------export const LAST_MIGRATION_VERSION = 930+export const LAST_MIGRATION_VERSION = 935// ---------------------------------------------------------------------------@@ -690,6 +692,12 @@ export const VIDEO_COMMENTS_POLICY: { [id in VideoCommentPolicyType]: string } =[VideoCommentPolicy.REQUIRES_APPROVAL]: 'Requires approval'}+export const CHANNEL_COLLABORATOR_STATE: { [id in VideoChannelCollaboratorStateType]: string } = {+ [VideoChannelCollaboratorState.ACCEPTED]: 'Accepted',+ [VideoChannelCollaboratorState.PENDING]: 'Pending',+ [VideoChannelCollaboratorState.REJECTED]: 'Rejected'+}+export const MIMETYPES = {AUDIO: {MIMETYPE_EXT: {diff --git a/server/core/initializers/database.ts b/server/core/initializers/database.tsindex 8f13400971..3e2323daee 100644--- a/server/core/initializers/database.ts+++ b/server/core/initializers/database.ts@@ -16,7 +16,9 @@ import { UserNotificationModel } from '@server/models/user/user-notification.js'import { UserRegistrationModel } from '@server/models/user/user-registration.js'import { UserVideoHistoryModel } from '@server/models/user/user-video-history.js'import { UserModel } from '@server/models/user/user.js'+import { PlayerSettingModel } from '@server/models/video/player-setting.js'import { StoryboardModel } from '@server/models/video/storyboard.js'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync.js'import { VideoChapterModel } from '@server/models/video/video-chapter.js'import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'@@ -69,7 +71,6 @@ import { VideoTagModel } from '../models/video/video-tag.js'import { VideoModel } from '../models/video/video.js'import { VideoViewModel } from '../models/view/video-view.js'import { CONFIG } from './config.js'-import { PlayerSettingModel } from '@server/models/video/player-setting.js'pg.defaults.parseInt8 = true // Avoid BIGINT to be converted to string@@ -191,7 +192,8 @@ export async function initDatabaseModels (silent: boolean) {AccountAutomaticTagPolicyModel,UploadImageModel,VideoLiveScheduleModel,- PlayerSettingModel+ PlayerSettingModel,+ VideoChannelCollaboratorModel])// Check extensions exist in the databasediff --git a/server/core/initializers/migrations/0935-channel-collaboration.ts b/server/core/initializers/migrations/0935-channel-collaboration.tsnew file mode 100644index 0000000000..391476683c--- /dev/null+++ b/server/core/initializers/migrations/0935-channel-collaboration.ts@@ -0,0 +1,45 @@+import * as Sequelize from 'sequelize'++async function up (utils: {+ transaction: Sequelize.Transaction+ queryInterface: Sequelize.QueryInterface+ sequelize: Sequelize.Sequelize+}): Promise<void> {+ {+ const query = `CREATE TABLE IF NOT EXISTS "videoChannelCollaborator" (+ "id" SERIAL,+ "state" INTEGER NOT NULL,+ "accountId" INTEGER REFERENCES "account" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ "channelId" INTEGER NOT NULL REFERENCES "videoChannel" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,+ PRIMARY KEY ("id")+)`++ await utils.sequelize.query(query, { transaction: utils.transaction })+ }++ {+ const metadata = {+ type: Sequelize.JSONB,+ allowNull: true+ }+ await utils.queryInterface.addColumn('userNotification', 'data', metadata)+ }++ {+ await utils.sequelize.query(`+ ALTER TABLE "userNotification"+ ADD COLUMN "channelCollaboratorId" INTEGER REFERENCES "videoChannelCollaborator" ("id") ON DELETE CASCADE ON UPDATE CASCADE+ `)+ }+}++function down (options) {+ throw new Error('Not implemented.')+}++export {+ up,+ down+}diff --git a/server/core/lib/activitypub/playlists/create-update.ts b/server/core/lib/activitypub/playlists/create-update.tsindex 746853f75b..980b75fc20 100644--- a/server/core/lib/activitypub/playlists/create-update.ts+++ b/server/core/lib/activitypub/playlists/create-update.ts@@ -9,13 +9,7 @@ import { updateRemotePlaylistMiniatureFromUrl } from '@server/lib/thumbnail.js'import { VideoPlaylistElementModel } from '@server/models/video/video-playlist-element.js'import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'import { FilteredModelAttributes } from '@server/types/index.js'-import {- MAccountHost,- MThumbnail,- MVideoPlaylist,- MVideoPlaylistFull,- MVideoPlaylistVideosLength-} from '@server/types/models/index.js'+import { MAccountHost, MThumbnail, MVideoPlaylist, MVideoPlaylistFull, MVideoPlaylistVideosLength } from '@server/types/models/index.js'import Bluebird from 'bluebird'import { getAPId } from '../activity.js'import { getOrCreateAPActor } from '../actors/index.js'@@ -33,6 +27,11 @@ import { isActivityPubUrlValid } from '@server/helpers/custom-validators/activitconst lTags = loggerTagsFactory('ap', 'video-playlist')export async function createAccountPlaylists (playlistUrls: string[], account: MAccountHost) {+ logger.info(+ `Creating or updating ${playlistUrls.length} playlists for account ${account.Actor.preferredUsername}`,+ lTags()+ )+await Bluebird.map(playlistUrls, async playlistUrl => {if (!checkUrlsSameHost(playlistUrl, account.Actor.url)) {logger.warn(`Playlist ${playlistUrl} is not on the same host as owner account ${account.Actor.url}`, lTags(playlistUrl))@@ -69,6 +68,8 @@ export async function createOrUpdateVideoPlaylist (options: {throw new Error(`Playlist ${playlistObject.id} is not on the same host as context URL ${contextUrl}`)}+ logger.debug(`Creating or updating playlist ${playlistObject.id}`, lTags(playlistObject.id))+const playlistAttributes = playlistObjectToDBAttributes(playlistObject, to || playlistObject.to)const channel = await getRemotePlaylistChannel(playlistObject)diff --git a/server/core/lib/activitypub/process/process-announce.ts b/server/core/lib/activitypub/process/process-announce.tsindex 8500efd4d5..a99201be5a 100644--- a/server/core/lib/activitypub/process/process-announce.ts+++ b/server/core/lib/activitypub/process/process-announce.ts@@ -51,7 +51,7 @@ async function processVideoShare (actorAnnouncer: MActorSignature, activity: Acttransaction: t})- if (video.isOwned() && created === true) {+ if (video.isLocal() && created === true) {// Don't resend the activity to the senderconst exceptions = [ actorAnnouncer ]diff --git a/server/core/lib/activitypub/process/process-create.ts b/server/core/lib/activitypub/process/process-create.tsindex dba187f6c6..870c32e465 100644--- a/server/core/lib/activitypub/process/process-create.ts+++ b/server/core/lib/activitypub/process/process-create.ts@@ -91,7 +91,7 @@ async function processCreateCacheFile (const { video } = await getOrCreateAPVideo({ videoObject: cacheFile.object })- if (video.isOwned() && !canVideoBeFederated(video)) {+ if (video.isLocal() && !canVideoBeFederated(video)) {logger.warn(`Do not process create cache file ${cacheFile.object} on a video that cannot be federated`)return}@@ -100,7 +100,7 @@ async function processCreateCacheFile (return createOrUpdateCacheFile(cacheFile, video, byActor, t)})- if (video.isOwned()) {+ if (video.isLocal()) {// Don't resend the activity to the senderconst exceptions = [ byActor ]await forwardVideoRelatedActivity(activity, undefined, exceptions, video)@@ -152,7 +152,7 @@ async function processCreateVideoComment (}// Try to not forward unwanted comments on our videos- if (video.isOwned()) {+ if (video.isLocal()) {if (!canVideoBeFederated(video)) {logger.info('Skip comment forward on non federated video' + video.url)returndiff --git a/server/core/lib/activitypub/process/process-delete.ts b/server/core/lib/activitypub/process/process-delete.tsindex e38e645135..c686a0f35e 100644--- a/server/core/lib/activitypub/process/process-delete.ts+++ b/server/core/lib/activitypub/process/process-delete.ts@@ -55,7 +55,7 @@ async function processDeleteActivity (options: APProcessorOptions<ActivityDelete{const videoInstance = await VideoModel.loadByUrlAndPopulateAccountAndFiles(objectUrl)if (videoInstance) {- if (videoInstance.isOwned()) throw new Error(`Remote instance cannot delete owned video ${videoInstance.url}.`)+ if (videoInstance.isLocal()) throw new Error(`Remote instance cannot delete owned video ${videoInstance.url}.`)return retryTransactionWrapper(processDeleteVideo, byActor, videoInstance)}@@ -64,7 +64,7 @@ async function processDeleteActivity (options: APProcessorOptions<ActivityDelete{const videoPlaylist = await VideoPlaylistModel.loadByUrlAndPopulateAccount(objectUrl)if (videoPlaylist) {- if (videoPlaylist.isOwned()) throw new Error(`Remote instance cannot delete owned playlist ${videoPlaylist.url}.`)+ if (videoPlaylist.isLocal()) throw new Error(`Remote instance cannot delete owned playlist ${videoPlaylist.url}.`)return retryTransactionWrapper(processDeleteVideoPlaylist, byActor, videoPlaylist)}@@ -144,7 +144,7 @@ function processDeleteVideoComment (byActor: MActorSignature, videoComment: MComawait videoComment.save({ transaction: t })- if (videoComment.Video.isOwned()) {+ if (videoComment.Video.isLocal()) {// Don't resend the activity to the senderconst exceptions = [ byActor ]await forwardVideoRelatedActivity(activity, t, exceptions, videoComment.Video)diff --git a/server/core/lib/activitypub/process/process-dislike.ts b/server/core/lib/activitypub/process/process-dislike.tsindex fc62e9bd69..cc0a864650 100644--- a/server/core/lib/activitypub/process/process-dislike.ts+++ b/server/core/lib/activitypub/process/process-dislike.ts@@ -28,7 +28,7 @@ async function processDislike (activity: ActivityDislike, byActor: MActorSignatuif (!byAccount) throw new Error('Cannot create dislike with the non account actor ' + byActor.url)const { video: onlyVideo } = await maybeGetOrCreateAPVideo({ videoObject: videoUrl, fetchType: 'only-video-and-blacklist' })- if (!onlyVideo?.isOwned()) return+ if (!onlyVideo?.isLocal()) returnif (!canVideoBeFederated(onlyVideo)) {logger.warn(`Do not process dislike on video ${videoUrl} that cannot be federated`)diff --git a/server/core/lib/activitypub/process/process-follow.ts b/server/core/lib/activitypub/process/process-follow.tsindex ada07e4507..564fd5a79a 100644--- a/server/core/lib/activitypub/process/process-follow.ts+++ b/server/core/lib/activitypub/process/process-follow.ts@@ -38,7 +38,7 @@ async function processFollow (byActor: MActorSignature, activityId: string, targconst targetActor = await ActorModel.loadByUrlAndPopulateAccountAndChannel(targetActorURL, t)if (!targetActor) throw new Error('Unknown actor')- if (targetActor.isOwned() === false) throw new Error('This is not a local actor.')+ if (targetActor.isLocal() === false) throw new Error('This is not a local actor.')if (await rejectIfInstanceFollowDisabled(byActor, activityId, targetActor)) return { actorFollow: undefined }if (await rejectIfMuted(byActor, activityId, targetActor)) return { actorFollow: undefined }diff --git a/server/core/lib/activitypub/process/process-like.ts b/server/core/lib/activitypub/process/process-like.tsindex 06e883533e..9664537cf7 100644--- a/server/core/lib/activitypub/process/process-like.ts+++ b/server/core/lib/activitypub/process/process-like.ts@@ -30,7 +30,7 @@ async function processLikeVideo (byActor: MActorSignature, activity: ActivityLikif (!byAccount) throw new Error('Cannot create like with the non account actor ' + byActor.url)const { video: onlyVideo } = await maybeGetOrCreateAPVideo({ videoObject: videoUrl, fetchType: 'only-video-and-blacklist' })- if (!onlyVideo?.isOwned()) return+ if (!onlyVideo?.isLocal()) returnif (!canVideoBeFederated(onlyVideo)) {logger.warn(`Do not process like on video ${videoUrl} that cannot be federated`)diff --git a/server/core/lib/activitypub/process/process-reply-approval.ts b/server/core/lib/activitypub/process/process-reply-approval.tsindex 6755168ca0..c7b94100ac 100644--- a/server/core/lib/activitypub/process/process-reply-approval.ts+++ b/server/core/lib/activitypub/process/process-reply-approval.ts@@ -16,7 +16,7 @@ export function processReplyApprovalFactory (type: Extract<ActivityType, 'Approvthrow new Error(`Cannot process reply approval on comment ${comment.url} that doesn't exist`)}- if (comment.isOwned() !== true) {+ if (comment.isLocal() !== true) {throw new Error(`Cannot process reply approval on non-owned comment ${comment.url}`)}diff --git a/server/core/lib/activitypub/process/process-undo.ts b/server/core/lib/activitypub/process/process-undo.tsindex ec5306bff2..e0e8477691 100644--- a/server/core/lib/activitypub/process/process-undo.ts+++ b/server/core/lib/activitypub/process/process-undo.ts@@ -68,7 +68,7 @@ async function processUndoLike (byActor: MActorSignature, activity: ActivityUndoconst likeActivity = activity.objectconst { video: onlyVideo } = await maybeGetOrCreateAPVideo({ videoObject: likeActivity.object })- if (!onlyVideo?.isOwned()) return+ if (!onlyVideo?.isLocal()) returnreturn sequelizeTypescript.transaction(async t => {if (!byActor.Account) throw new Error('Unknown account ' + byActor.url)@@ -92,7 +92,7 @@ async function processUndoDislike (byActor: MActorSignature, activity: ActivityUconst dislikeActivity = activity.objectconst { video: onlyVideo } = await maybeGetOrCreateAPVideo({ videoObject: dislikeActivity.object })- if (!onlyVideo?.isOwned()) return+ if (!onlyVideo?.isLocal()) returnreturn sequelizeTypescript.transaction(async t => {if (!byActor.Account) throw new Error('Unknown account ' + byActor.url)@@ -132,7 +132,7 @@ async function processUndoCacheFile (await cacheFile.destroy({ transaction: t })- if (video.isOwned()) {+ if (video.isLocal()) {// Don't resend the activity to the senderconst exceptions = [ byActor ]@@ -153,7 +153,7 @@ function processUndoAnnounce (byActor: MActorSignature, announceActivity: Activiawait share.destroy({ transaction: t })- if (share.Video.isOwned()) {+ if (share.Video.isLocal()) {// Don't resend the activity to the senderconst exceptions = [ byActor ]diff --git a/server/core/lib/activitypub/process/process-update.ts b/server/core/lib/activitypub/process/process-update.tsindex 857d47717a..7f3c4aa1f3 100644--- a/server/core/lib/activitypub/process/process-update.ts+++ b/server/core/lib/activitypub/process/process-update.ts@@ -103,7 +103,7 @@ async function processUpdateCacheFile (const { video } = await getOrCreateAPVideo({ videoObject: cacheFileObject.object })- if (video.isOwned() && !canVideoBeFederated(video)) {+ if (video.isLocal() && !canVideoBeFederated(video)) {logger.warn(`Do not process update cache file on video ${activity.object} that cannot be federated`)return}@@ -112,7 +112,7 @@ async function processUpdateCacheFile (await createOrUpdateCacheFile(cacheFileObject, video, byActor, t)})- if (video.isOwned()) {+ if (video.isLocal()) {// Don't resend the activity to the senderconst exceptions = [ byActor ]diff --git a/server/core/lib/activitypub/process/process-view.ts b/server/core/lib/activitypub/process/process-view.tsindex 12e86d9937..72a3fa8c6f 100644--- a/server/core/lib/activitypub/process/process-view.ts+++ b/server/core/lib/activitypub/process/process-view.ts@@ -38,7 +38,7 @@ async function processCreateView (activity: ActivityView, byActor: MActorSignatuviewerResultCounter: getViewerResultCounter(activity)})- if (video.isOwned()) {+ if (video.isLocal()) {// Forward the view but don't resend the activity to the senderconst exceptions = [ byActor ]await forwardVideoRelatedActivity(activity, undefined, exceptions, video)diff --git a/server/core/lib/activitypub/send/send-create.ts b/server/core/lib/activitypub/send/send-create.tsindex 381d203363..52655e8f63 100644--- a/server/core/lib/activitypub/send/send-create.ts+++ b/server/core/lib/activitypub/send/send-create.ts@@ -110,7 +110,7 @@ export async function sendCreateVideoPlaylist (playlist: MVideoPlaylistFull, tra}export async function sendCreateVideoCommentIfNeeded (comment: MCommentOwnerVideoReply, transaction: Transaction) {- const isOrigin = comment.Video.isOwned()+ const isOrigin = comment.Video.isLocal()if (isOrigin) {const videoWithBlacklist = await VideoModel.loadWithBlacklist(comment.Video.id)diff --git a/server/core/lib/activitypub/send/send-delete.ts b/server/core/lib/activitypub/send/send-delete.tsindex 4c810bafe6..8f05e1af61 100644--- a/server/core/lib/activitypub/send/send-delete.ts+++ b/server/core/lib/activitypub/send/send-delete.ts@@ -53,13 +53,13 @@ async function sendDeleteActor (byActor: ActorModel, transaction: Transaction) {async function sendDeleteVideoComment (videoComment: MCommentOwnerVideo, transaction: Transaction) {logger.info('Creating job to send delete of comment %s.', videoComment.url)- const isVideoOrigin = videoComment.Video.isOwned()+ const isVideoOrigin = videoComment.Video.isLocal()const url = getDeleteActivityPubUrl(videoComment.url)const videoAccount = await AccountModel.load(videoComment.Video.VideoChannel.Account.id, transaction)- const byActor = videoComment.isOwned()+ const byActor = videoComment.isLocal()? videoComment.Account.Actor: videoAccount.Actordiff --git a/server/core/lib/activitypub/send/shared/send-utils.ts b/server/core/lib/activitypub/send/shared/send-utils.tsindex 1ad9f3fa18..ba17a528f4 100644--- a/server/core/lib/activitypub/send/shared/send-utils.ts+++ b/server/core/lib/activitypub/send/shared/send-utils.ts@@ -29,7 +29,7 @@ async function sendVideoRelatedActivity (activityBuilder: (audience: ActivityAudconst { byActor, video, transaction, contextType, parallelizable } = options// Send to origin- if (video.isOwned() === false) {+ if (video.isLocal() === false) {return sendVideoActivityToOrigin(activityBuilder, options)}@@ -62,7 +62,7 @@ async function sendVideoActivityToOrigin (activityBuilder: (audience: ActivityAu}) {const { byActor, video, actorsInvolvedInVideo, transaction, contextType } = options- if (video.isOwned()) throw new Error('Cannot send activity to owned video origin ' + video.url)+ if (video.isLocal()) throw new Error('Cannot send activity to owned video origin ' + video.url)let accountActor: MActorLight = (video as MVideoAccountLight).VideoChannel?.Account?.Actorif (!accountActor) accountActor = await ActorModel.loadAccountActorByVideoId(video.id, transaction)diff --git a/server/core/lib/activitypub/video-comments.ts b/server/core/lib/activitypub/video-comments.tsindex 22c8be1c32..adf28637e0 100644--- a/server/core/lib/activitypub/video-comments.ts+++ b/server/core/lib/activitypub/video-comments.ts@@ -109,7 +109,7 @@ async function tryToResolveThreadFromVideo (params: ResolveThreadParams) {const syncParam = { rates: true, shares: true, comments: false, refreshVideo: false }const { video } = await getOrCreateAPVideo({ videoObject: url, syncParam })- if (video.isOwned() && !canVideoBeFederated(video)) {+ if (video.isLocal() && !canVideoBeFederated(video)) {throw new Error('Cannot resolve thread of video that is not compatible with federation')}@@ -169,7 +169,7 @@ async function getAutomaticTagsAndAssignReview (comment: MComment, video: MVideoconst automaticTags = await new AutomaticTagger().buildCommentsAutomaticTags({ ownerAccount, text: comment.text })// Third parties rely on origin, so if origin has the comment it's not held for review- if (video.isOwned() || comment.isOwned()) {+ if (video.isLocal() || comment.isLocal()) {comment.heldForReview = await shouldCommentBeHeldForReview({ user: null, video, automaticTags })} else {comment.heldForReview = falsediff --git a/server/core/lib/activitypub/video-rates.ts b/server/core/lib/activitypub/video-rates.tsindex 1c0d5ec14c..1e3a99c5c6 100644--- a/server/core/lib/activitypub/video-rates.ts+++ b/server/core/lib/activitypub/video-rates.ts@@ -13,7 +13,7 @@ async function sendVideoRateChange (dislikes: number,t: Transaction) {- if (video.isOwned()) return federateVideoIfNeeded(video, false, t)+ if (video.isLocal()) return federateVideoIfNeeded(video, false, t)return sendVideoRateChangeToOrigin(account, video, likes, dislikes, t)}@@ -41,7 +41,7 @@ async function sendVideoRateChangeToOrigin (t: Transaction) {// Local video, we don't need to send like- if (video.isOwned()) return+ if (video.isLocal()) returnconst actor = account.Actordiff --git a/server/core/lib/emailer.ts b/server/core/lib/emailer.tsindex 1496469e40..6bdebcfa57 100644--- a/server/core/lib/emailer.ts+++ b/server/core/lib/emailer.ts@@ -490,7 +490,7 @@ export class Emailer {}private initHandlebarsIfNeeded () {- if (this.registeringHandlebars) return this.registeringHandlebars+ if (this.registeringHandlebars !== undefined) return this.registeringHandlebarsthis.registeringHandlebars = this._initHandlebarsIfNeeded()diff --git a/server/core/lib/files-cache/shared/abstract-permanent-file-cache.ts b/server/core/lib/files-cache/shared/abstract-permanent-file-cache.tsindex f7df6e5605..0aa4f6d0f6 100644--- a/server/core/lib/files-cache/shared/abstract-permanent-file-cache.ts+++ b/server/core/lib/files-cache/shared/abstract-permanent-file-cache.ts@@ -12,13 +12,13 @@ type ImageModel = {filename: stringonDisk: boolean- isOwned (): boolean- getPath (): string+ isLocal(): boolean+ getPath(): string- save (): Promise<Model>+ save(): Promise<Model>}-export abstract class AbstractPermanentFileCache <M extends ImageModel> {+export abstract class AbstractPermanentFileCache<M extends ImageModel> {// Unsafe because it can return paths that do not exist anymoreprivate readonly filenameToPathUnsafeCache = new LRUCache<string, string>({max: LRU_CACHE.FILENAME_TO_PATH_PERMANENT_FILE_CACHE.MAX_SIZE@@ -28,7 +28,6 @@ export abstract class AbstractPermanentFileCache <M extends ImageModel> {protected abstract loadModel (filename: string): Promise<M>constructor (private readonly directory: string) {-}async lazyServe (options: {@@ -102,7 +101,7 @@ export abstract class AbstractPermanentFileCache <M extends ImageModel> {const { err, image, filename, next } = options// It seems this actor image is not on the disk anymore- if (err.status === HttpStatusCode.NOT_FOUND_404 && !image.isOwned()) {+ if (err.status === HttpStatusCode.NOT_FOUND_404 && !image.isLocal()) {logger.error('Cannot lazy serve image %s.', filename, { err })this.filenameToPathUnsafeCache.delete(filename)diff --git a/server/core/lib/files-cache/shared/abstract-simple-file-cache.ts b/server/core/lib/files-cache/shared/abstract-simple-file-cache.tsindex 6e7d6867bb..2febaa80a2 100644--- a/server/core/lib/files-cache/shared/abstract-simple-file-cache.ts+++ b/server/core/lib/files-cache/shared/abstract-simple-file-cache.ts@@ -2,10 +2,9 @@ import { remove } from 'fs-extra/esm'import { logger } from '../../../helpers/logger.js'import memoizee from 'memoizee'-type GetFilePathResult = { isOwned: boolean, path: string, downloadName?: string } | undefined--export abstract class AbstractSimpleFileCache <T> {+type GetFilePathResult = { isLocal: boolean, path: string, downloadName?: string } | undefined+export abstract class AbstractSimpleFileCache<T> {getFilePath: (params: T) => Promise<GetFilePathResult>abstract getFilePathImpl (params: T): Promise<GetFilePathResult>@@ -19,7 +18,7 @@ export abstract class AbstractSimpleFileCache <T> {max,promise: true,dispose: (result?: GetFilePathResult) => {- if (result && result.isOwned !== true) {+ if (result && result.isLocal !== true) {remove(result.path).then(() => logger.debug('%s removed from %s', result.path, this.constructor.name)).catch(err => logger.error('Cannot remove %s from cache %s.', result.path, this.constructor.name, { err }))diff --git a/server/core/lib/files-cache/video-captions-simple-file-cache.ts b/server/core/lib/files-cache/video-captions-simple-file-cache.tsindex 9f68dc511c..6e0e7038f9 100644--- a/server/core/lib/files-cache/video-captions-simple-file-cache.ts+++ b/server/core/lib/files-cache/video-captions-simple-file-cache.ts@@ -21,8 +21,8 @@ class VideoCaptionsSimpleFileCache extends AbstractSimpleFileCache<string> {const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(filename)if (!videoCaption) return undefined- if (videoCaption.isOwned()) {- return { isOwned: true, path: videoCaption.getFSFilePath() }+ if (videoCaption.isLocal()) {+ return { isLocal: true, path: videoCaption.getFSFilePath() }}return this.loadRemoteFile(filename)@@ -33,7 +33,7 @@ class VideoCaptionsSimpleFileCache extends AbstractSimpleFileCache<string> {const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(key)if (!videoCaption) return undefined- if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')+ if (videoCaption.isLocal()) throw new Error('Cannot load remote caption of owned video.')// Used to fetch the pathconst video = await VideoModel.loadFull(videoCaption.videoId)@@ -45,7 +45,7 @@ class VideoCaptionsSimpleFileCache extends AbstractSimpleFileCache<string> {try {await doRequestAndSaveToFile(remoteUrl, destPath)- return { isOwned: false, path: destPath }+ return { isLocal: false, path: destPath }} catch (err) {logger.info('Cannot fetch remote caption file %s.', remoteUrl, { err })diff --git a/server/core/lib/files-cache/video-previews-simple-file-cache.ts b/server/core/lib/files-cache/video-previews-simple-file-cache.tsindex 4dd0fd1483..262882f319 100644--- a/server/core/lib/files-cache/video-previews-simple-file-cache.ts+++ b/server/core/lib/files-cache/video-previews-simple-file-cache.ts@@ -1,14 +1,13 @@+import { ThumbnailType } from '@peertube/peertube-models'+import { logger } from '@server/helpers/logger.js'+import { doRequestAndSaveToFile } from '@server/helpers/requests.js'+import { ThumbnailModel } from '@server/models/video/thumbnail.js'import { join } from 'path'import { FILES_CACHE } from '../../initializers/constants.js'import { VideoModel } from '../../models/video/video.js'import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'-import { doRequestAndSaveToFile } from '@server/helpers/requests.js'-import { ThumbnailModel } from '@server/models/video/thumbnail.js'-import { ThumbnailType } from '@peertube/peertube-models'-import { logger } from '@server/helpers/logger.js'--class VideoPreviewsSimpleFileCache extends AbstractSimpleFileCache <string> {+class VideoPreviewsSimpleFileCache extends AbstractSimpleFileCache<string> {private static instance: VideoPreviewsSimpleFileCacheprivate constructor () {@@ -23,7 +22,7 @@ class VideoPreviewsSimpleFileCache extends AbstractSimpleFileCache <string> {const thumbnail = await ThumbnailModel.loadWithVideoByFilename(filename, ThumbnailType.PREVIEW)if (!thumbnail) return undefined- if (thumbnail.Video.isOwned()) return { isOwned: true, path: thumbnail.getPath() }+ if (thumbnail.Video.isLocal()) return { isLocal: true, path: thumbnail.getPath() }return this.loadRemoteFile(thumbnail.Video.uuid)}@@ -33,7 +32,7 @@ class VideoPreviewsSimpleFileCache extends AbstractSimpleFileCache <string> {const video = await VideoModel.loadFull(key)if (!video) return undefined- if (video.isOwned()) throw new Error('Cannot load remote preview of owned video.')+ if (video.isLocal()) throw new Error('Cannot load remote preview of owned video.')const preview = video.getPreview()const destPath = join(FILES_CACHE.PREVIEWS.DIRECTORY, preview.filename)@@ -44,7 +43,7 @@ class VideoPreviewsSimpleFileCache extends AbstractSimpleFileCache <string> {logger.debug('Fetched remote preview %s to %s.', remoteUrl, destPath)- return { isOwned: false, path: destPath }+ return { isLocal: false, path: destPath }} catch (err) {logger.info('Cannot fetch remote preview file %s.', remoteUrl, { err })diff --git a/server/core/lib/files-cache/video-storyboards-simple-file-cache.ts b/server/core/lib/files-cache/video-storyboards-simple-file-cache.tsindex 7991b8d592..b0389ce631 100644--- a/server/core/lib/files-cache/video-storyboards-simple-file-cache.ts+++ b/server/core/lib/files-cache/video-storyboards-simple-file-cache.ts@@ -1,12 +1,11 @@-import { join } from 'path'import { logger } from '@server/helpers/logger.js'import { doRequestAndSaveToFile } from '@server/helpers/requests.js'import { StoryboardModel } from '@server/models/video/storyboard.js'+import { join } from 'path'import { FILES_CACHE } from '../../initializers/constants.js'import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'-class VideoStoryboardsSimpleFileCache extends AbstractSimpleFileCache <string> {-+class VideoStoryboardsSimpleFileCache extends AbstractSimpleFileCache<string> {private static instance: VideoStoryboardsSimpleFileCacheprivate constructor () {@@ -21,7 +20,7 @@ class VideoStoryboardsSimpleFileCache extends AbstractSimpleFileCache <string> {const storyboard = await StoryboardModel.loadWithVideoByFilename(filename)if (!storyboard) return undefined- if (storyboard.Video.isOwned()) return { isOwned: true, path: storyboard.getPath() }+ if (storyboard.Video.isLocal()) return { isLocal: true, path: storyboard.getPath() }return this.loadRemoteFile(storyboard.filename)}@@ -39,7 +38,7 @@ class VideoStoryboardsSimpleFileCache extends AbstractSimpleFileCache <string> {logger.debug('Fetched remote storyboard %s to %s.', remoteUrl, destPath)- return { isOwned: false, path: destPath }+ return { isLocal: false, path: destPath }} catch (err) {logger.info('Cannot fetch remote storyboard file %s.', remoteUrl, { err })diff --git a/server/core/lib/files-cache/video-torrents-simple-file-cache.ts b/server/core/lib/files-cache/video-torrents-simple-file-cache.tsindex 5a1ef34676..3e09e1764e 100644--- a/server/core/lib/files-cache/video-torrents-simple-file-cache.ts+++ b/server/core/lib/files-cache/video-torrents-simple-file-cache.ts@@ -8,8 +8,7 @@ import { FILES_CACHE } from '../../initializers/constants.js'import { VideoModel } from '../../models/video/video.js'import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'-class VideoTorrentsSimpleFileCache extends AbstractSimpleFileCache <string> {-+class VideoTorrentsSimpleFileCache extends AbstractSimpleFileCache<string> {private static instance: VideoTorrentsSimpleFileCacheprivate constructor () {@@ -24,10 +23,10 @@ class VideoTorrentsSimpleFileCache extends AbstractSimpleFileCache <string> {const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(filename)if (!file) return undefined- if (file.getVideo().isOwned()) {+ if (file.getVideo().isLocal()) {const downloadName = this.buildDownloadName(file.getVideo(), file)- return { isOwned: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }+ return { isLocal: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }}return this.loadRemoteFile(filename)@@ -38,7 +37,7 @@ class VideoTorrentsSimpleFileCache extends AbstractSimpleFileCache <string> {const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(key)if (!file) return undefined- if (file.getVideo().isOwned()) throw new Error('Cannot load remote file of owned video.')+ if (file.getVideo().isLocal()) throw new Error('Cannot load remote file of owned video.')// Used to fetch the pathconst video = await VideoModel.loadFull(file.getVideo().id)@@ -52,7 +51,7 @@ class VideoTorrentsSimpleFileCache extends AbstractSimpleFileCache <string> {const downloadName = this.buildDownloadName(video, file)- return { isOwned: false, path: destPath, downloadName }+ return { isLocal: false, path: destPath, downloadName }} catch (err) {logger.info('Cannot fetch remote torrent file %s.', remoteUrl, { err })diff --git a/server/core/lib/html/shared/actor-html.ts b/server/core/lib/html/shared/actor-html.tsindex 27a14d33fb..24e548adca 100644--- a/server/core/lib/html/shared/actor-html.ts+++ b/server/core/lib/html/shared/actor-html.ts@@ -108,7 +108,7 @@ export class ActorHtml {updatedAt: entity.updatedAt},- forbidIndexation: !entity.Actor.isOwned(),+ forbidIndexation: !entity.Actor.isLocal(),embedIndexation: false,rssFeeds: getRSSFeeds(entity)diff --git a/server/core/lib/html/shared/playlist-html.ts b/server/core/lib/html/shared/playlist-html.tsindex 5adf723043..35698c8222 100644--- a/server/core/lib/html/shared/playlist-html.ts+++ b/server/core/lib/html/shared/playlist-html.ts@@ -113,7 +113,7 @@ export class PlaylistHtml {forbidIndexation: isEmbed? playlist.privacy !== VideoPlaylistPrivacy.PUBLIC && playlist.privacy !== VideoPlaylistPrivacy.UNLISTED- : !playlist.isOwned() || playlist.privacy !== VideoPlaylistPrivacy.PUBLIC,+ : !playlist.isLocal() || playlist.privacy !== VideoPlaylistPrivacy.PUBLIC,embedIndexation: isEmbed,diff --git a/server/core/lib/live/shared/muxing-session.ts b/server/core/lib/live/shared/muxing-session.tsindex fcda0e93d9..4513cf5729 100644--- a/server/core/lib/live/shared/muxing-session.ts+++ b/server/core/lib/live/shared/muxing-session.ts@@ -438,7 +438,10 @@ class MuxingSession extends EventEmitter implements MuxingSession {setTimeout(() => {// Wait latest segments generation, and close watchers- const promise = this.filesWatcher?.close() || Promise.resolve()+ const promise = this.filesWatcher+ ? this.filesWatcher.close()+ : Promise.resolve()+promise.then(() => {// Process remaining segments hashdiff --git a/server/core/lib/moderation.ts b/server/core/lib/moderation.tsindex 0a5069f7b7..861aebfa04 100644--- a/server/core/lib/moderation.ts+++ b/server/core/lib/moderation.ts@@ -129,7 +129,7 @@ async function createVideoAbuse (options: {videoAbuseInstance.Video = videoInstanceabuseInstance.VideoAbuse = videoAbuseInstance- return { isOwned: videoInstance.isOwned() }+ return { isLocal: videoInstance.isLocal() }}return createAbuse({@@ -160,7 +160,7 @@ function createVideoCommentAbuse (options: {commentAbuseInstance.VideoComment = commentInstanceabuseInstance.VideoCommentAbuse = commentAbuseInstance- return { isOwned: commentInstance.isOwned() }+ return { isLocal: commentInstance.isLocal() }}return createAbuse({@@ -183,7 +183,7 @@ function createAccountAbuse (options: {const { baseAbuse, accountInstance, transaction, reporterAccount, skipNotification } = optionsconst associateFun = () => {- return Promise.resolve({ isOwned: accountInstance.isOwned() })+ return Promise.resolve({ isLocal: accountInstance.isLocal() })}return createAbuse({@@ -217,7 +217,7 @@ async function createAbuse (options: {base: FilteredModelAttributes<AbuseModel>reporterAccount: MAccountDefaultflaggedAccount: MAccountLight- associateFun: (abuseInstance: MAbuseFull) => Promise<{ isOwned: boolean }>+ associateFun: (abuseInstance: MAbuseFull) => Promise<{ isLocal: boolean }>skipNotification: booleantransaction: Transaction}) {@@ -230,9 +230,9 @@ async function createAbuse (options: {abuseInstance.ReporterAccount = reporterAccountabuseInstance.FlaggedAccount = flaggedAccount- const { isOwned } = await associateFun(abuseInstance)+ const { isLocal } = await associateFun(abuseInstance)- if (isOwned === false) {+ if (isLocal === false) {sendAbuse(reporterAccount.Actor, abuseInstance, abuseInstance.FlaggedAccount, transaction)}diff --git a/server/core/lib/notifier/notifier.ts b/server/core/lib/notifier/notifier.tsindex a2cf1f396f..e031521300 100644--- a/server/core/lib/notifier/notifier.ts+++ b/server/core/lib/notifier/notifier.ts@@ -8,6 +8,9 @@ import {MAbuseMessage,MActorFollowFull,MApplication,+ MChannelAccountDefault,+ MChannelCollaboratorAccount,+ MChannelDefault,MCommentOwnerVideo,MPlugin,MVideoAccountLight,@@ -17,6 +20,9 @@ import {import { JobQueue } from '../job-queue/index.js'import { PeerTubeSocket } from '../peertube-socket.js'import { Hooks } from '../plugins/hooks.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'import {AbstractNotification,AbuseStateChangeForReporter,@@ -71,7 +77,10 @@ class Notifier {newPeertubeVersion: [ NewPeerTubeVersionForAdmins ],newPluginVersion: [ NewPluginVersionForAdmins ],videoStudioEditionFinished: [ StudioEditionFinishedForOwner ],- videoTranscriptionGenerated: [ VideoTranscriptionGeneratedForOwner ]+ videoTranscriptionGenerated: [ VideoTranscriptionGeneratedForOwner ],+ channelCollaboratorInvitation: [ InvitedToCollaborateToChannel ],+ channelCollaborationAccepted: [ AcceptedToCollaborateToChannel ],+ channelCollaborationRefused: [ RefusedToCollaborateToChannel ]}private static instance: Notifier@@ -287,6 +296,44 @@ class Notifier {.catch(err => logger.error('Cannot notify on generated video transcription %s of video %s.', caption.language, video.url, { err }))}+ notifyOfChannelCollaboratorInvitation (collaborator: MChannelCollaboratorAccount, channel: MChannelAccountDefault) {+ const models = this.notificationModels.channelCollaboratorInvitation++ const channelName = channel.Actor.preferredUsername+ const collaboratorName = collaborator.Account.Actor.preferredUsername++ logger.debug('Notify on channel collaborator invitation', { channelName, collaboratorName, ...lTags() })++ this.sendNotifications(models, { channel, collaborator })+ .catch(err => logger.error(`Cannot notify ${collaboratorName} of invitation to collaborate to channel ${channelName}`, { err }))+ }++ notifyOfAcceptedChannelCollaborator (collaborator: MChannelCollaboratorAccount, channel: MChannelDefault) {+ const models = this.notificationModels.channelCollaborationAccepted++ const channelName = channel.Actor.preferredUsername+ const channelOwner = collaborator.Account.Actor.preferredUsername++ logger.debug('Notify of accepted channel collaboration invitation', { channelName, channelOwner, ...lTags() })++ this.sendNotifications(models, { channel, collaborator })+ .catch(err => logger.error(`Cannot notify ${channelOwner} of accepted invitation to collaborate to channel ${channelName}`, { err }))+ }++ notifyOfRefusedChannelCollaborator (collaborator: MChannelCollaboratorAccount, channel: MChannelDefault) {+ const models = this.notificationModels.channelCollaborationRefused++ const channelName = channel.Actor.preferredUsername+ const channelOwner = collaborator.Account.Actor.preferredUsername++ logger.debug('Notify of refused channel collaboration invitation', { channelName, channelOwner, ...lTags() })++ this.sendNotifications(models, { channel, collaborator })+ .catch(err => logger.error(`Cannot notify ${channelOwner} of refused invitation to collaborate to channel ${channelName}`, { err }))+ }++ // ---------------------------------------------------------------------------+private async notify<T> (object: AbstractNotification<T>) {await object.prepare()diff --git a/server/core/lib/notifier/shared/abuse/abuse-state-change-for-reporter.ts b/server/core/lib/notifier/shared/abuse/abuse-state-change-for-reporter.tsindex 867df4ca68..bad552c916 100644--- a/server/core/lib/notifier/shared/abuse/abuse-state-change-for-reporter.ts+++ b/server/core/lib/notifier/shared/abuse/abuse-state-change-for-reporter.ts@@ -13,7 +13,7 @@ export class AbuseStateChangeForReporter extends AbstractNotification<MAbuseFullasync prepare () {const reporter = this.abuse.ReporterAccount- if (reporter.isOwned() !== true) return+ if (reporter.isLocal() !== true) returnthis.user = await UserModel.loadByAccountActorId(this.abuse.ReporterAccount.actorId)}diff --git a/server/core/lib/notifier/shared/abuse/new-abuse-for-moderators.ts b/server/core/lib/notifier/shared/abuse/new-abuse-for-moderators.tsindex d28b66c797..ea6274cdf1 100644--- a/server/core/lib/notifier/shared/abuse/new-abuse-for-moderators.ts+++ b/server/core/lib/notifier/shared/abuse/new-abuse-for-moderators.ts@@ -70,7 +70,7 @@ export class NewAbuseForModerators extends AbstractNotification<NewAbusePayload>channelDisplayName: channel.getDisplayName(),channelUrl: channel.getClientUrl(),reporter: this.payload.reporter,- action: this.buildEmailAction()+ action: this.buildEmailAction(to)}}}@@ -85,12 +85,12 @@ export class NewAbuseForModerators extends AbstractNotification<NewAbusePayload>locals: {commentUrl: WEBSERVER.URL + comment.getCommentStaticPath(),videoName: comment.Video.name,- isLocal: comment.isOwned(),+ isLocal: comment.isLocal(),commentCreatedAt: new Date(comment.createdAt).toLocaleString(),reason: this.payload.abuse.reason,flaggedAccount: this.payload.abuseInstance.FlaggedAccount.getDisplayName(),reporter: this.payload.reporter,- action: this.buildEmailAction()+ action: this.buildEmailAction(to)}}}@@ -106,17 +106,17 @@ export class NewAbuseForModerators extends AbstractNotification<NewAbusePayload>locals: {accountUrl,accountDisplayName: account.getDisplayName(),- isLocal: account.isOwned(),+ isLocal: account.isLocal(),reason: this.payload.abuse.reason,reporter: this.payload.reporter,- action: this.buildEmailAction()+ action: this.buildEmailAction(to)}}}- private buildEmailAction () {+ private buildEmailAction (to: To) {return {- text: 'View report #' + this.payload.abuseInstance.id,+ text: t('View report #' + this.payload.abuseInstance.id, to.language),url: getAdminAbuseUrl(this.payload.abuseInstance)}}diff --git a/server/core/lib/notifier/shared/abuse/new-abuse-message-for-reporter.ts b/server/core/lib/notifier/shared/abuse/new-abuse-message-for-reporter.tsindex 2864a1cf08..7c598718bb 100644--- a/server/core/lib/notifier/shared/abuse/new-abuse-message-for-reporter.ts+++ b/server/core/lib/notifier/shared/abuse/new-abuse-message-for-reporter.ts@@ -9,7 +9,7 @@ export class NewAbuseMessageForReporter extends AbstractNewAbuseMessage {async prepare () {// Only notify our users- if (this.abuse.ReporterAccount.isOwned() !== true) return+ if (this.abuse.ReporterAccount.isLocal() !== true) returnawait this.loadMessageAccount()diff --git a/server/core/lib/notifier/shared/channel/accepted-to-collaborate-to-channel.ts b/server/core/lib/notifier/shared/channel/accepted-to-collaborate-to-channel.tsnew file mode 100644index 0000000000..cae3cbc7e6--- /dev/null+++ b/server/core/lib/notifier/shared/channel/accepted-to-collaborate-to-channel.ts@@ -0,0 +1,68 @@+import { UserNotificationSettingValue, UserNotificationType } from '@peertube/peertube-models'+import { t } from '@server/helpers/i18n.js'+import { logger } from '@server/helpers/logger.js'+import { UserModel } from '@server/models/user/user.js'+import { MUserDefault, MUserWithNotificationSetting } from '@server/types/models/index.js'+import { AbstractNotification } from '../common/abstract-notification.js'+import { buildCollaborateToChannelNotification, NotificationCollaboratePayload } from './collaborate-to-channel-utils.js'++export class AcceptedToCollaborateToChannel extends AbstractNotification<NotificationCollaboratePayload> {+ private user: MUserDefault++ async prepare () {+ this.user = await UserModel.loadByAccountId(this.payload.channel.accountId)+ }++ log () {+ logger.info(+ `Notifying user ${this.user.username} of accepted invitation to collaborate on channel ${this.payload.channel.Actor.getIdentifier()}`+ )+ }++ isDisabled () {+ return false+ }++ getSetting (_user: MUserWithNotificationSetting) {+ // Always notify+ return UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ }++ getTargetUsers () {+ return [ this.user ]+ }++ createNotification (user: MUserWithNotificationSetting) {+ return buildCollaborateToChannelNotification({+ user,+ payload: this.payload,+ notificationType: UserNotificationType.ACCEPTED_TO_COLLABORATE_TO_CHANNEL+ })+ }++ // ---------------------------------------------------------------------------++ createEmail (user: MUserWithNotificationSetting) {+ const userLanguage = user.getLanguage()+ const to = { email: user.email, language: userLanguage }++ const { channel, collaborator } = this.payload++ const text = t('{collaboratorName} accepted your invitation to become a collaborator of {channelName}', userLanguage, {+ collaboratorName: collaborator.Account.getDisplayName(),+ channelName: channel.getDisplayName()+ })++ return {+ to,+ subject: text,+ text,+ locals: {+ action: {+ text: t('Manage your channel', userLanguage),+ url: channel.getClientManageUrl()+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/channel/collaborate-to-channel-utils.ts b/server/core/lib/notifier/shared/channel/collaborate-to-channel-utils.tsnew file mode 100644index 0000000000..0bdce827a4--- /dev/null+++ b/server/core/lib/notifier/shared/channel/collaborate-to-channel-utils.ts@@ -0,0 +1,31 @@+import { UserNotificationType_Type } from '@peertube/peertube-models'+import { UserNotificationModel } from '@server/models/user/user-notification.js'+import { MChannelAccountDefault, MChannelCollaboratorAccount } from '@server/types/models/index.js'+import { MUserId, UserNotificationModelForApi } from '@server/types/models/user/index.js'++export type NotificationCollaboratePayload = {+ collaborator: MChannelCollaboratorAccount+ channel: MChannelAccountDefault+}++export function buildCollaborateToChannelNotification (options: {+ user: MUserId+ payload: NotificationCollaboratePayload+ notificationType: UserNotificationType_Type+}): UserNotificationModelForApi {+ const { user, payload, notificationType } = options++ const notification = UserNotificationModel.build<UserNotificationModelForApi>({+ type: notificationType,++ userId: user.id,+ channelCollaboratorId: payload.collaborator.id+ })++ notification.VideoChannelCollaborator = Object.assign(payload.collaborator, {+ Account: payload.collaborator.Account,+ Channel: payload.channel+ })++ return notification+}diff --git a/server/core/lib/notifier/shared/channel/invited-to-collaborate-to-channel.ts b/server/core/lib/notifier/shared/channel/invited-to-collaborate-to-channel.tsnew file mode 100644index 0000000000..8e4b03f32e--- /dev/null+++ b/server/core/lib/notifier/shared/channel/invited-to-collaborate-to-channel.ts@@ -0,0 +1,76 @@+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 { AbstractNotification } from '../common/abstract-notification.js'+import { buildCollaborateToChannelNotification, NotificationCollaboratePayload } from './collaborate-to-channel-utils.js'++export class InvitedToCollaborateToChannel extends AbstractNotification<NotificationCollaboratePayload> {+ private user: MUserDefault+ private channelAccountMuted = false++ async prepare () {+ this.user = await UserModel.loadByAccountId(this.payload.collaborator.accountId)++ const hash = await AccountBlocklistModel.isAccountMutedByAccounts([ this.user.Account.id ], this.payload.channel.accountId)+ this.channelAccountMuted = hash[this.user.Account.id] === true+ }++ log () {+ logger.info(+ `Notifying user ${this.user.username} of invitation to collaborate on channel ${this.payload.channel.Actor.getIdentifier()}`+ )+ }++ isDisabled () {+ return false+ }++ getSetting (_user: MUserWithNotificationSetting) {+ if (this.channelAccountMuted) return UserNotificationSettingValue.NONE++ // Always notify+ return UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ }++ getTargetUsers () {+ return [ this.user ]+ }++ createNotification (user: MUserWithNotificationSetting) {+ return buildCollaborateToChannelNotification({+ user,+ payload: this.payload,+ notificationType: UserNotificationType.INVITED_TO_COLLABORATE_TO_CHANNEL+ })+ }++ // ---------------------------------------------------------------------------++ createEmail (user: MUserWithNotificationSetting) {+ const userLanguage = user.getLanguage()+ const to = { email: user.email, language: userLanguage }++ const { channel } = this.payload++ const text = t('{channelOwner} invited you to become a collaborator of channel {channelName}', userLanguage, {+ channelOwner: channel.Account.getDisplayName(),+ channelName: channel.getDisplayName()+ })++ return {+ to,+ subject: text,+ text,+ locals: {+ action: {+ text: t('Review the invitation', userLanguage),+ url: WEBSERVER.URL + '/my-account/notifications'+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/channel/refused-to-collaborate-to-channel.ts b/server/core/lib/notifier/shared/channel/refused-to-collaborate-to-channel.tsnew file mode 100644index 0000000000..4f8442502a--- /dev/null+++ b/server/core/lib/notifier/shared/channel/refused-to-collaborate-to-channel.ts@@ -0,0 +1,68 @@+import { UserNotificationSettingValue, UserNotificationType } from '@peertube/peertube-models'+import { t } from '@server/helpers/i18n.js'+import { logger } from '@server/helpers/logger.js'+import { UserModel } from '@server/models/user/user.js'+import { MUserDefault, MUserWithNotificationSetting } from '@server/types/models/index.js'+import { AbstractNotification } from '../common/abstract-notification.js'+import { buildCollaborateToChannelNotification, NotificationCollaboratePayload } from './collaborate-to-channel-utils.js'++export class RefusedToCollaborateToChannel extends AbstractNotification<NotificationCollaboratePayload> {+ private user: MUserDefault++ async prepare () {+ this.user = await UserModel.loadByAccountId(this.payload.channel.accountId)+ }++ log () {+ logger.info(+ `Notifying user ${this.user.username} of refused invitation to collaborate on channel ${this.payload.channel.Actor.getIdentifier()}`+ )+ }++ isDisabled () {+ return false+ }++ getSetting (_user: MUserWithNotificationSetting) {+ // Always notify+ return UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ }++ getTargetUsers () {+ return [ this.user ]+ }++ createNotification (user: MUserWithNotificationSetting) {+ return buildCollaborateToChannelNotification({+ user,+ payload: this.payload,+ notificationType: UserNotificationType.REFUSED_TO_COLLABORATE_TO_CHANNEL+ })+ }++ // ---------------------------------------------------------------------------++ createEmail (user: MUserWithNotificationSetting) {+ const userLanguage = user.getLanguage()+ const to = { email: user.email, language: userLanguage }++ const { channel, collaborator } = this.payload++ const text = t('{collaboratorName} refused your invitation to become a collaborator of {channelName}', userLanguage, {+ collaboratorName: collaborator.Account.getDisplayName(),+ channelName: channel.getDisplayName()+ })++ return {+ to,+ subject: text,+ text,+ locals: {+ action: {+ text: t('Manage your channel', userLanguage),+ url: channel.getClientManageUrl()+ }+ }+ }+ }+}diff --git a/server/core/lib/notifier/shared/comment/comment-mention.ts b/server/core/lib/notifier/shared/comment/comment-mention.tsindex b9f4d9eacc..62164a4aec 100644--- a/server/core/lib/notifier/shared/comment/comment-mention.ts+++ b/server/core/lib/notifier/shared/comment/comment-mention.ts@@ -40,7 +40,7 @@ export class CommentMention extends AbstractNotification<MCommentOwnerVideo, MUsthis.users = await UserModel.listByUsernames(extractedUsernames)- if (this.payload.Video.isOwned()) {+ if (this.payload.Video.isLocal()) {const userException = await UserModel.loadByVideoId(this.payload.videoId)this.users = this.users.filter(u => u.id !== userException.id)}diff --git a/server/core/lib/notifier/shared/comment/new-comment-for-video-owner.ts b/server/core/lib/notifier/shared/comment/new-comment-for-video-owner.tsindex 7a33b19187..4c946e643a 100644--- a/server/core/lib/notifier/shared/comment/new-comment-for-video-owner.ts+++ b/server/core/lib/notifier/shared/comment/new-comment-for-video-owner.ts@@ -21,7 +21,7 @@ export class NewCommentForVideoOwner extends AbstractNotification<MCommentOwnerV}isDisabled () {- if (this.payload.Video.isOwned() === false) return true+ if (this.payload.Video.isLocal() === false) return true// Not our user or user comments its own videoif (!this.user || this.payload.Account.userId === this.user.id) return truediff --git a/server/core/lib/notifier/shared/follow/auto-follow-for-instance.ts b/server/core/lib/notifier/shared/follow/auto-follow-for-instance.tsindex f6ea20f8e7..49ca97edca 100644--- a/server/core/lib/notifier/shared/follow/auto-follow-for-instance.ts+++ b/server/core/lib/notifier/shared/follow/auto-follow-for-instance.ts@@ -45,7 +45,7 @@ export class AutoFollowForInstance extends AbstractNotification<MActorFollowFullreturn {to,subject: t('Auto platform follow', to.language),- text: `Your platform automatically followed ${subscription.getIdentifier()}`,+ text: t('Your platform automatically followed {identifier}', to.language, { identifier: subscription.getIdentifier() }),locals: {action: {text: t('View subscription', to.language),diff --git a/server/core/lib/notifier/shared/follow/follow-for-user.ts b/server/core/lib/notifier/shared/follow/follow-for-user.tsindex 3e79a136cc..8dd37a9ee9 100644--- a/server/core/lib/notifier/shared/follow/follow-for-user.ts+++ b/server/core/lib/notifier/shared/follow/follow-for-user.ts@@ -24,7 +24,7 @@ export class FollowForUser extends AbstractNotification<MActorFollowFull> {}async isDisabled () {- if (this.payload.ActorFollowing.isOwned() === false) return true+ if (this.payload.ActorFollowing.isLocal() === false) return trueconst followerAccount = this.actorFollow.ActorFollower.Accountconst followerAccountWithActor = Object.assign(followerAccount, { Actor: this.actorFollow.ActorFollower })diff --git a/server/core/lib/notifier/shared/video-publication/new-video-or-live-for-subscribers.ts b/server/core/lib/notifier/shared/video-publication/new-video-or-live-for-subscribers.tsindex 1b59053301..db49787680 100644--- a/server/core/lib/notifier/shared/video-publication/new-video-or-live-for-subscribers.ts+++ b/server/core/lib/notifier/shared/video-publication/new-video-or-live-for-subscribers.ts@@ -65,12 +65,15 @@ export class NewVideoOrLiveForSubscribers extends AbstractNotification<MVideoAccprivate createVideoEmail (to: To, channelName: string, videoUrl: string) {return {to,- subject: channelName + ' just published a new video',- text: `Your subscription ${channelName} just published a new video: ${this.payload.name}.`,+ subject: t('{channelName} just published a new video', to.language, { channelName }),+ text: t('Your subscription {channelName} just published a new video: {videoName}.', to.language, {+ channelName,+ videoName: this.payload.name+ }),locals: {- title: channelName + ' just published a new video',+ title: t('{channelName} just published a new video', to.language, { channelName }),action: {- text: 'View video',+ text: t('View video', to.language),url: videoUrl}}diff --git a/server/core/lib/object-storage/shared/client.ts b/server/core/lib/object-storage/shared/client.tsindex 9e37ba10bc..0dacb5667b 100644--- a/server/core/lib/object-storage/shared/client.ts+++ b/server/core/lib/object-storage/shared/client.ts@@ -29,7 +29,7 @@ function getEndpointParsed () {let s3ClientPromise: Promise<S3Client>function getClient () {- if (s3ClientPromise) return s3ClientPromise+ if (s3ClientPromise !== undefined) return s3ClientPromises3ClientPromise = (async () => {const OBJECT_STORAGE = CONFIG.OBJECT_STORAGEdiff --git a/server/core/lib/thumbnail.ts b/server/core/lib/thumbnail.tsindex 2a26c16294..a4c1f2eeec 100644--- a/server/core/lib/thumbnail.ts+++ b/server/core/lib/thumbnail.ts@@ -4,10 +4,10 @@ import { logger, loggerTagsFactory } from '@server/helpers/logger.js'import Bluebird from 'bluebird'import { FfprobeData } from 'fluent-ffmpeg'import { remove } from 'fs-extra/esm'-import { join } from 'path'+import { extname, join } from 'path'import { generateImageFilename } from '../helpers/image-utils.js'import { CONFIG } from '../initializers/config.js'-import { ASSETS_PATH, PREVIEWS_SIZE, THUMBNAILS_SIZE } from '../initializers/constants.js'+import { ASSETS_PATH, MIMETYPES, PREVIEWS_SIZE, THUMBNAILS_SIZE } from '../initializers/constants.js'import { ThumbnailModel } from '../models/video/thumbnail.js'import { MVideoFile, MVideoThumbnail, MVideoUUID, MVideoWithAllFiles } from '../types/models/index.js'import { MThumbnail } from '../types/models/video/thumbnail.js'@@ -56,7 +56,7 @@ export function updateRemotePlaylistMiniatureFromUrl (options: {const type = ThumbnailType.MINIATURE// Only save the file URL if it is a remote playlist- const fileUrl = playlist.isOwned()+ const fileUrl = playlist.isLocal()? null: downloadUrl@@ -79,7 +79,12 @@ export function updateLocalVideoMiniatureFromExisting (options: {}) {const { inputPath, video, type, automaticallyGenerated, size, keepOriginal = false } = options- const { filename, outputPath, height, width, existingThumbnail } = buildMetadataFromVideo(video, type, size)+ const { filename, outputPath, height, width, existingThumbnail } = buildMetadataFromVideo({+ video,+ type,+ size,+ extension: getImageExtension(inputPath)+ })const thumbnailCreator = () => {return processImageFromWorker({ path: inputPath, destination: outputPath, newSize: { width, height }, keepOriginal })@@ -110,7 +115,7 @@ export function generateLocalVideoMiniature (options: {return VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(video), input => {// Get bigger images to generate first- const metadatas = types.map(type => buildMetadataFromVideo(video, type))+ const metadatas = types.map(type => buildMetadataFromVideo({ video, type })).sort((a, b) => {if (a.height < b.height) return 1if (a.height === b.height) return 0@@ -124,27 +129,30 @@ export function generateLocalVideoMiniature (options: {let thumbnailCreator: () => Promise<any>if (videoFile.isAudio()) {- thumbnailCreator = () => processImageFromWorker({- path: ASSETS_PATH.DEFAULT_AUDIO_BACKGROUND,- destination: outputPath,- newSize: { width, height },- keepOriginal: true- })+ thumbnailCreator = () =>+ processImageFromWorker({+ path: ASSETS_PATH.DEFAULT_AUDIO_BACKGROUND,+ destination: outputPath,+ newSize: { width, height },+ keepOriginal: true+ })} else if (biggestImagePath) {- thumbnailCreator = () => processImageFromWorker({- path: biggestImagePath,- destination: outputPath,- newSize: { width, height },- keepOriginal: true- })+ thumbnailCreator = () =>+ processImageFromWorker({+ path: biggestImagePath,+ destination: outputPath,+ newSize: { width, height },+ keepOriginal: true+ })} else {- thumbnailCreator = () => generateImageFromVideoFile({- fromPath: input,- folder: basePath,- imageName: filename,- size: { height, width },- ffprobe- })+ thumbnailCreator = () =>+ generateImageFromVideoFile({+ fromPath: input,+ folder: basePath,+ imageName: filename,+ size: { height, width },+ ffprobe+ })}if (!biggestImagePath) biggestImagePath = outputPath@@ -172,10 +180,16 @@ export function updateLocalVideoMiniatureFromUrl (options: {size?: ImageSize}) {const { downloadUrl, video, type, size } = options- const { filename: updatedFilename, basePath, height, width, existingThumbnail } = buildMetadataFromVideo(video, type, size)++ const { filename: updatedFilename, basePath, height, width, existingThumbnail } = buildMetadataFromVideo({+ video,+ type,+ size,+ extension: getImageExtension(downloadUrl)+ })// Only save the file URL if it is a remote video- const fileUrl = video.isOwned()+ const fileUrl = video.isLocal()? null: downloadUrl@@ -205,7 +219,12 @@ export function updateRemoteVideoThumbnail (options: {onDisk: boolean}) {const { fileUrl, video, type, size, onDisk } = options- const { filename: generatedFilename, height, width, existingThumbnail } = buildMetadataFromVideo(video, type, size)+ const { filename: generatedFilename, height, width, existingThumbnail } = buildMetadataFromVideo({+ video,+ type,+ size,+ extension: getImageExtension(fileUrl)+ })const thumbnail = existingThumbnail || new ThumbnailModel()@@ -276,13 +295,20 @@ function buildMetadataFromPlaylist (playlist: MVideoPlaylistThumbnail, size: Ima}}-function buildMetadataFromVideo (video: MVideoThumbnail, type: ThumbnailType_Type, size?: ImageSize) {+function buildMetadataFromVideo (options: {+ video: MVideoThumbnail+ type: ThumbnailType_Type+ extension?: string+ size?: ImageSize+}) {+ const { video, type, extension, size } = options+const existingThumbnail = Array.isArray(video.Thumbnails)? video.Thumbnails.find(t => t.type === type): undefinedif (type === ThumbnailType.MINIATURE) {- const filename = generateImageFilename()+ const filename = generateImageFilename(extension)const basePath = CONFIG.STORAGE.THUMBNAILS_DIRreturn {@@ -297,7 +323,7 @@ function buildMetadataFromVideo (video: MVideoThumbnail, type: ThumbnailType_Typ}if (type === ThumbnailType.PREVIEW) {- const filename = generateImageFilename()+ const filename = generateImageFilename(extension)const basePath = CONFIG.STORAGE.PREVIEWS_DIRreturn {@@ -390,3 +416,13 @@ async function generateImageFromVideoFile (options: {throw err}}++function getImageExtension (input: string) {+ const extension = extname(input).toLowerCase()++ if (MIMETYPES.IMAGE.EXT_MIMETYPE[extension]) return extension++ logger.warn('Cannot determine image extension from input ' + input, lTags())++ return '.jpg'+}diff --git a/server/core/lib/user-import-export/exporters/channels-exporter.ts b/server/core/lib/user-import-export/exporters/channels-exporter.tsindex af416a2a69..78854613dc 100644--- a/server/core/lib/user-import-export/exporters/channels-exporter.ts+++ b/server/core/lib/user-import-export/exporters/channels-exporter.ts@@ -12,7 +12,7 @@ export class ChannelsExporter extends ActorExporter<ChannelExportJSON> {const channelsJSON: ChannelExportJSON['channels'] = []let staticFiles: ExportResult<ChannelExportJSON>['staticFiles'] = []- const channels = await VideoChannelModel.listAllByAccount(this.user.Account.id)+ const channels = await VideoChannelModel.listAllOwnedByAccount(this.user.Account.id)for (const channel of channels) {try {diff --git a/server/core/lib/user-import-export/exporters/followers-exporter.ts b/server/core/lib/user-import-export/exporters/followers-exporter.tsindex 0692ed4f23..02147266ad 100644--- a/server/core/lib/user-import-export/exporters/followers-exporter.ts+++ b/server/core/lib/user-import-export/exporters/followers-exporter.ts@@ -3,15 +3,14 @@ import { FollowersExportJSON } from '@peertube/peertube-models'import { ActorFollowModel } from '@server/models/actor/actor-follow.js'import { VideoChannelModel } from '@server/models/video/video-channel.js'-export class FollowersExporter extends AbstractUserExporter <FollowersExportJSON> {-+export class FollowersExporter extends AbstractUserExporter<FollowersExportJSON> {async export () {let followersJSON = this.formatFollowersJSON(await ActorFollowModel.listAcceptedFollowersForExport(this.user.Account.actorId),this.user.Account.Actor.getFullIdentifier())- const channels = await VideoChannelModel.listAllByAccount(this.user.Account.id)+ const channels = await VideoChannelModel.listAllOwnedByAccount(this.user.Account.id)for (const channel of channels) {followersJSON = followersJSON.concat(diff --git a/server/core/lib/user-import-export/exporters/videos-exporter.ts b/server/core/lib/user-import-export/exporters/videos-exporter.tsindex b4394cb4df..f1b8b4b1bb 100644--- a/server/core/lib/user-import-export/exporters/videos-exporter.ts+++ b/server/core/lib/user-import-export/exporters/videos-exporter.ts@@ -56,7 +56,7 @@ export class VideosExporter extends AbstractUserExporter<VideoExportJSON> {const activityPubOutbox: ActivityCreate<VideoObject>[] = []let staticFiles: ExportResult<VideoExportJSON>['staticFiles'] = []- const channels = await VideoChannelModel.listAllByAccount(this.user.Account.id)+ const channels = await VideoChannelModel.listAllOwnedByAccount(this.user.Account.id)for (const channel of channels) {const videoIds = await VideoModel.getAllIdsFromChannel(channel, USER_EXPORT_MAX_ITEMS)diff --git a/server/core/lib/video-comment.ts b/server/core/lib/video-comment.tsindex 2c65b387e9..83c396064c 100644--- a/server/core/lib/video-comment.ts+++ b/server/core/lib/video-comment.ts@@ -11,7 +11,9 @@ import {MComment,MCommentFormattable,MCommentOwnerVideo,- MCommentOwnerVideoReply, MUserAccountId, MVideoAccountLight,+ MCommentOwnerVideoReply,+ MUserAccountId,+ MVideoAccountLight,MVideoFullLight} from '../types/models/index.js'import { sendCreateVideoCommentIfNeeded, sendDeleteVideoComment, sendReplyApproval } from './activitypub/send/index.js'@@ -29,7 +31,7 @@ export async function removeComment (commentArg: MComment, req: express.Request,videoCommentInstanceBefore = cloneDeep(comment)- if (comment.isOwned() || comment.Video.isOwned()) {+ if (comment.isLocal() || comment.Video.isLocal()) {await sendDeleteVideoComment(comment, t)}@@ -52,7 +54,7 @@ export async function approveComment (commentArg: MComment) {comment.heldForReview = falseawait comment.save({ transaction: t })- if (comment.isOwned()) {+ if (comment.isLocal()) {await sendCreateVideoCommentIfNeeded(comment, t)} else {sendReplyApproval(comment, 'ApproveReply')@@ -159,13 +161,13 @@ export async function shouldCommentBeHeldForReview (options: {}) {const { user, video, transaction, automaticTags } = options- if (video.isOwned() && user) {+ if (video.isLocal() && user) {if (user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)) return falseif (user.Account.id === video.VideoChannel.accountId) return false}if (video.commentsPolicy === VideoCommentPolicy.REQUIRES_APPROVAL) return true- if (video.isOwned() !== true) return false+ if (video.isLocal() !== true) return falseconst ownerAccountTags = automaticTags.filter(t => t.accountId === video.VideoChannel.accountId)diff --git a/server/core/lib/video-download.ts b/server/core/lib/video-download.tsindex f6f14f492f..4be5a9c4e9 100644--- a/server/core/lib/video-download.ts+++ b/server/core/lib/video-download.ts@@ -217,7 +217,7 @@ export class VideoDownload {private async buildCoverInput () {const preview = this.video.getPreview()- if (this.video.isOwned()) return { coverPath: preview?.getPath() }+ if (this.video.isLocal()) return { coverPath: preview?.getPath() }if (preview.fileUrl) {const destination = VideoPathManager.Instance.buildTMPDestination(preview.filename)diff --git a/server/core/lib/video-playlist.ts b/server/core/lib/video-playlist.tsindex 32b7e7da06..8ced4eab19 100644--- a/server/core/lib/video-playlist.ts+++ b/server/core/lib/video-playlist.ts@@ -39,7 +39,7 @@ export async function generateThumbnailForPlaylist (videoPlaylist: MVideoPlaylis// Ensure the file is on diskconst videoMiniaturePermanentFileCache = new VideoMiniaturePermanentFileCache()- const inputPath = videoMiniature.isOwned()+ const inputPath = videoMiniature.isLocal()? videoMiniature.getPath(): await videoMiniaturePermanentFileCache.downloadRemoteFile(videoMiniature)diff --git a/server/core/lib/views/shared/video-views.ts b/server/core/lib/views/shared/video-views.tsindex 078aca8360..b8a0a2c549 100644--- a/server/core/lib/views/shared/video-views.ts+++ b/server/core/lib/views/shared/video-views.ts@@ -12,7 +12,6 @@ import { CONFIG } from '@server/initializers/config.js'const lTags = loggerTagsFactory('views')export class VideoViews {-private readonly viewsCache = new LRUCache<string, boolean>({max: 10_000,ttl: VIEW_LIFETIME.VIEW@@ -58,7 +57,7 @@ export class VideoViews {private async addView (video: MVideoImmutable) {const promises: Promise<any>[] = []- if (video.isOwned()) {+ if (video.isLocal()) {promises.push(Redis.Instance.addLocalVideoView(video.id))}diff --git a/server/core/middlewares/auth.ts b/server/core/middlewares/auth.tsindex c0460b5464..2d8f940e87 100644--- a/server/core/middlewares/auth.ts+++ b/server/core/middlewares/auth.ts@@ -55,36 +55,41 @@ export function authenticateSocket (socket: Socket, next: (err?: any) => void) {.catch(err => logger.error('Cannot get access token.', { err }))}-export function authenticatePromise (options: {+export function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {+ if (req.header('authorization')) return authenticate(req, res, next)++ res.locals.authenticated = false++ return next()+}++export function authenticateOrFail (options: {req: express.Requestres: express.ResponseerrorMessage?: stringerrorStatus?: HttpStatusCodeTypeerrorType?: ServerErrorCodeType}) {- const { req, res, errorMessage = 'Not authenticated', errorStatus = HttpStatusCode.UNAUTHORIZED_401, errorType } = options- return new Promise<void>(resolve => {+ const { req, res, errorMessage = req.t('Authentication is required'), errorStatus = HttpStatusCode.UNAUTHORIZED_401, errorType } = options++ return new Promise<boolean>(resolve => {// Already authenticated? (or tried to)- if (res.locals.oauth?.token.User) return resolve()+ if (res.locals.oauth?.token.User) return resolve(true)- if (res.locals.authenticated === false) {- return res.fail({- status: errorStatus,- type: errorType,- message: errorMessage- })- }+ if (res.locals.authenticated === false || !req.header('authorization')) {+ res.fail({ status: errorStatus, type: errorType, message: errorMessage })- authenticate(req, res, () => resolve())- })-}+ return resolve(false)+ }-export function optionalAuthenticate (req: express.Request, res: express.Response, next: express.NextFunction) {- if (req.header('authorization')) return authenticate(req, res, next)+ authenticate(req, res, () => {+ if (res.locals.oauth?.token.User) return resolve(true)- res.locals.authenticated = false+ res.fail({ status: errorStatus, type: errorType, message: errorMessage })- return next()+ resolve(false)+ })+ })}// ---------------------------------------------------------------------------diff --git a/server/core/middlewares/user-right.ts b/server/core/middlewares/user-right.tsindex 4240fab2a1..7554368c67 100644--- a/server/core/middlewares/user-right.ts+++ b/server/core/middlewares/user-right.ts@@ -2,11 +2,11 @@ import express from 'express'import { HttpStatusCode, UserRightType } from '@peertube/peertube-models'import { logger } from '../helpers/logger.js'-function ensureUserHasRight (userRight: UserRightType) {+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 ${userRight} to access to ${req.path}.`+ const message = `User ${user.username} does not have right (No. ${userRight}) to access to ${req.path}.`logger.info(message)return res.fail({@@ -18,9 +18,3 @@ function ensureUserHasRight (userRight: UserRightType) {return next()}}--// -----------------------------------------------------------------------------export {- ensureUserHasRight-}diff --git a/server/core/middlewares/validators/abuse.ts b/server/core/middlewares/validators/abuse.tsindex 12c316ef8d..a3b188d4cf 100644--- a/server/core/middlewares/validators/abuse.ts+++ b/server/core/middlewares/validators/abuse.ts@@ -57,7 +57,7 @@ const abuseReportValidator = [const body: AbuseCreate = req.bodyif (body.video?.id && !await doesVideoExist(body.video.id, res)) return- if (body.account?.id && !await doesAccountIdExist({ id: body.account.id, req, res, checkIsLocal: false, checkManage: false })) return+ if (body.account?.id && !await doesAccountIdExist({ id: body.account.id, req, res, checkIsLocal: false, checkCanManage: false })) returnif (body.comment?.id && !await doesCommentIdExist(body.comment.id, res)) returnif (!body.video?.id && !body.account?.id && !body.comment?.id) {@@ -187,7 +187,7 @@ const getAbuseValidator = [const checkAbuseValidForMessagesValidator = [(req: express.Request, res: express.Response, next: express.NextFunction) => {const abuse = res.locals.abuse- if (abuse.ReporterAccount.isOwned() === false) {+ if (abuse.ReporterAccount.isLocal() === false) {return res.fail({ message: 'This abuse was created by a user of your instance.' })}diff --git a/server/core/middlewares/validators/account.ts b/server/core/middlewares/validators/account.tsindex 9458bd7b29..86da6857ee 100644--- a/server/core/middlewares/validators/account.ts+++ b/server/core/middlewares/validators/account.ts@@ -1,13 +1,13 @@import { UserRight } from '@peertube/peertube-models'import express from 'express'import { param } from 'express-validator'-import { areValidationErrors, checkUserCanManageAccount, doesAccountHandleExist } from './shared/index.js'+import { areValidationErrors, checkCanManageAccount, doesAccountHandleExist } from './shared/index.js'export const accountHandleGetValidatorFactory = (options: {- checkManage: boolean+ checkCanManage: booleancheckIsLocal: boolean}) => {- const { checkManage, checkIsLocal } = options+ const { checkCanManage, checkIsLocal } = optionsreturn [param('handle')@@ -15,12 +15,12 @@ export const accountHandleGetValidatorFactory = (options: {async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountHandleExist({ handle: req.params.handle, req, res, checkIsLocal, checkManage })) return+ if (!await doesAccountHandleExist({ handle: req.params.handle, req, res, checkIsLocal, checkCanManage })) return- if (options.checkManage) {+ if (checkCanManage) {const user = res.locals.oauth.token.User- if (!checkUserCanManageAccount({ account: res.locals.account, user, req, res, specialRight: UserRight.MANAGE_USERS })) {+ if (!checkCanManageAccount({ account: res.locals.account, user, req, res, specialRight: UserRight.MANAGE_USERS })) {return false}}diff --git a/server/core/middlewares/validators/automatic-tags.ts b/server/core/middlewares/validators/automatic-tags.tsindex fdd8fa371a..a60d84c24f 100644--- a/server/core/middlewares/validators/automatic-tags.ts+++ b/server/core/middlewares/validators/automatic-tags.ts@@ -12,7 +12,7 @@ export const manageAccountAutomaticTagsValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: true, checkManage: true })) return+ if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: true, checkCanManage: true })) returnreturn next()}diff --git a/server/core/middlewares/validators/blocklist.ts b/server/core/middlewares/validators/blocklist.tsindex 01e9712efe..1c92255be0 100644--- a/server/core/middlewares/validators/blocklist.ts+++ b/server/core/middlewares/validators/blocklist.ts@@ -17,7 +17,7 @@ const blockAccountValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountHandleExist({ handle: req.body.accountName, req, res, checkIsLocal: false, checkManage: false })) return+ if (!await doesAccountHandleExist({ handle: req.body.accountName, req, res, checkIsLocal: false, checkCanManage: false })) returnconst user = res.locals.oauth.token.Userconst accountToBlock = res.locals.account@@ -40,7 +40,7 @@ const unblockAccountByAccountValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: false, checkManage: false })) return+ if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: false, checkCanManage: false })) returnconst user = res.locals.oauth.token.Userconst targetAccount = res.locals.account@@ -56,7 +56,7 @@ const unblockAccountByServerValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: false, checkManage: false })) return+ if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: false, checkCanManage: false })) returnconst serverActor = await getServerActor()const targetAccount = res.locals.accountdiff --git a/server/core/middlewares/validators/bulk.ts b/server/core/middlewares/validators/bulk.tsindex c9162ebd58..c99c9f3cb5 100644--- a/server/core/middlewares/validators/bulk.ts+++ b/server/core/middlewares/validators/bulk.ts@@ -12,7 +12,7 @@ export const bulkRemoveCommentsOfValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountHandleExist({ handle: req.body.accountName, req, res, checkIsLocal: false, checkManage: false })) return+ if (!await doesAccountHandleExist({ handle: req.body.accountName, req, res, checkIsLocal: false, checkCanManage: false })) returnconst user = res.locals.oauth.token.Userconst body = req.body as BulkRemoveCommentsOfBodydiff --git a/server/core/middlewares/validators/feeds.ts b/server/core/middlewares/validators/feeds.tsindex 9b260fafa6..bff1e21faf 100644--- a/server/core/middlewares/validators/feeds.ts+++ b/server/core/middlewares/validators/feeds.ts@@ -14,7 +14,7 @@ import {doesVideoExist} from './shared/index.js'-const feedsFormatValidator = [+export const feedsFormatValidator = [param('format').optional().custom(isValidRSSFeed).withMessage('Should have a valid format (rss, atom, json)'),@@ -29,7 +29,7 @@ const feedsFormatValidator = [}]-function setFeedFormatContentType (req: express.Request, res: express.Response, next: express.NextFunction) {+export function setFeedFormatContentType (req: express.Request, res: express.Response, next: express.NextFunction) {const format = req.query.format || req.params.format || 'rss'let acceptableContentTypes: string[]@@ -46,13 +46,13 @@ function setFeedFormatContentType (req: express.Request, res: express.Response,return feedContentTypeResponse(req, res, next, acceptableContentTypes)}-function setFeedPodcastContentType (req: express.Request, res: express.Response, next: express.NextFunction) {+export function setFeedPodcastContentType (req: express.Request, res: express.Response, next: express.NextFunction) {const acceptableContentTypes = [ 'application/rss+xml', 'application/xml', 'text/xml' ]return feedContentTypeResponse(req, res, next, acceptableContentTypes)}-function feedContentTypeResponse (+export function feedContentTypeResponse (req: express.Request,res: express.Response,next: express.NextFunction,@@ -72,7 +72,7 @@ function feedContentTypeResponse (// ----------------------------------------------------------------------------const feedsAccountOrChannelFiltersValidator = [+export const feedsAccountOrChannelFiltersValidator = [query('accountId').optional().custom(isIdValid),@@ -91,7 +91,7 @@ const feedsAccountOrChannelFiltersValidator = [if (areValidationErrors(req, res)) returnconst { accountId, videoChannelId, accountName, videoChannelName } = req.query- const commonOptions = { req, res, checkManage: false, checkIsLocal: false }+ const commonOptions = { req, res, checkCanManage: false, checkIsLocal: false, checkIsOwner: false }if (accountId && !await doesAccountIdExist({ id: accountId, ...commonOptions })) returnif (videoChannelId && !await doesChannelIdExist({ id: videoChannelId, ...commonOptions })) return@@ -105,13 +105,23 @@ const feedsAccountOrChannelFiltersValidator = [// ----------------------------------------------------------------------------const videoFeedsPodcastValidator = [+export const videoFeedsPodcastValidator = [query('videoChannelId').custom(isIdValid),async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesChannelIdExist({ id: req.query.videoChannelId, checkManage: false, checkIsLocal: false, req, res })) return++ if (+ !await doesChannelIdExist({+ id: req.query.videoChannelId,+ checkCanManage: false,+ checkIsLocal: false,+ checkIsOwner: false,+ req,+ res+ })+ ) returnreturn next()}@@ -119,7 +129,7 @@ const videoFeedsPodcastValidator = [// ----------------------------------------------------------------------------const videoSubscriptionFeedsValidator = [+export const videoSubscriptionFeedsValidator = [query('accountId').custom(isIdValid),@@ -129,14 +139,14 @@ const videoSubscriptionFeedsValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountIdExist({ id: req.query.accountId, req, res, checkIsLocal: true, checkManage: false })) return+ if (!await doesAccountIdExist({ id: req.query.accountId, req, res, checkIsLocal: true, checkCanManage: false })) returnif (!await doesUserFeedTokenCorrespond(res.locals.account.userId, req.query.token, res)) returnreturn next()}]-const videoCommentsFeedsValidator = [+export const videoCommentsFeedsValidator = [query('videoId').optional().customSanitizer(toCompleteUUID)@@ -157,15 +167,3 @@ const videoCommentsFeedsValidator = [return next()}]--// -----------------------------------------------------------------------------export {- feedsAccountOrChannelFiltersValidator,- feedsFormatValidator,- setFeedFormatContentType,- setFeedPodcastContentType,- videoCommentsFeedsValidator,- videoFeedsPodcastValidator,- videoSubscriptionFeedsValidator-}diff --git a/server/core/middlewares/validators/player-settings.ts b/server/core/middlewares/validators/player-settings.tsindex e39cdd8a76..539b28c3b4 100644--- a/server/core/middlewares/validators/player-settings.ts+++ b/server/core/middlewares/validators/player-settings.ts@@ -3,9 +3,9 @@ import { isBooleanValid, toBooleanOrNull } from '@server/helpers/custom-validatoimport { isPlayerChannelThemeSettingValid, isPlayerVideoThemeSettingValid } from '@server/helpers/custom-validators/player-settings.js'import express from 'express'import { body, query } from 'express-validator'-import { checkUserCanManageAccount } from './shared/users.js'import { areValidationErrors, isValidVideoIdParam } from './shared/utils.js'-import { checkCanSeeVideo, checkUserCanManageVideo, doesVideoExist } from './shared/videos.js'+import { checkCanManageChannel } from './shared/video-channels.js'+import { checkCanManageVideo, checkCanSeeVideo, doesVideoExist } from './shared/videos.js'export const getVideoPlayerSettingsValidator = [isValidVideoIdParam('videoId'),@@ -28,7 +28,17 @@ export const getVideoPlayerSettingsValidator = [if (raw === true) {const user = res.locals.oauth?.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) return}return next()@@ -41,14 +51,25 @@ export const getChannelPlayerSettingsValidator = [.customSanitizer(toBooleanOrNull).custom(isBooleanValid),- (req: express.Request, res: express.Response, next: express.NextFunction) => {+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) returnif (req.query.raw === true) {- const account = res.locals.videoChannel.Accountconst user = res.locals.oauth?.token.User- if (!checkUserCanManageAccount({ account, user, req, res, specialRight: UserRight.MANAGE_ANY_VIDEO_CHANNEL })) return false+ if (+ !await checkCanManageChannel({+ channel: res.locals.videoChannel,+ user,+ req,+ res,+ checkCanManage: true,+ checkIsOwner: false,+ specialRight: UserRight.MANAGE_ANY_VIDEO_CHANNEL+ })+ ) {+ return false+ }}return next()@@ -64,7 +85,17 @@ export const updateVideoPlayerSettingsValidator = [if (!await doesVideoExist(req.params.videoId, res, 'all')) returnconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) returnreturn next()}diff --git a/server/core/middlewares/validators/shared/accounts.ts b/server/core/middlewares/validators/shared/accounts.tsindex 14f0503e6a..67837045a8 100644--- a/server/core/middlewares/validators/shared/accounts.ts+++ b/server/core/middlewares/validators/shared/accounts.ts@@ -3,34 +3,34 @@ import { HttpStatusCode, UserRight } from '@peertube/peertube-models'import { AccountModel } from '@server/models/account/account.js'import { MAccountDefault } from '@server/types/models/index.js'import { Request, Response } from 'express'-import { checkUserCanManageAccount } from './users.js'+import { checkCanManageAccount } from './users.js'export async function doesAccountIdExist (options: {id: string | numberreq: Requestres: Response- checkManage: boolean // Also check the user can manage the account+ checkCanManage: boolean // Also check the user can manage the accountcheckIsLocal: boolean // Also check this is a local channel}) {- const { id, req, res, checkIsLocal, checkManage } = options+ const { id, req, res, checkIsLocal, checkCanManage } = optionsconst account = await AccountModel.load(forceNumber(id))- return doesAccountExist({ account, req, res, checkIsLocal, checkManage })+ return doesAccountExist({ account, req, res, checkIsLocal, checkCanManage })}export async function doesAccountHandleExist (options: {handle: stringreq: Requestres: Response- checkManage: boolean // Also check the user can manage the account+ checkCanManage: boolean // Also check the user can manage the accountcheckIsLocal: boolean // Also check this is a local channel}) {- const { handle, req, res, checkIsLocal, checkManage } = options+ const { handle, req, res, checkIsLocal, checkCanManage } = optionsconst account = await AccountModel.loadByHandle(handle)- return doesAccountExist({ account, req, res, checkIsLocal, checkManage })+ return doesAccountExist({ account, req, res, checkIsLocal, checkCanManage })}// ---------------------------------------------------------------------------@@ -41,10 +41,10 @@ function doesAccountExist (options: {account: MAccountDefaultreq: Requestres: Response- checkManage: boolean+ checkCanManage: booleancheckIsLocal: boolean}) {- const { account, req, res, checkIsLocal, checkManage } = options+ const { account, req, res, checkIsLocal, checkCanManage } = optionsif (!account) {res.fail({@@ -54,15 +54,15 @@ function doesAccountExist (options: {return false}- if (checkManage) {+ if (checkCanManage) {const user = res.locals.oauth.token.User- if (!checkUserCanManageAccount({ account, user, req, res, specialRight: UserRight.MANAGE_USERS })) {+ if (!checkCanManageAccount({ account, user, req, res, specialRight: UserRight.MANAGE_USERS })) {return false}}- if (checkIsLocal && account.Actor.isOwned() === false) {+ if (checkIsLocal && account.Actor.isLocal() === false) {res.fail({status: HttpStatusCode.FORBIDDEN_403,message: 'This account is not owned.'diff --git a/server/core/middlewares/validators/shared/users.ts b/server/core/middlewares/validators/shared/users.tsindex 20c1ff9d2c..02f1cbdccb 100644--- a/server/core/middlewares/validators/shared/users.ts+++ b/server/core/middlewares/validators/shared/users.ts@@ -91,17 +91,17 @@ export async function checkUserExist (finder: () => Promise<MUserDefault>, res:return true}-export function checkUserCanManageAccount (options: {+export function checkCanManageAccount (options: {user: MUserAccountIdaccount: MAccountIdspecialRight: UserRightTypereq: express.Request- res: express.Response+ res: express.Response | null}) {const { user, account, specialRight, res, req } = optionsif (!user) {- res.fail({+ res?.fail({status: HttpStatusCode.UNAUTHORIZED_401,message: req.t('Authentication is required')})@@ -111,18 +111,9 @@ export function checkUserCanManageAccount (options: {if (account.id === user.Account.id) return trueif (specialRight && user.hasRight(specialRight) === true) return true- if (!specialRight) {- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: req.t('Only the owner of this account can manage this account resource.')- })-- return false- }-- res.fail({+ res?.fail({status: HttpStatusCode.FORBIDDEN_403,- message: req.t('Only a user with sufficient right can access this account resource.')+ message: req.t('Only a user with sufficient right can manage this account resource.')})return falsediff --git a/server/core/middlewares/validators/shared/video-channels.ts b/server/core/middlewares/validators/shared/video-channels.tsindex c5e5d3b485..c81e3f1ba5 100644--- a/server/core/middlewares/validators/shared/video-channels.ts+++ b/server/core/middlewares/validators/shared/video-channels.ts@@ -1,70 +1,119 @@-import { HttpStatusCode, UserRight } from '@peertube/peertube-models'+import { HttpStatusCode, UserRight, UserRightType } from '@peertube/peertube-models'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'import { VideoChannelModel } from '@server/models/video/video-channel.js'-import { MChannelBannerAccountDefault } from '@server/types/models/index.js'+import { MChannelBannerAccountDefault, MChannelUserId, MUserAccountId } from '@server/types/models/index.js'import express from 'express'-import { checkUserCanManageAccount } from './users.js'+import { checkCanManageAccount } from './users.js'-export async function doesChannelIdExist (options: {- id: number- checkManage: boolean // Also check the user can manage the account- checkIsLocal: boolean // Also check this is a local channel+type CommonOptions = {+ checkCanManage: boolean // Also check the user can manage the account+ checkIsOwner: boolean // Also check this is the owner of the channelreq: express.Requestres: express.Response-}) {- const { id, checkManage, checkIsLocal, req, res } = options+ specialRight?: UserRightType+}++export async function doesChannelIdExist (+ options: CommonOptions & {+ id: number+ checkIsLocal: boolean // Also check this is a local channel+ }+) {+ const { id, checkCanManage, checkIsLocal, checkIsOwner, req, res, specialRight } = optionsconst channel = await VideoChannelModel.loadAndPopulateAccount(+id)- return processVideoChannelExist({ channel, checkManage, checkIsLocal, req, res })+ return processVideoChannelExist({ channel, checkCanManage, checkIsLocal, checkIsOwner, req, res, specialRight })}-export async function doesChannelHandleExist (options: {- handle: string- checkManage: boolean // Also check the user can manage the account- checkIsLocal: boolean // Also check this is a local channel- req: express.Request- res: express.Response-}) {- const { handle, checkManage, checkIsLocal, req, res } = options+export async function doesChannelHandleExist (+ options: CommonOptions & {+ handle: string+ checkIsLocal: boolean // Also check this is a local channel+ }+) {+ const { handle, checkCanManage, checkIsLocal, checkIsOwner, req, res, specialRight } = optionsconst channel = await VideoChannelModel.loadByHandleAndPopulateAccount(handle)- return processVideoChannelExist({ channel, checkManage, checkIsLocal, req, res })+ return processVideoChannelExist({ channel, checkCanManage, checkIsLocal, checkIsOwner, req, res, specialRight })}-// ----------------------------------------------------------------------------// Private-// -----------------------------------------------------------------------------function processVideoChannelExist (options: {- channel: MChannelBannerAccountDefault- req: express.Request- res: express.Response- checkManage: boolean- checkIsLocal: boolean-}) {- const { channel, req, res, checkManage, checkIsLocal } = options+export async function checkCanManageChannel (+ options: CommonOptions & {+ user: MUserAccountId+ channel: MChannelUserId+ }+) {+ const { channel, user, req, res, checkCanManage, checkIsOwner, specialRight = UserRight.MANAGE_ANY_VIDEO_CHANNEL } = optionsif (!channel) {- res.fail({+ res?.fail({status: HttpStatusCode.NOT_FOUND_404,message: req.t('Video channel not found')})return false}- if (checkManage) {- const user = res.locals.oauth.token.User-- if (!checkUserCanManageAccount({ account: channel.Account, user, req, res, specialRight: UserRight.MANAGE_ANY_VIDEO_CHANNEL })) {+ if (checkIsOwner || checkCanManage) {+ if (!user) {+ res?.fail({+ status: HttpStatusCode.UNAUTHORIZED_401,+ message: req.t('Authentication is required')+ })return false}++ const isOwner = checkCanManageAccount({+ account: channel.Account,+ user,+ req,+ res: null,+ specialRight+ })++ if (!isOwner) {+ if (checkIsOwner) {+ res?.fail({+ status: HttpStatusCode.FORBIDDEN_403,+ message: req.t('This user has not owner rights on this channel')+ })++ return false+ }++ if (checkCanManage && !await VideoChannelCollaboratorModel.isCollaborator({ user, channel })) {+ res?.fail({+ status: HttpStatusCode.FORBIDDEN_403,+ message: req.t('This user cannot manage this channel')+ })+ return false+ }+ }}- if (checkIsLocal && channel.Actor.isOwned() === false) {+ return true+}++// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------++async function processVideoChannelExist (+ options: CommonOptions & {+ channel: MChannelBannerAccountDefault+ checkIsLocal: boolean // Also check this is a local channel+ }+) {+ const { channel, req, res, checkCanManage, checkIsLocal, checkIsOwner, specialRight = UserRight.MANAGE_ANY_VIDEO_CHANNEL } = options++ const user = res.locals.oauth?.token.User+ if (!await checkCanManageChannel({ channel, user, req, res, checkCanManage, checkIsOwner, specialRight })) return false++ if (checkIsLocal && channel.Actor.isLocal() === false) {res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: req.t('This channel is not owned.')+ message: req.t('The channel must be local.')})return falsediff --git a/server/core/middlewares/validators/shared/video-ownerships.ts b/server/core/middlewares/validators/shared/video-ownerships.tsindex 9f3d7b2c23..fcc2c21acf 100644--- a/server/core/middlewares/validators/shared/video-ownerships.ts+++ b/server/core/middlewares/validators/shared/video-ownerships.ts@@ -3,14 +3,14 @@ import { VideoChangeOwnershipModel } from '@server/models/video/video-change-ownimport { forceNumber } from '@peertube/peertube-core-utils'import { HttpStatusCode } from '@peertube/peertube-models'-async function doesChangeVideoOwnershipExist (idArg: number | string, res: express.Response) {+export async function doesChangeVideoOwnershipExist (idArg: number | string, req: express.Request, res: express.Response) {const id = forceNumber(idArg)const videoChangeOwnership = await VideoChangeOwnershipModel.load(id)if (!videoChangeOwnership) {res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Video change ownership not found'+ message: req.t('Video change ownership not found')})return false}@@ -19,7 +19,3 @@ async function doesChangeVideoOwnershipExist (idArg: number | string, res: exprereturn true}--export {- doesChangeVideoOwnershipExist-}diff --git a/server/core/middlewares/validators/shared/video-passwords.ts b/server/core/middlewares/validators/shared/video-passwords.tsindex dc82be572d..4d250e8e48 100644--- a/server/core/middlewares/validators/shared/video-passwords.ts+++ b/server/core/middlewares/validators/shared/video-passwords.ts@@ -1,22 +1,24 @@-import express from 'express'-import { HttpStatusCode, UserRight, VideoPrivacy } from '@peertube/peertube-models'import { forceNumber } from '@peertube/peertube-core-utils'+import { HttpStatusCode, UserRight, VideoPrivacy } from '@peertube/peertube-models'+import { getVideoWithAttributes } from '@server/helpers/video.js'import { VideoPasswordModel } from '@server/models/video/video-password.js'+import { MUserAccountId, MVideoAccountLight } from '@server/types/models/index.js'+import express from 'express'import { header } from 'express-validator'-import { getVideoWithAttributes } from '@server/helpers/video.js'+import { checkCanManageVideo } from './videos.js'-function isValidVideoPasswordHeader () {+export function isValidVideoPasswordHeader () {return header('x-peertube-video-password').optional().isString()}-function checkVideoIsPasswordProtected (res: express.Response) {+export function checkVideoIsPasswordProtected (req: express.Request, res: express.Response) {const video = getVideoWithAttributes(res)if (video.privacy !== VideoPrivacy.PASSWORD_PROTECTED) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Video is not password protected'+ message: req.t('Video is not password protected')})return false}@@ -24,15 +26,21 @@ function checkVideoIsPasswordProtected (res: express.Response) {return true}-async function doesVideoPasswordExist (idArg: number | string, res: express.Response) {+export async function doesVideoPasswordExist (options: {+ id: number | string+ req: express.Request+ res: express.Response+}) {+ const { req, res } = options+const video = getVideoWithAttributes(res)- const id = forceNumber(idArg)+ const id = forceNumber(options.id)const videoPassword = await VideoPasswordModel.loadByIdAndVideo({ id, videoId: video.id })if (!videoPassword) {res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Video password not found'+ message: req.t('Video password not found')})return false}@@ -42,39 +50,23 @@ async function doesVideoPasswordExist (idArg: number | string, res: express.Respreturn true}-async function isVideoPasswordDeletable (res: express.Response) {- const user = res.locals.oauth.token.User- const userAccount = user.Account- const video = res.locals.videoAll-- // Check if the user who did the request is able to delete the video passwords- if (- user.hasRight(UserRight.UPDATE_ANY_VIDEO) === false && // Not a moderator- video.VideoChannel.accountId !== userAccount.id // Not the video owner- ) {- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot remove passwords of another user\'s video'- })- return false- }+export async function checkCanDeleteVideoPassword (options: {+ user: MUserAccountId+ video: MVideoAccountLight+ req: express.Request+ res: express.Response+}) {+ const { user, video, req, res } = optionsconst passwordCount = await VideoPasswordModel.countByVideoId(video.id)if (passwordCount <= 1) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Cannot delete the last password of the protected video'+ message: req.t('Cannot delete the last password of the protected video')})return false}- return true-}--export {- isValidVideoPasswordHeader,- checkVideoIsPasswordProtected as isVideoPasswordProtected,- doesVideoPasswordExist,- isVideoPasswordDeletable+ return checkCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res, checkIsLocal: true, checkIsOwner: false })}diff --git a/server/core/middlewares/validators/shared/video-playlists.ts b/server/core/middlewares/validators/shared/video-playlists.tsindex caa0bfaf45..64dbe73f6a 100644--- a/server/core/middlewares/validators/shared/video-playlists.ts+++ b/server/core/middlewares/validators/shared/video-playlists.ts@@ -4,33 +4,36 @@ import { MVideoPlaylist } from '@server/types/models/index.js'import { HttpStatusCode } from '@peertube/peertube-models'export type VideoPlaylistFetchType = 'summary' | 'all'-async function doesVideoPlaylistExist (id: number | string, res: express.Response, fetchType: VideoPlaylistFetchType = 'summary') {++export async function doesVideoPlaylistExist (options: {+ id: number | string+ req: express.Request+ res: express.Response+ fetchType?: VideoPlaylistFetchType+}) {+ const { id, req, res, fetchType = 'summary' } = options+if (fetchType === 'summary') {const videoPlaylist = await VideoPlaylistModel.loadWithAccountAndChannelSummary(id, undefined)res.locals.videoPlaylistSummary = videoPlaylist- return handleVideoPlaylist(videoPlaylist, res)+ return handleVideoPlaylist(videoPlaylist, req, res)}const videoPlaylist = await VideoPlaylistModel.loadWithAccountAndChannel(id, undefined)res.locals.videoPlaylistFull = videoPlaylist- return handleVideoPlaylist(videoPlaylist, res)+ return handleVideoPlaylist(videoPlaylist, req, res)}-// -----------------------------------------------------------------------------export {- doesVideoPlaylistExist-}-+// Private// ----------------------------------------------------------------------------function handleVideoPlaylist (videoPlaylist: MVideoPlaylist, res: express.Response) {- if (!videoPlaylist) {+function handleVideoPlaylist (playlist: MVideoPlaylist, req: express.Request, res: express.Response) {+ if (!playlist) {res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Video playlist not found'+ message: req.t('Video playlist not found')})return false}diff --git a/server/core/middlewares/validators/shared/videos.ts b/server/core/middlewares/validators/shared/videos.tsindex 4f6af5e4fb..070001dcdd 100644--- a/server/core/middlewares/validators/shared/videos.ts+++ b/server/core/middlewares/validators/shared/videos.ts@@ -3,14 +3,13 @@ import { exists } from '@server/helpers/custom-validators/misc.js'import { VideoLoadType, loadVideo } from '@server/lib/model-loaders/index.js'import { isUserQuotaValid } from '@server/lib/user.js'import { VideoTokensManager } from '@server/lib/video-tokens-manager.js'-import { authenticatePromise } from '@server/middlewares/auth.js'-import { VideoChannelModel } from '@server/models/video/video-channel.js'+import { authenticateOrFail } from '@server/middlewares/auth.js'import { VideoFileModel } from '@server/models/video/video-file.js'import { VideoPasswordModel } from '@server/models/video/video-password.js'import { VideoModel } from '@server/models/video/video.js'import {- MUser,MUserAccountId,+ MUserAccountUrl,MUserId,MVideo,MVideoAccountLight,@@ -23,6 +22,7 @@ import {MVideoWithRights} from '@server/types/models/index.js'import { Request, Response } from 'express'+import { checkCanManageChannel } from './video-channels.js'export async function doesVideoExist (id: number | string, res: Response, fetchType: VideoLoadType = 'all') {const userId = res.locals.oauth ? res.locals.oauth.token.User.id : undefined@@ -67,10 +67,7 @@ export async function doesVideoExist (id: number | string, res: Response, fetchTexport async function doesVideoFileOfVideoExist (id: number, videoIdOrUUID: number | string, res: Response) {if (!await VideoFileModel.doesVideoExistForVideoFile(id, videoIdOrUUID)) {- res.fail({- status: HttpStatusCode.NOT_FOUND_404,- message: 'VideoFile matching Video not found'- })+ res.sendStatus(HttpStatusCode.NOT_FOUND_404)return false}@@ -79,45 +76,23 @@ export async function doesVideoFileOfVideoExist (id: number, videoIdOrUUID: numb// ----------------------------------------------------------------------------export async function doesVideoChannelOfAccountExist (channelId: number, user: MUserAccountId, res: Response) {- const videoChannel = await VideoChannelModel.loadAndPopulateAccount(channelId)-- if (videoChannel === null) {- res.fail({ message: `Unknown ${channelId} on this instance.` })- return false- }-- // Don't check account id if the user can update any video- if (user.hasRight(UserRight.UPDATE_ANY_VIDEO) === true) {- res.locals.videoChannel = videoChannel- return true- }-- if (videoChannel.Account.id !== user.Account.id) {- res.fail({ message: `Unknown channel ${channelId} for this account.` })- return false- }-- res.locals.videoChannel = videoChannel- return true-}--// ----------------------------------------------------------------------------export async function checkCanSeeVideo (options: {req: Requestres: ResponseparamId: stringvideo: MVideo+ videoFileToken?: {+ user: MUserAccountUrl+ }}) {- const { req, res, video, paramId } = options+ const { req, res, video, videoFileToken, paramId } = optionsif (video.requiresUserAuth({ urlParamId: paramId, checkBlacklist: true })) {- return checkCanSeeUserAuthVideo({ req, res, video })+ return checkCanSeeUserAuthVideo({ req, res, video, videoFileTokenUser: videoFileToken?.user })}if (video.privacy === VideoPrivacy.PASSWORD_PROTECTED) {- return checkCanSeePasswordProtectedVideo({ req, res, video })+ return checkCanSeePasswordProtectedVideo({ req, res, video, hasVideoFileToken: !!videoFileToken })}if (video.privacy === VideoPrivacy.UNLISTED || video.privacy === VideoPrivacy.PUBLIC) {@@ -131,22 +106,25 @@ async function checkCanSeeUserAuthVideo (options: {req: Requestres: Responsevideo: MVideoId | MVideoWithRights+ videoFileTokenUser?: MUserAccountUrl}) {const { req, res, video } = optionsconst fail = () => {res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot fetch information of private/internal/blocked video'+ message: req.t('Cannot fetch information of private/internal/blocked video')})return false}- await authenticatePromise({ req, res })+ let user = options.videoFileTokenUser+ if (!user) {+ if (!await authenticateOrFail({ req, res })) return false- const user = res.locals.oauth?.token.User- if (!user) return fail()+ user = res.locals.oauth.token.User+ }const videoWithRights = await getVideoWithRights(video as MVideoWithRights)@@ -158,13 +136,13 @@ async function checkCanSeeUserAuthVideo (options: {}if (videoWithRights.isBlacklisted()) {- if (canUserAccessVideo(user, videoWithRights, UserRight.MANAGE_VIDEO_BLACKLIST)) return true+ if (await canUserManageProtectedVideo({ user, req, video: videoWithRights, right: UserRight.MANAGE_VIDEO_BLACKLIST })) return truereturn fail()}if (privacy === VideoPrivacy.PRIVATE || privacy === VideoPrivacy.UNLISTED) {- if (canUserAccessVideo(user, videoWithRights, UserRight.SEE_ALL_VIDEOS)) return true+ if (await canUserManageProtectedVideo({ user, req, video: videoWithRights, right: UserRight.SEE_ALL_VIDEOS })) return truereturn fail()}@@ -177,26 +155,31 @@ async function checkCanSeePasswordProtectedVideo (options: {req: Requestres: Responsevideo: MVideo+ hasVideoFileToken: boolean}) {- const { req, res, video } = options+ const { req, res, video, hasVideoFileToken } = optionsconst videoWithRights = await getVideoWithRights(video as MVideoWithRights)const videoPassword = req.header('x-peertube-video-password')if (!exists(videoPassword)) {- const errorMessage = 'Please provide a password to access this password protected video'+ if (hasVideoFileToken === true) return true++ const errorMessage = req.t('Please provide a password to access this password protected video')const errorType = ServerErrorCode.VIDEO_REQUIRES_PASSWORD- if (req.header('authorization')) {- await authenticatePromise({ req, res, errorMessage, errorStatus: HttpStatusCode.FORBIDDEN_403, errorType })- const user = res.locals.oauth?.token.User+ if (!await authenticateOrFail({ req, res, errorMessage, errorStatus: HttpStatusCode.UNAUTHORIZED_401, errorType })) return false- if (canUserAccessVideo(user, videoWithRights, UserRight.SEE_ALL_VIDEOS)) return true- }+ const user = res.locals.oauth.token.User++ if (await canUserManageProtectedVideo({ user, req, video: videoWithRights, right: UserRight.SEE_ALL_VIDEOS })) return trueres.fail({- status: HttpStatusCode.FORBIDDEN_403,+ status: user+ ? HttpStatusCode.FORBIDDEN_403+ : HttpStatusCode.UNAUTHORIZED_401,+type: errorType,message: errorMessage})@@ -208,22 +191,37 @@ async function checkCanSeePasswordProtectedVideo (options: {res.fail({status: HttpStatusCode.FORBIDDEN_403,type: ServerErrorCode.INCORRECT_VIDEO_PASSWORD,- message: 'Incorrect video password. Access to the video is denied.'+ message: req.t('Incorrect video password. Access to the video is denied')})return false}-function canUserAccessVideo (user: MUser, video: MVideoWithRights | MVideoAccountLight, right: UserRightType) {- const isOwnedByUser = video.VideoChannel.Account.userId === user.id-- return isOwnedByUser || user.hasRight(right)+async function canUserManageProtectedVideo (options: {+ req: Request+ user: MUserAccountId+ video: MVideoWithRights | MVideoAccountLight+ right: UserRightType+}) {+ const { user, video, right, req } = options++ return checkCanManageChannel({+ channel: video.VideoChannel,+ user,+ req,+ res: null,+ checkCanManage: true,+ checkIsOwner: false,+ specialRight: right+ })}async function getVideoWithRights (video: MVideoWithRights): Promise<MVideoWithRights> {- return video.VideoChannel?.Account?.userId- ? video- : VideoModel.loadFull(video.id)+ const channel = video.VideoChannel++ if (channel?.id && channel?.Account?.userId && channel?.Account?.id) return video++ return VideoModel.loadFull(video.id)}// ---------------------------------------------------------------------------@@ -233,85 +231,105 @@ export async function checkCanAccessVideoStaticFiles (options: {req: Requestres: ResponseparamId: string-}) {+}): Promise<boolean> {const { video, req, res } = options- if (res.locals.oauth?.token.User || exists(req.header('x-peertube-video-password'))) {- return checkCanSeeVideo(options)- }-- assignVideoTokenIfNeeded(req, res, video)+ if (!checkVideoTokenIfNeeded(req, res, video)) return false- if (res.locals.videoFileToken) return true- if (!video.hasPrivateStaticPath()) return true-- res.sendStatus(HttpStatusCode.FORBIDDEN_403)- return false+ return checkCanSeeVideo({ ...options, videoFileToken: res.locals.videoFileToken })}export async function checkCanAccessVideoSourceFile (options: {videoId: numberreq: Requestres: Response-}) {+}): Promise<boolean> {const { req, res, videoId } = optionsconst video = await VideoModel.loadFull(videoId)- if (res.locals.oauth?.token.User) {- if (canUserAccessVideo(res.locals.oauth.token.User, video, UserRight.SEE_ALL_VIDEOS) === true) return true+ let user = res.locals.oauth?.token.User+ if (!user) {+ if (!checkVideoTokenIfNeeded(req, res, video)) return false++ user = res.locals.videoFileToken?.user+ }- res.sendStatus(HttpStatusCode.FORBIDDEN_403)+ if (!user) {+ res.fail({ status: HttpStatusCode.UNAUTHORIZED_401, message: req.t('Authentication is required to access the video source file') })return false}- assignVideoTokenIfNeeded(req, res, video)- if (res.locals.videoFileToken) return true+ if (await canUserManageProtectedVideo({ user, req, video, right: UserRight.SEE_ALL_VIDEOS }) === true) {+ return true+ }res.sendStatus(HttpStatusCode.FORBIDDEN_403)return false}-function assignVideoTokenIfNeeded (req: Request, res: Response, video: MVideoUUID) {+function checkVideoTokenIfNeeded (req: Request, res: Response, video: MVideoUUID) {const videoFileToken = req.query.videoFileToken- if (videoFileToken && VideoTokensManager.Instance.hasToken({ token: videoFileToken, videoUUID: video.uuid })) {- const user = VideoTokensManager.Instance.getUserFromToken({ token: videoFileToken })+ if (videoFileToken) {+ if (VideoTokensManager.Instance.hasToken({ token: videoFileToken, videoUUID: video.uuid })) {+ const user = VideoTokensManager.Instance.getUserFromToken({ token: videoFileToken })- res.locals.videoFileToken = { user }+ res.locals.videoFileToken = { user }+ } else {+ res.fail({+ message: req.t('Invalid video file token'),+ status: HttpStatusCode.FORBIDDEN_403+ })++ return false+ }}++ return true}// ----------------------------------------------------------------------------export function checkUserCanManageVideo (options: {- user: MUser+export async function checkCanManageVideo (options: {+ user: MUserAccountIdvideo: MVideoAccountLightright: UserRightTypereq: Request- res: Response- onlyOwned?: boolean+ res: Response | null+ checkIsLocal: boolean+ checkIsOwner: boolean}) {- const { user, video, right, req, res, onlyOwned = true } = options+ const { user, video, right, req, res, checkIsLocal, checkIsOwner } = optionsif (!user) {- res.fail({+ res?.fail({status: HttpStatusCode.UNAUTHORIZED_401,message: req.t('Authentication is required.')})+ return false}- if (onlyOwned && video.isOwned() === false) {- res.fail({+ if (checkIsLocal && video.isLocal() === false) {+ res?.fail({status: HttpStatusCode.FORBIDDEN_403,message: req.t('Cannot manage a video of another server.')})return false}- const account = video.VideoChannel.Account- if (user.hasRight(right) === false && account.userId !== user.id) {- res.fail({+ if (+ !await checkCanManageChannel({+ channel: video.VideoChannel,+ user,+ req,+ res: null,+ checkCanManage: true,+ checkIsOwner,+ specialRight: right+ })+ ) {+ res?.fail({status: HttpStatusCode.FORBIDDEN_403,message: req.t('Cannot manage a video of another user.')})@@ -321,13 +339,22 @@ export function checkUserCanManageVideo (options: {return true}+type NewType = MUserId+// ----------------------------------------------------------------------------export async function checkUserQuota (user: MUserId, videoFileSize: number, res: Response) {+export async function checkUserQuota (options: {+ user: NewType+ videoFileSize: number+ req: Request+ res: Response+}) {+ const { user, videoFileSize, req, res } = options+if (await isUserQuotaValid({ userId: user.id, uploadSize: videoFileSize }) === false) {res.fail({status: HttpStatusCode.PAYLOAD_TOO_LARGE_413,- message: 'The user video quota is exceeded with this video.',+ message: req.t('The user video quota is exceeded with this video'),type: ServerErrorCode.QUOTA_REACHED})return falsediff --git a/server/core/middlewares/validators/static.ts b/server/core/middlewares/validators/static.tsindex f186d36dcf..39a4f7e4d6 100644--- a/server/core/middlewares/validators/static.ts+++ b/server/core/middlewares/validators/static.ts@@ -196,7 +196,7 @@ function extractTokenOrDie (req: express.Request, res: express.Response) {if (!token) {return res.fail({message: 'Video password header, video file token query parameter and bearer token are all missing', //- status: HttpStatusCode.FORBIDDEN_403+ status: HttpStatusCode.UNAUTHORIZED_401})}diff --git a/server/core/middlewares/validators/token.ts b/server/core/middlewares/validators/token.tsindex 02b0fe732b..c03bbfe206 100644--- a/server/core/middlewares/validators/token.ts+++ b/server/core/middlewares/validators/token.ts@@ -3,7 +3,7 @@ import { isIdValid } from '@server/helpers/custom-validators/misc.js'import { OAuthTokenModel } from '@server/models/oauth/oauth-token.js'import express from 'express'import { param } from 'express-validator'-import { checkUserCanManageAccount, checkUserIdExist } from './shared/users.js'+import { checkCanManageAccount, checkUserIdExist } from './shared/users.js'import { areValidationErrors } from './shared/utils.js'export const manageTokenSessionsValidator = [@@ -17,7 +17,7 @@ export const manageTokenSessionsValidator = [const authUser = res.locals.oauth.token.Userconst targetUser = res.locals.user- if (!checkUserCanManageAccount({ account: targetUser.Account, user: authUser, req, res, specialRight: UserRight.MANAGE_USERS })) return+ if (!checkCanManageAccount({ account: targetUser.Account, user: authUser, req, res, specialRight: UserRight.MANAGE_USERS })) returnreturn next()}diff --git a/server/core/middlewares/validators/users/users.ts b/server/core/middlewares/validators/users/users.tsindex d0145d58ad..2a5575673a 100644--- a/server/core/middlewares/validators/users/users.ts+++ b/server/core/middlewares/validators/users/users.ts@@ -130,7 +130,7 @@ export const usersRemoveValidator = [return res.fail({ message: 'Cannot remove the root user' })}- if (!checkUserCanModerate(user, res)) return+ if (!checkCanModerate(user, res)) returnreturn next()}@@ -152,7 +152,7 @@ export const usersBlockToggleValidator = [return res.fail({ message: 'Cannot block the root user' })}- if (!checkUserCanModerate(user, res)) return+ if (!checkCanModerate(user, res)) returnreturn next()}@@ -207,7 +207,7 @@ export const usersUpdateValidator = [return res.fail({ message: 'Cannot change root role.' })}- if (!checkUserCanModerate(user, res)) return+ if (!checkCanModerate(user, res)) returnif (req.body.email && req.body.email !== user.email && !await checkEmailDoesNotAlreadyExist(req.body.email, res)) return@@ -355,7 +355,7 @@ export const usersVideoRatingValidator = [}]-export const usersVideosValidator = [+export const listMyVideosValidator = [query('channelId').optional().customSanitizer(toIntOrNull)@@ -366,10 +366,17 @@ export const usersVideosValidator = [.customSanitizer(arrayify).custom(isStringArray).withMessage('Should have a valid channelNameOneOf array'),+ query('includeCollaborations')+ .optional()+ .customSanitizer(toBooleanOrNull),+async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (req.query.channelId && !await doesChannelIdExist({ id: req.query.channelId, checkManage: true, checkIsLocal: true, req, res })) {+ if (+ req.query.channelId &&+ !await doesChannelIdExist({ id: req.query.channelId, checkCanManage: true, checkIsLocal: true, checkIsOwner: false, req, res })+ ) {return}@@ -478,7 +485,7 @@ export const userAutocompleteValidator = [// Private// ----------------------------------------------------------------------------function checkUserCanModerate (onUser: MUser, res: express.Response) {+function checkCanModerate (onUser: MUser, res: express.Response) {const authUser = res.locals.oauth.token.Userif (authUser.role === UserRole.ADMINISTRATOR) return truediff --git a/server/core/middlewares/validators/videos/shared/video-validators.ts b/server/core/middlewares/validators/videos/shared/video-validators.tsindex 7bff15251f..cd9f06cbc1 100644--- a/server/core/middlewares/validators/videos/shared/video-validators.ts+++ b/server/core/middlewares/validators/videos/shared/video-validators.ts@@ -10,17 +10,21 @@ import express from 'express'import { checkUserQuota } from '../../shared/index.js'export async function commonVideoFileChecks (options: {+ req: express.Requestres: express.Responseuser: MUserAccountIdvideoFileSize: numberfiles: express.UploadFilesForCheck}): Promise<boolean> {- const { res, user, videoFileSize, files } = options+ const { req, res, user, videoFileSize, files } = optionsif (!isVideoFileMimeTypeValid(files)) {res.fail({status: HttpStatusCode.UNSUPPORTED_MEDIA_TYPE_415,- message: `This file is not supported. Please, make sure it is of the following type: ${CONSTRAINTS_FIELDS.VIDEOS.EXTNAME.join(', ')}`+ message: req.t(+ 'This file is not supported. Please, make sure it is of the following type: {types}',+ { types: CONSTRAINTS_FIELDS.VIDEOS.EXTNAME.join(', ') }+ )})return false}@@ -28,13 +32,13 @@ export async function commonVideoFileChecks (options: {if (!isVideoFileSizeValid(videoFileSize.toString())) {res.fail({status: HttpStatusCode.PAYLOAD_TOO_LARGE_413,- message: 'This file is too large. It exceeds the maximum file size authorized.',+ message: req.t('This file is too large. It exceeds the maximum file size authorized'),type: ServerErrorCode.MAX_FILE_SIZE_REACHED})return false}- if (await checkUserQuota(user, videoFileSize, res) === false) return false+ if (await checkUserQuota({ user, videoFileSize, req, res }) === false) return falsereturn true}@@ -59,7 +63,7 @@ export async function isVideoFileAccepted (options: {logger.info('Refused local video file.', { acceptedResult, acceptParameters })res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: acceptedResult.errorMessage || 'Refused local video file'+ message: acceptedResult.errorMessage || req.t('Refused local video file')})return false}@@ -67,11 +71,11 @@ export async function isVideoFileAccepted (options: {return true}-export function checkVideoFileCanBeEdited (video: MVideo, res: express.Response) {+export function checkVideoFileCanBeEdited (video: MVideo, req: express.Request, res: express.Response) {if (video.isLive) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Cannot edit a live video'+ message: req.t('Cannot edit a live video')})return false@@ -80,7 +84,7 @@ export function checkVideoFileCanBeEdited (video: MVideo, res: express.Response)if (video.state === VideoState.TO_TRANSCODE || video.state === VideoState.TO_EDIT) {res.fail({status: HttpStatusCode.CONFLICT_409,- message: 'Cannot edit video that is already waiting for transcoding/edition'+ message: req.t('Cannot edit video that is already waiting for transcoding/edition')})return false@@ -89,7 +93,7 @@ export function checkVideoFileCanBeEdited (video: MVideo, res: express.Response)if (!canVideoFileBeEdited(video.state)) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Video state is not compatible with edition'+ message: req.t('Video state is not compatible with edition')})return false@@ -98,11 +102,11 @@ export function checkVideoFileCanBeEdited (video: MVideo, res: express.Response)return true}-export function checkVideoCanBeTranscribedOrTranscripted (video: MVideo, res: express.Response) {+export function checkVideoCanBeTranscribed (video: MVideo, req: express.Request, res: express.Response) {if (video.remote) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Cannot run this task on a remote video'+ message: req.t('Cannot run this task on a remote video')})return false}@@ -110,7 +114,7 @@ export function checkVideoCanBeTranscribedOrTranscripted (video: MVideo, res: exif (video.isLive) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Cannot run this task on a live'+ message: req.t('Cannot run this task on a live video')})return false}@@ -124,7 +128,7 @@ export function checkVideoCanBeTranscribedOrTranscripted (video: MVideo, res: exif (incompatibleStates.has(video.state)) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: `Cannot run this task on a video with "${VIDEO_STATES[video.state]}" state`+ message: req.t('Cannot run this task on a video with "{state}" state', { state: VIDEO_STATES[video.state] })})return false}diff --git a/server/core/middlewares/validators/videos/video-captions.ts b/server/core/middlewares/validators/videos/video-captions.tsindex 10f27397a4..11206aa45d 100644--- a/server/core/middlewares/validators/videos/video-captions.ts+++ b/server/core/middlewares/validators/videos/video-captions.ts@@ -11,13 +11,13 @@ import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../../initializers/constants.jimport {areValidationErrors,checkCanSeeVideo,- checkUserCanManageVideo,+ checkCanManageVideo,doesVideoCaptionExist,doesVideoExist,isValidVideoIdParam,isValidVideoPasswordHeader} from '../shared/index.js'-import { checkVideoCanBeTranscribedOrTranscripted } from './shared/video-validators.js'+import { checkVideoCanBeTranscribed } from './shared/video-validators.js'export const addVideoCaptionValidator = [isValidVideoIdParam('videoId'),@@ -40,7 +40,17 @@ export const addVideoCaptionValidator = [// Check if the user who did the request is able to update the videoconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.UPDATE_ANY_VIDEO, req, res })) {+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) {return cleanUpReqFiles(req)}@@ -70,11 +80,13 @@ export const generateVideoCaptionValidator = [const video = res.locals.videoAll- if (!checkVideoCanBeTranscribedOrTranscripted(video, res)) return+ if (!checkVideoCanBeTranscribed(video, req, res)) return// Check if the user who did the request is able to update the videoconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return+ if (!await checkCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res, checkIsLocal: true, checkIsOwner: false })) {+ return+ }// Check the video has not already a captionconst captions = await VideoCaptionModel.listVideoCaptions(video.id)@@ -125,7 +137,17 @@ export const deleteVideoCaptionValidator = [// Check if the user who did the request is able to update the videoconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) returnreturn next()}diff --git a/server/core/middlewares/validators/videos/video-channel-collaborators.ts b/server/core/middlewares/validators/videos/video-channel-collaborators.tsnew file mode 100644index 0000000000..896624c066--- /dev/null+++ b/server/core/middlewares/validators/videos/video-channel-collaborators.ts@@ -0,0 +1,171 @@+import { HttpStatusCode, UserRight, VideoChannelCollaboratorState } from '@peertube/peertube-models'+import { isIdValid } from '@server/helpers/custom-validators/misc.js'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'+import express from 'express'+import { body, param } from 'express-validator'+import { areValidationErrors, checkCanManageAccount, doesAccountHandleExist, doesChannelHandleExist } from '../shared/index.js'+import { CONFIG } from '@server/initializers/config.js'++export const channelListCollaboratorsValidator = [+ 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: false, req, res })+ ) return++ return next()+ }+]++export const channelInviteCollaboratorsValidator = [+ param('handle').exists(),++ body('accountHandle').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 doesAccountHandleExist({ handle: req.body.accountHandle, req, res, checkIsLocal: true, checkCanManage: false })) return++ const user = res.locals.oauth.token.User+ if (user.Account.id === res.locals.account.id) {+ res.fail({+ message: req.t('Cannot invite the account owner of the channel to collaborate'),+ status: HttpStatusCode.BAD_REQUEST_400+ })+ return+ }++ const collaborator = await VideoChannelCollaboratorModel.loadByCollaboratorAccountName({+ accountName: req.body.accountHandle,+ channelId: res.locals.videoChannel.id+ })+ res.locals.channelCollaborator = collaborator++ if (collaborator && collaborator.state !== VideoChannelCollaboratorState.REJECTED) {+ res.fail({+ message: req.t('This account is already a collaborator or has a pending invitation for this channel'),+ status: HttpStatusCode.CONFLICT_409+ })+ return+ }++ const count = await VideoChannelCollaboratorModel.countByChannel(res.locals.videoChannel.id)+ if (count >= CONFIG.VIDEO_CHANNELS.MAX_COLLABORATORS_PER_CHANNEL) {+ res.fail({+ message: req.t(+ 'The maximum number of collaborators for this channel ({limit}) has been reached',+ { limit: CONFIG.VIDEO_CHANNELS.MAX_COLLABORATORS_PER_CHANNEL }+ ),+ status: HttpStatusCode.BAD_REQUEST_400+ })+ return+ }++ return next()+ }+]++export const channelAcceptOrRejectInviteCollaboratorsValidator = [+ param('handle').exists(),+ param('collaboratorId').custom(isIdValid),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return++ if (+ !await doesChannelHandleExist({ handle: req.params.handle, checkCanManage: false, checkIsLocal: true, checkIsOwner: false, req, res })+ ) {+ return+ }++ if (!await doesChannelCollaboratorExist({ collaboratorId: +req.params.collaboratorId, channelHandle: req.params.handle, req, res })) {+ return+ }++ const channelCollaborator = res.locals.channelCollaborator++ if (channelCollaborator.state !== VideoChannelCollaboratorState.PENDING) {+ res.fail({ message: req.t('Collaborator is not in pending state') })+ return+ }++ const user = res.locals.oauth.token.User+ if (channelCollaborator.accountId !== user.Account.id) {+ res.fail({ message: req.t('Collaborator is not the current user') })+ return+ }++ return next()+ }+]++export const channelDeleteCollaboratorsValidator = [+ param('handle').exists(),+ param('collaboratorId').custom(isIdValid),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return++ if (!await doesChannelCollaboratorExist({ collaboratorId: +req.params.collaboratorId, channelHandle: req.params.handle, req, res })) {+ return+ }++ const user = res.locals.oauth.token.User++ const canManageCollaboratorAccount = checkCanManageAccount({+ user,+ account: res.locals.channelCollaborator.Account,+ req,+ res,+ specialRight: UserRight.MANAGE_ANY_VIDEO_CHANNEL+ })++ // Check this is the owner of the channel if the user is not the collaborator account+ // Only the owner and the collaborator can delete the collaboration+ const checkIsOwner = !canManageCollaboratorAccount++ if (+ !await doesChannelHandleExist({ handle: req.params.handle, checkCanManage: true, checkIsLocal: true, checkIsOwner, req, res })+ ) {+ return+ }++ return next()+ }+]++// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------++async function doesChannelCollaboratorExist (options: {+ collaboratorId: number+ channelHandle: string+ req: express.Request+ res: express.Response+}) {+ const { collaboratorId, channelHandle, req, res } = options++ const channelCollaborator = await VideoChannelCollaboratorModel.loadByChannelHandle(collaboratorId, channelHandle)+ if (!channelCollaborator) {+ res.fail({+ message: req.t('Channel collaborator does not exist'),+ status: HttpStatusCode.NOT_FOUND_404+ })+ return false+ }++ res.locals.channelCollaborator = channelCollaborator++ return true+}diff --git a/server/core/middlewares/validators/videos/video-channel-sync.ts b/server/core/middlewares/validators/videos/video-channel-sync.tsindex 8aa4619854..0430728562 100644--- a/server/core/middlewares/validators/videos/video-channel-sync.ts+++ b/server/core/middlewares/validators/videos/video-channel-sync.ts@@ -1,9 +1,10 @@-import * as express from 'express'-import { body, param } from 'express-validator'+import { HttpStatusCode, VideoChannelSyncCreate } from '@peertube/peertube-models'import { isUrlValid } from '@server/helpers/custom-validators/activitypub/misc.js'+import { toBooleanOrNull } from '@server/helpers/custom-validators/misc.js'import { CONFIG } from '@server/initializers/config.js'import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync.js'-import { HttpStatusCode, VideoChannelSyncCreate } from '@peertube/peertube-models'+import * as express from 'express'+import { body, param, query } from 'express-validator'import { areValidationErrors, doesChannelIdExist } from '../shared/index.js'import { doesVideoChannelSyncIdExist } from '../shared/video-channel-syncs.js'@@ -29,7 +30,9 @@ export const videoChannelSyncValidator = [if (areValidationErrors(req, res)) returnconst body: VideoChannelSyncCreate = req.body- if (!await doesChannelIdExist({ id: body.videoChannelId, checkManage: true, checkIsLocal: true, req, res })) return+ if (!await doesChannelIdExist({ id: body.videoChannelId, checkCanManage: true, checkIsOwner: false, checkIsLocal: true, req, res })) {+ return+ }const count = await VideoChannelSyncModel.countByAccount(res.locals.videoChannel.accountId)if (count >= CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.MAX_PER_USER) {@@ -49,10 +52,31 @@ export const ensureSyncExists = [if (areValidationErrors(req, res)) returnif (!await doesVideoChannelSyncIdExist(+req.params.id, res)) return- if (!await doesChannelIdExist({ id: res.locals.videoChannelSync.videoChannelId, checkManage: true, checkIsLocal: true, req, res })) {+ if (+ !await doesChannelIdExist({+ id: res.locals.videoChannelSync.videoChannelId,+ checkCanManage: true,+ checkIsOwner: false,+ checkIsLocal: true,+ req,+ res+ })+ ) {return}return next()}]++export const listAccountChannelsSyncValidator = [+ query('includeCollaborations')+ .optional()+ .customSanitizer(toBooleanOrNull),++ (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return++ return next()+ }+]diff --git a/server/core/middlewares/validators/videos/video-channels.ts b/server/core/middlewares/validators/videos/video-channels.tsindex 43bbb7d96a..fe08ab8868 100644--- a/server/core/middlewares/validators/videos/video-channels.ts+++ b/server/core/middlewares/validators/videos/video-channels.ts@@ -81,9 +81,10 @@ export const videoChannelsRemoveValidator = [export const videoChannelsHandleValidatorFactory = (options: {checkIsLocal: boolean- checkManage: boolean+ checkCanManage: boolean+ checkIsOwner: boolean}) => {- const { checkIsLocal, checkManage } = options+ const { checkIsLocal, checkCanManage, checkIsOwner } = optionsreturn [param('handle')@@ -92,7 +93,7 @@ export const videoChannelsHandleValidatorFactory = (options: {async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesChannelHandleExist({ handle: req.params.handle, checkManage, checkIsLocal, req, res })) return+ if (!await doesChannelHandleExist({ handle: req.params.handle, checkCanManage, checkIsLocal, checkIsOwner, req, res })) returnreturn next()}@@ -104,20 +105,24 @@ export const ensureChannelOwnerCanUpload = [const channel = res.locals.videoChannelconst user = { id: channel.Account.userId }- if (!await checkUserQuota(user, 1, res)) return+ if (!await checkUserQuota({ user, videoFileSize: 1, req, res })) returnnext()}]-export const videoChannelStatsValidator = [+export const listAccountChannelsValidator = [query('withStats').optional()- .customSanitizer(toBooleanOrNull)- .custom(isBooleanValid).withMessage('Should have a valid stats flag boolean'),+ .customSanitizer(toBooleanOrNull),++ query('includeCollaborations')+ .optional()+ .customSanitizer(toBooleanOrNull),(req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return+return next()}]diff --git a/server/core/middlewares/validators/videos/video-chapters.ts b/server/core/middlewares/validators/videos/video-chapters.tsindex d6e8acf628..e7a0912afa 100644--- a/server/core/middlewares/validators/videos/video-chapters.ts+++ b/server/core/middlewares/validators/videos/video-chapters.ts@@ -1,7 +1,7 @@import express from 'express'import { body } from 'express-validator'import { HttpStatusCode, UserRight } from '@peertube/peertube-models'-import { areValidationErrors, checkUserCanManageVideo, doesVideoExist, isValidVideoIdParam } from '../shared/index.js'+import { areValidationErrors, checkCanManageVideo, doesVideoExist, isValidVideoIdParam } from '../shared/index.js'import { areVideoChaptersValid } from '@server/helpers/custom-validators/video-chapters.js'export const updateVideoChaptersValidator = [@@ -24,7 +24,17 @@ export const updateVideoChaptersValidator = [// Check if the user who did the request is able to update video chapters (same right as updating the video)const user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) returnreturn next()}diff --git a/server/core/middlewares/validators/videos/video-comments.ts b/server/core/middlewares/validators/videos/video-comments.tsindex a74b81aa6c..c445419da4 100644--- a/server/core/middlewares/validators/videos/video-comments.ts+++ b/server/core/middlewares/validators/videos/video-comments.ts@@ -2,6 +2,7 @@ import { arrayify } from '@peertube/peertube-core-utils'import { HttpStatusCode, UserRight, VideoCommentPolicy } from '@peertube/peertube-models'import { isStringArray } from '@server/helpers/custom-validators/search.js'import { canVideoBeFederated } from '@server/lib/activitypub/videos/federate.js'+import { VideoChannelModel } from '@server/models/video/video-channel.js'import { MUserAccountUrl } from '@server/types/models/index.js'import express from 'express'import { body, param, query } from 'express-validator'@@ -21,9 +22,9 @@ import { Hooks } from '../../../lib/plugins/hooks.js'import { MCommentOwnerVideoReply, MVideo, MVideoFullLight } from '../../../types/models/video/index.js'import {areValidationErrors,+ checkCanManageChannel,+ checkCanManageVideo,checkCanSeeVideo,- checkUserCanManageAccount,- checkUserCanManageVideo,doesChannelIdExist,doesVideoCommentExist,doesVideoCommentThreadExist,@@ -53,7 +54,7 @@ export const listAllVideoCommentsForAdminValidator = [if (req.query.videoId && !await doesVideoExist(req.query.videoId, res, 'unsafe-only-immutable-attributes')) returnif (req.query.videoChannelId &&- !await doesChannelIdExist({ id: req.query.videoChannelId, checkManage: true, checkIsLocal: true, req, res })+ !await doesChannelIdExist({ id: req.query.videoChannelId, checkCanManage: true, checkIsOwner: false, checkIsLocal: true, req, res })) returnreturn next()@@ -65,28 +66,37 @@ export const listCommentsOnUserVideosValidator = [query('isHeldForReview').optional()- .customSanitizer(toBooleanOrNull)- .custom(isBooleanValid)- .withMessage('Should have a valid isHeldForReview boolean'),+ .customSanitizer(toBooleanOrNull),++ query('includeCollaborations')+ .optional()+ .customSanitizer(toBooleanOrNull),async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) returnif (req.query.videoId && !await doesVideoExist(req.query.videoId, res, 'all')) return+if (req.query.videoChannelId &&- !await doesChannelIdExist({ id: req.query.videoChannelId, checkManage: true, checkIsLocal: true, req, res })+ !await doesChannelIdExist({+ id: req.query.videoChannelId,+ checkCanManage: true,+ checkIsLocal: true,+ checkIsOwner: false,+ req,+ res,+ specialRight: UserRight.SEE_ALL_COMMENTS+ })) returnconst user = res.locals.oauth.token.Userconst video = res.locals.videoAll- if (video && !checkUserCanManageVideo({ user, video, right: UserRight.SEE_ALL_COMMENTS, req, res })) return-- const channel = res.locals.videoChannel- if (channel && !checkUserCanManageAccount({ account: channel.Account, user, req, res, specialRight: UserRight.SEE_ALL_COMMENTS })) {- return- }+ if (+ video &&+ !await checkCanManageVideo({ user, video, right: UserRight.SEE_ALL_COMMENTS, req, res, checkIsLocal: true, checkIsOwner: false })+ ) returnreturn next()}@@ -197,7 +207,9 @@ export const removeVideoCommentValidator = [if (!await doesVideoExist(req.params.videoId, res)) returnif (!await doesVideoCommentExist(req.params.commentId, res.locals.videoAll, res)) return- if (!checkUserCanDeleteVideoComment(res.locals.oauth.token.User, res.locals.videoCommentFull, res)) return+ if (!await checkCanDeleteVideoComment({ user: res.locals.oauth.token.User, videoComment: res.locals.videoCommentFull, req, res })) {+ return+ }return next()}@@ -214,7 +226,9 @@ export const approveVideoCommentValidator = [if (!await doesVideoExist(req.params.videoId, res)) returnif (!await doesVideoCommentExist(req.params.commentId, res.locals.videoAll, res)) return- if (!checkUserCanApproveVideoComment(res.locals.oauth.token.User, res.locals.videoCommentFull, res)) return+ if (!await checkCanApproveVideoComment({ user: res.locals.oauth.token.User, videoComment: res.locals.videoCommentFull, req, res })) {+ return+ }return next()}@@ -236,63 +250,76 @@ function isVideoCommentsEnabled (video: MVideo, res: express.Response) {return true}-function checkUserCanDeleteVideoComment (user: MUserAccountUrl, videoComment: MCommentOwnerVideoReply, res: express.Response) {+function checkCanDeleteVideoComment (options: {+ user: MUserAccountUrl+ videoComment: MCommentOwnerVideoReply+ req: express.Request+ res: express.Response+}): Promise<boolean> {+ const { user, videoComment, req, res } = options+if (videoComment.isDeleted()) {res.fail({status: HttpStatusCode.CONFLICT_409,- message: 'This comment is already deleted'+ message: req.t('This comment is already deleted')})- return false+ return Promise.resolve(false)}- const userAccount = user.Account-- if (- user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT) === false && // Not a moderator- videoComment.accountId !== userAccount.id && // Not the comment owner- videoComment.Video.VideoChannel.accountId !== userAccount.id // Not the video owner- ) {- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot remove video comment of another user'- })- return false+ // Owner of the comment+ if (videoComment.accountId === user.Account.id) {+ return Promise.resolve(true)}- return true+ return checkCanManageCommentsOfVideo(options)}-function checkUserCanApproveVideoComment (user: MUserAccountUrl, videoComment: MCommentOwnerVideoReply, res: express.Response) {+function checkCanApproveVideoComment (options: {+ user: MUserAccountUrl+ videoComment: MCommentOwnerVideoReply+ req: express.Request+ res: express.Response+}): Promise<boolean> {+ const { user, videoComment, req, res } = options+if (videoComment.isDeleted()) {res.fail({status: HttpStatusCode.CONFLICT_409,- message: 'This comment is deleted'+ message: req.t('This comment is deleted')})- return false+ return Promise.resolve(false)}if (videoComment.heldForReview !== true) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'This comment is not held for review'+ message: req.t('This comment is not held for review')})- return false+ return Promise.resolve(false)}- const userAccount = user.Account+ return checkCanManageCommentsOfVideo({ user, videoComment, req, res })+}- if (- user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT) === false && // Not a moderator- videoComment.Video.VideoChannel.accountId !== userAccount.id // Not the video owner- ) {- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot approve video comment of another user'- })- return false- }+async function checkCanManageCommentsOfVideo (options: {+ user: MUserAccountUrl+ videoComment: MCommentOwnerVideoReply+ req: express.Request+ res: express.Response+}) {+ const { user, videoComment, req, res } = options- return true+ if (user.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)) return true++ const channel = await VideoChannelModel.loadAndPopulateAccount(videoComment.Video.VideoChannel.id)+ if (await checkCanManageChannel({ channel, user, req, res: null, checkCanManage: true, checkIsOwner: false })) return true++ res.fail({+ status: HttpStatusCode.FORBIDDEN_403,+ message: req.t('User does not have the permission to delete this comment')+ })++ return false}async function isVideoCommentAccepted (req: express.Request, res: express.Response, video: MVideoFullLight, isReply: boolean) {diff --git a/server/core/middlewares/validators/videos/video-imports.ts b/server/core/middlewares/validators/videos/video-imports.tsindex d1829d4a71..1dc6724873 100644--- a/server/core/middlewares/validators/videos/video-imports.ts+++ b/server/core/middlewares/validators/videos/video-imports.ts@@ -3,20 +3,20 @@ import { HttpStatusCode, UserRight, VideoImportCreate, VideoImportState } from 'import { isResolvingToUnicastOnly } from '@server/helpers/dns.js'import { isPreImportVideoAccepted } from '@server/lib/moderation.js'import { Hooks } from '@server/lib/plugins/hooks.js'-import { MUserAccountId, MVideoImport } from '@server/types/models/index.js'+import { MUserAccountId, MVideoImportDefault } from '@server/types/models/index.js'import express from 'express'import { body, param, query } from 'express-validator'-import { isIdValid, toIntOrNull } from '../../../helpers/custom-validators/misc.js'+import { isIdValid, toBooleanOrNull, toIntOrNull } from '../../../helpers/custom-validators/misc.js'import { isVideoImportTargetUrlValid, isVideoImportTorrentFile } from '../../../helpers/custom-validators/video-imports.js'import { isValidPasswordProtectedPrivacy, isVideoMagnetUriValid, isVideoNameValid } from '../../../helpers/custom-validators/videos.js'import { cleanUpReqFiles } from '../../../helpers/express-utils.js'import { logger } from '../../../helpers/logger.js'import { CONFIG } from '../../../initializers/config.js'import { CONSTRAINTS_FIELDS } from '../../../initializers/constants.js'-import { areValidationErrors, doesVideoChannelOfAccountExist, doesVideoImportExist } from '../shared/index.js'+import { areValidationErrors, checkCanManageVideo, doesChannelIdExist, doesVideoImportExist } from '../shared/index.js'import { areErrorsInNSFW, getCommonVideoEditAttributes } from './videos.js'-const videoImportAddValidator = getCommonVideoEditAttributes().concat([+export const videoImportAddValidator = getCommonVideoEditAttributes().concat([body('channelId').customSanitizer(toIntOrNull).custom(isIdValid),@@ -43,7 +43,6 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([.withMessage('Video passwords should be an array.'),async (req: express.Request, res: express.Response, next: express.NextFunction) => {- const user = res.locals.oauth.token.Userconst torrentFile = req.files?.['torrentfile'] ? req.files['torrentfile'][0] : undefinedif (areValidationErrors(req, res)) return cleanUpReqFiles(req)@@ -56,7 +55,7 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([return res.fail({status: HttpStatusCode.CONFLICT_409,- message: 'HTTP import is not enabled on this instance.'+ message: req.t('HTTP import is not enabled on this instance')})}@@ -65,17 +64,19 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([return res.fail({status: HttpStatusCode.CONFLICT_409,- message: 'Torrent/magnet URI import is not enabled on this instance.'+ message: req.t('Torrent/magnet URI import is not enabled on this instance')})}- if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)+ if (!await doesChannelIdExist({ id: req.body.channelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: false })) {+ return cleanUpReqFiles(req)+ }// Check we have at least 1 required paramif (!req.body.targetUrl && !req.body.magnetUri && !torrentFile) {cleanUpReqFiles(req)- return res.fail({ message: 'Should have a magnetUri or a targetUrl or a torrent file.' })+ return res.fail({ message: req.t('Should have a magnetUri or a targetUrl or a torrent file') })}if (req.body.targetUrl) {@@ -86,7 +87,7 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([return res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot use non unicast IP as targetUrl.'+ message: req.t('Cannot use non unicast IP as targetUrl')})}}@@ -97,11 +98,15 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([}])-const getMyVideoImportsValidator = [+export const listMyVideoImportsValidator = [query('videoChannelSyncId').optional().custom(isIdValid),+ query('includeCollaborations')+ .optional()+ .customSanitizer(toBooleanOrNull),+(req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return@@ -109,7 +114,7 @@ const getMyVideoImportsValidator = [}]-const videoImportDeleteValidator = [+export const videoImportDeleteValidator = [param('id').custom(isIdValid),@@ -117,12 +122,12 @@ const videoImportDeleteValidator = [if (areValidationErrors(req, res)) returnif (!await doesVideoImportExist(parseInt(req.params.id), res)) return- if (!checkUserCanManageImport(res.locals.oauth.token.user, res.locals.videoImport, res)) return+ if (!await checkCanManageImport({ user: res.locals.oauth.token.User, videoImport: res.locals.videoImport, req, res })) returnif (res.locals.videoImport.state === VideoImportState.PENDING) {return res.fail({status: HttpStatusCode.CONFLICT_409,- message: 'Cannot delete a pending video import. Cancel it or wait for the end of the import first.'+ message: req.t('Cannot delete a pending video import. Cancel it or wait for the end of the import first')})}@@ -130,7 +135,7 @@ const videoImportDeleteValidator = [}]-const videoImportCancelValidator = [+export const videoImportCancelValidator = [param('id').custom(isIdValid),@@ -138,12 +143,12 @@ const videoImportCancelValidator = [if (areValidationErrors(req, res)) returnif (!await doesVideoImportExist(forceNumber(req.params.id), res)) return- if (!checkUserCanManageImport(res.locals.oauth.token.user, res.locals.videoImport, res)) return+ if (!await checkCanManageImport({ user: res.locals.oauth.token.User, videoImport: res.locals.videoImport, req, res })) returnif (res.locals.videoImport.state !== VideoImportState.PENDING) {return res.fail({status: HttpStatusCode.CONFLICT_409,- message: 'Cannot cancel a non pending video import.'+ message: req.t('Cannot cancel a non pending video import')})}@@ -152,14 +157,7 @@ const videoImportCancelValidator = []// -----------------------------------------------------------------------------export {- getMyVideoImportsValidator,- videoImportAddValidator,- videoImportCancelValidator,- videoImportDeleteValidator-}-+// Private// ---------------------------------------------------------------------------async function isImportAccepted (req: express.Request, res: express.Response) {@@ -184,7 +182,7 @@ async function isImportAccepted (req: express.Request, res: express.Response) {res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: acceptedResult.errorMessage || 'Refused to import video'+ message: acceptedResult.errorMessage || req.t('Refused to import video')})return false}@@ -192,14 +190,34 @@ async function isImportAccepted (req: express.Request, res: express.Response) {return true}-function checkUserCanManageImport (user: MUserAccountId, videoImport: MVideoImport, res: express.Response) {- if (user.hasRight(UserRight.MANAGE_VIDEO_IMPORTS) === false && videoImport.userId !== user.id) {- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot manage video import of another user'+async function checkCanManageImport (options: {+ user: MUserAccountId+ videoImport: MVideoImportDefault+ req: express.Request+ res: express.Response+}) {+ const { user, videoImport, req, res } = options++ if (user.hasRight(UserRight.MANAGE_VIDEO_IMPORTS) === true) return true+ if (videoImport.userId === user.id) return true+ if (+ videoImport.Video &&+ await checkCanManageVideo({+ user,+ video: videoImport.Video,+ req,+ res,+ right: UserRight.MANAGE_VIDEO_IMPORTS,+ checkIsLocal: true,+ checkIsOwner: false})- return false+ ) {+ return true}- return true+ res.fail({+ status: HttpStatusCode.FORBIDDEN_403,+ message: req.t('Cannot manage video import of another user')+ })+ return false}diff --git a/server/core/middlewares/validators/videos/video-live.ts b/server/core/middlewares/validators/videos/video-live.tsindex 633ea392e2..1bf8b8cb81 100644--- a/server/core/middlewares/validators/videos/video-live.ts+++ b/server/core/middlewares/validators/videos/video-live.ts@@ -7,7 +7,7 @@ import {UserRight,VideoState} from '@peertube/peertube-models'-import { isLiveLatencyModeValid, areLiveSchedulesValid } from '@server/helpers/custom-validators/video-lives.js'+import { areLiveSchedulesValid, isLiveLatencyModeValid } from '@server/helpers/custom-validators/video-lives.js'import { CONSTRAINTS_FIELDS } from '@server/initializers/constants.js'import { isLocalLiveVideoAccepted } from '@server/lib/moderation.js'import { Hooks } from '@server/lib/plugins/hooks.js'@@ -21,16 +21,10 @@ import { isValidPasswordProtectedPrivacy, isVideoNameValid, isVideoReplayPrivacyimport { cleanUpReqFiles } from '../../../helpers/express-utils.js'import { logger } from '../../../helpers/logger.js'import { CONFIG } from '../../../initializers/config.js'-import {- areValidationErrors,- checkUserCanManageVideo,- doesVideoChannelOfAccountExist,- doesVideoExist,- isValidVideoIdParam-} from '../shared/index.js'+import { areValidationErrors, checkCanManageVideo, doesChannelIdExist, doesVideoExist, isValidVideoIdParam } from '../shared/index.js'import { areErrorsInNSFW, getCommonVideoEditAttributes } from './videos.js'-const videoLiveGetValidator = [+export const videoLiveGetValidator = [isValidVideoIdParam('videoId'),async (req: express.Request, res: express.Response, next: express.NextFunction) => {@@ -51,7 +45,7 @@ const videoLiveGetValidator = [}]-const videoLiveAddValidator = getCommonVideoEditAttributes().concat([+export const videoLiveAddValidator = getCommonVideoEditAttributes().concat([body('channelId').customSanitizer(toIntOrNull).custom(isIdValid),@@ -127,8 +121,9 @@ const videoLiveAddValidator = getCommonVideoEditAttributes().concat([})}- const user = res.locals.oauth.token.User- if (!await doesVideoChannelOfAccountExist(body.channelId, user, res)) return cleanUpReqFiles(req)+ if (!await doesChannelIdExist({ id: body.channelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: false })) {+ return cleanUpReqFiles(req)+ }if (CONFIG.LIVE.MAX_INSTANCE_LIVES !== -1) {const totalInstanceLives = await VideoModel.countLives({ remote: false, mode: 'not-ended' })@@ -145,6 +140,8 @@ const videoLiveAddValidator = getCommonVideoEditAttributes().concat([}if (CONFIG.LIVE.MAX_USER_LIVES !== -1) {+ const user = res.locals.oauth.token.User+const totalUserLives = await VideoModel.countLivesOfAccount(user.Account.id)if (totalUserLives >= CONFIG.LIVE.MAX_USER_LIVES) {@@ -164,7 +161,7 @@ const videoLiveAddValidator = getCommonVideoEditAttributes().concat([}])-const videoLiveUpdateValidator = [+export const videoLiveUpdateValidator = [body('saveReplay').optional().customSanitizer(toBooleanOrNull)@@ -184,7 +181,7 @@ const videoLiveUpdateValidator = [.optional().custom(areLiveSchedulesValid).withMessage('Should have a valid schedules array'),- (req: express.Request, res: express.Response, next: express.NextFunction) => {+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) returnconst body: LiveVideoUpdate = req.body@@ -211,23 +208,43 @@ const videoLiveUpdateValidator = [// Check the user can manage the liveconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.GET_ANY_LIVE, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.GET_ANY_LIVE,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) returnreturn next()}]-const videoLiveListSessionsValidator = [- (req: express.Request, res: express.Response, next: express.NextFunction) => {+export const videoLiveListSessionsValidator = [+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {// Check the user can manage the liveconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.GET_ANY_LIVE, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.GET_ANY_LIVE,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) returnreturn next()}]-const videoLiveFindReplaySessionValidator = [+export const videoLiveFindReplaySessionValidator = [isValidVideoIdParam('videoId'),async (req: express.Request, res: express.Response, next: express.NextFunction) => {@@ -249,15 +266,7 @@ const videoLiveFindReplaySessionValidator = []// -----------------------------------------------------------------------------export {- videoLiveAddValidator,- videoLiveFindReplaySessionValidator,- videoLiveGetValidator,- videoLiveListSessionsValidator,- videoLiveUpdateValidator-}-+// Private// ---------------------------------------------------------------------------async function isLiveVideoAccepted (req: express.Request, res: express.Response) {diff --git a/server/core/middlewares/validators/videos/video-ownership-changes.ts b/server/core/middlewares/validators/videos/video-ownership-changes.tsindex 8c9e1d8572..742a46dee2 100644--- a/server/core/middlewares/validators/videos/video-ownership-changes.ts+++ b/server/core/middlewares/validators/videos/video-ownership-changes.ts@@ -1,16 +1,17 @@import { HttpStatusCode, UserRight, VideoChangeOwnershipAccept, VideoChangeOwnershipStatus, VideoState } from '@peertube/peertube-models'import { isIdValid } from '@server/helpers/custom-validators/misc.js'-import { checkUserCanTerminateOwnershipChange } from '@server/helpers/custom-validators/video-ownership.js'+import { CONFIG } from '@server/initializers/config.js'import { AccountModel } from '@server/models/account/account.js'-import { MVideoWithAllFiles } from '@server/types/models/index.js'+import { MUserAccountId, MVideoChangeOwnershipFull, MVideoWithAllFiles } from '@server/types/models/index.js'import express from 'express'import { param } from 'express-validator'import {areValidationErrors,- checkUserCanManageVideo,+ checkCanManageAccount,+ checkCanManageVideo,checkUserQuota,doesChangeVideoOwnershipExist,- doesVideoChannelOfAccountExist,+ doesChannelIdExist,doesVideoExist,isValidVideoIdParam} from '../shared/index.js'@@ -24,10 +25,12 @@ export const videosChangeOwnershipValidator = [// Check if the user who did the request is able to change the ownership of the videoif (- !checkUserCanManageVideo({+ !await checkCanManageVideo({user: res.locals.oauth.token.User,video: res.locals.videoAll,right: UserRight.CHANGE_VIDEO_OWNERSHIP,+ checkIsOwner: true,+ checkIsLocal: true,req,res})@@ -35,7 +38,9 @@ export const videosChangeOwnershipValidator = [const nextOwner = await AccountModel.loadLocalByName(req.body.username)if (!nextOwner) {- res.fail({ message: 'Changing video ownership to a remote account is not supported yet' })+ res.fail({+ message: req.t('{username} does not exist on {instanceName}', { username: req.body.username, instanceName: CONFIG.INSTANCE.NAME })+ })return}@@ -50,17 +55,24 @@ export const videosTerminateChangeOwnershipValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesChangeVideoOwnershipExist(req.params.id, res)) return+ if (!await doesChangeVideoOwnershipExist(req.params.id, req, res)) return// Check if the user who did the request is able to change the ownership of the video- if (!checkUserCanTerminateOwnershipChange(res.locals.oauth.token.User, res.locals.videoChangeOwnership, res)) return+ if (+ !checkCanTerminateOwnershipChange({+ user: res.locals.oauth.token.User,+ videoChangeOwnership: res.locals.videoChangeOwnership,+ req,+ res+ })+ ) returnconst videoChangeOwnership = res.locals.videoChangeOwnershipif (videoChangeOwnership.status !== VideoChangeOwnershipStatus.WAITING) {res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Ownership already accepted or refused'+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('Ownership already accepted or refused')})return}@@ -72,13 +84,13 @@ export const videosTerminateChangeOwnershipValidator = [export const videosAcceptChangeOwnershipValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {const body = req.body as VideoChangeOwnershipAccept- if (!await doesVideoChannelOfAccountExist(body.channelId, res.locals.oauth.token.User, res)) return+ if (!await doesChannelIdExist({ id: body.channelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: true })) returnconst videoChangeOwnership = res.locals.videoChangeOwnershipconst video = videoChangeOwnership.Video- if (!await checkCanAccept(video, res)) return+ if (!await checkCanAccept(video, req, res)) returnreturn next()}@@ -88,12 +100,12 @@ export const videosAcceptChangeOwnershipValidator = [// Private// ----------------------------------------------------------------------------async function checkCanAccept (video: MVideoWithAllFiles, res: express.Response): Promise<boolean> {+async function checkCanAccept (video: MVideoWithAllFiles, req: express.Request, res: express.Response): Promise<boolean> {if (video.isLive) {if (video.state !== VideoState.WAITING_FOR_LIVE) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'You can accept an ownership change of a published live.'+ message: req.t('You can accept an ownership change of a published live.')})return false@@ -104,7 +116,27 @@ async function checkCanAccept (video: MVideoWithAllFiles, res: express.Response)const user = res.locals.oauth.token.User- if (!await checkUserQuota(user, video.getMaxQualityBytes(), res)) return false+ if (!await checkUserQuota({ user, videoFileSize: video.getMaxQualityBytes(), req, res })) return false++ return true+}++function checkCanTerminateOwnershipChange (options: {+ user: MUserAccountId+ videoChangeOwnership: MVideoChangeOwnershipFull+ req: express.Request+ res: express.Response+}) {+ const { user, videoChangeOwnership, req, res } = options++ 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 false+ }return true}diff --git a/server/core/middlewares/validators/videos/video-passwords.ts b/server/core/middlewares/validators/videos/video-passwords.tsindex 8d7e566293..e403631cad 100644--- a/server/core/middlewares/validators/videos/video-passwords.ts+++ b/server/core/middlewares/validators/videos/video-passwords.ts@@ -1,36 +1,46 @@+import { UserRight } from '@peertube/peertube-models'+import { isIdValid } from '@server/helpers/custom-validators/misc.js'+import { isValidPasswordProtectedPrivacy } from '@server/helpers/custom-validators/videos.js'import express from 'express'+import { body, param } from 'express-validator'import {areValidationErrors,+ checkCanDeleteVideoPassword,+ checkCanManageVideo,doesVideoExist,- isVideoPasswordProtected,- isValidVideoIdParam,doesVideoPasswordExist,- isVideoPasswordDeletable,- checkUserCanManageVideo+ isValidVideoIdParam,+ checkVideoIsPasswordProtected} from '../shared/index.js'-import { body, param } from 'express-validator'-import { isIdValid } from '@server/helpers/custom-validators/misc.js'-import { isValidPasswordProtectedPrivacy } from '@server/helpers/custom-validators/videos.js'-import { UserRight } from '@peertube/peertube-models'-const listVideoPasswordValidator = [+export const listVideoPasswordValidator = [isValidVideoIdParam('videoId'),async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) returnif (!await doesVideoExist(req.params.videoId, res)) return- if (!isVideoPasswordProtected(res)) return+ if (!checkVideoIsPasswordProtected(req, res)) return// Check if the user who did the request is able to access video password listconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.SEE_ALL_VIDEOS, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.SEE_ALL_VIDEOS,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) returnreturn next()}]-const updateVideoPasswordListValidator = [+export const updateVideoPasswordListValidator = [body('passwords').optional().isArray()@@ -44,13 +54,23 @@ const updateVideoPasswordListValidator = [// Check if the user who did the request is able to update video passwordsconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) returnreturn next()}]-const removeVideoPasswordValidator = [+export const removeVideoPasswordValidator = [isValidVideoIdParam('videoId'),param('passwordId')@@ -60,18 +80,11 @@ const removeVideoPasswordValidator = [if (areValidationErrors(req, res)) returnif (!await doesVideoExist(req.params.videoId, res)) return- if (!isVideoPasswordProtected(res)) return- if (!await doesVideoPasswordExist(req.params.passwordId, res)) return- if (!await isVideoPasswordDeletable(res)) return+ if (!checkVideoIsPasswordProtected(req, res)) return+ if (!await doesVideoPasswordExist({ id: req.params.passwordId, req, res })) return++ if (!await checkCanDeleteVideoPassword({ user: res.locals.oauth.token.User, video: res.locals.videoAll, req, res })) returnreturn next()}]--// -----------------------------------------------------------------------------export {- listVideoPasswordValidator,- updateVideoPasswordListValidator,- removeVideoPasswordValidator-}diff --git a/server/core/middlewares/validators/videos/video-playlists.ts b/server/core/middlewares/validators/videos/video-playlists.tsindex 3549e24667..1208016d1c 100644--- a/server/core/middlewares/validators/videos/video-playlists.ts+++ b/server/core/middlewares/validators/videos/video-playlists.ts@@ -1,4 +1,4 @@-import { forceNumber } from '@peertube/peertube-core-utils'+import { arrayify, forceNumber } from '@peertube/peertube-core-utils'import {HttpStatusCode,UserRight,@@ -8,6 +8,8 @@ import {VideoPlaylistType,VideoPlaylistUpdate} from '@peertube/peertube-models'+import { isStringArray } from '@server/helpers/custom-validators/search.js'+import { VideoChannelModel } from '@server/models/video/video-channel.js'import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'import { ExpressPromiseHandler } from '@server/types/express-handler.js'import { MUserAccountId } from '@server/types/models/index.js'@@ -18,6 +20,7 @@ import {isIdOrUUIDValid,isIdValid,isUUIDValid,+ toBooleanOrNull,toCompleteUUID,toIntArray,toIntOrNull,@@ -34,11 +37,13 @@ import { isVideoImageValid } from '../../../helpers/custom-validators/videos.js'import { cleanUpReqFiles } from '../../../helpers/express-utils.js'import { CONSTRAINTS_FIELDS } from '../../../initializers/constants.js'import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element.js'-import { MVideoPlaylist } from '../../../types/models/video/video-playlist.js'-import { authenticatePromise } from '../../auth.js'+import { MVideoPlaylistFullSummary } from '../../../types/models/video/video-playlist.js'+import { authenticateOrFail } from '../../auth.js'import {areValidationErrors,- doesVideoChannelOfAccountExist,+ checkCanManageAccount,+ checkCanManageChannel,+ doesChannelIdExist,doesVideoExist,doesVideoPlaylistExist,isValidPlaylistIdParam,@@ -53,7 +58,10 @@ export const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concif (areValidationErrors(req, res)) return cleanUpReqFiles(req)const body: VideoPlaylistCreate = req.body- if (body.videoChannelId && !await doesVideoChannelOfAccountExist(body.videoChannelId, res.locals.oauth.token.User, res)) {+ if (+ body.videoChannelId &&+ !await doesChannelIdExist({ id: body.videoChannelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: false })+ ) {return cleanUpReqFiles(req)}@@ -63,7 +71,7 @@ export const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().conc) {cleanUpReqFiles(req)- return res.fail({ message: 'Cannot set "public" or "unlisted" a playlist that is not assigned to a channel.' })+ return res.fail({ message: req.t('Cannot set "public" or "unlisted" a playlist that is not assigned to a channel.') })}return next()@@ -80,11 +88,19 @@ export const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().casync (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return cleanUpReqFiles(req)- if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)+ if (!await doesVideoPlaylistExist({ id: req.params.playlistId, req, res, fetchType: 'all' })) return cleanUpReqFiles(req)const videoPlaylist = getPlaylist(res)- if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {+ if (+ !await checkCanManagePlaylist({+ user: res.locals.oauth.token.User,+ videoPlaylist,+ right: UserRight.REMOVE_ANY_VIDEO_PLAYLIST,+ req,+ res+ })+ ) {return cleanUpReqFiles(req)}@@ -100,16 +116,28 @@ export const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().c) {cleanUpReqFiles(req)- return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })+ return res.fail({ message: req.t('Cannot set "public" a playlist that is not assigned to a channel.') })}if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {cleanUpReqFiles(req)- return res.fail({ message: 'Cannot update a watch later playlist.' })+ return res.fail({ message: req.t('Cannot update a watch later playlist.') })+ }++ if (+ body.videoChannelId &&+ !await doesChannelIdExist({ id: body.videoChannelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: false })+ ) {+ return cleanUpReqFiles(req)}- if (body.videoChannelId && !await doesVideoChannelOfAccountExist(body.videoChannelId, res.locals.oauth.token.User, res)) {+ if (res.locals.videoChannel && res.locals.videoChannel.accountId !== videoPlaylist.ownerAccountId) {+ res.fail({+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('The channel must be owned by the same account as the playlist')+ })+return cleanUpReqFiles(req)}@@ -123,14 +151,22 @@ export const videoPlaylistsDeleteValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return+ if (!await doesVideoPlaylistExist({ id: req.params.playlistId, req, res })) returnconst videoPlaylist = getPlaylist(res)if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {- return res.fail({ message: 'Cannot delete a watch later playlist.' })+ return res.fail({ message: req.t('Cannot delete a watch later playlist.') })}- if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {+ if (+ !await checkCanManagePlaylist({+ user: res.locals.oauth.token.User,+ videoPlaylist,+ right: UserRight.REMOVE_ANY_VIDEO_PLAYLIST,+ req,+ res+ })+ ) {return}@@ -145,7 +181,7 @@ export const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) =>async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return+ if (!await doesVideoPlaylistExist({ id: req.params.playlistId, req, res, fetchType })) returnconst videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary@@ -155,26 +191,24 @@ export const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) =>return res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Playlist not found'+ message: req.t('Playlist not found')})}if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {- await authenticatePromise({ req, res })-- const user = res.locals.oauth ? res.locals.oauth.token.User : null+ if (!await authenticateOrFail({ req, res })) returnif (- !user ||- (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))- ) {- return res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot get this private video playlist.'+ !await checkCanManagePlaylist({+ user: res.locals.oauth.token.User,+ videoPlaylist,+ right: UserRight.UPDATE_ANY_VIDEO_PLAYLIST,+ req,+ res})+ ) {+ return}-- return next()}return next()@@ -194,6 +228,23 @@ export const videoPlaylistsSearchValidator = [}]+export const videoPlaylistsAccountValidator = [+ query('includeCollaborations')+ .optional()+ .customSanitizer(toBooleanOrNull),++ query('channelNameOneOf')+ .optional()+ .customSanitizer(arrayify)+ .custom(isStringArray).withMessage('Should have a valid channelNameOneOf array'),++ (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return++ return next()+ }+]+export const videoPlaylistsAddVideoValidator = [isValidPlaylistIdParam('playlistId'),@@ -210,12 +261,20 @@ export const videoPlaylistsAddVideoValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return+ if (!await doesVideoPlaylistExist({ id: req.params.playlistId, req, res, fetchType: 'all' })) returnif (!await doesVideoExist(req.body.videoId, res, 'only-video-and-blacklist')) returnconst videoPlaylist = getPlaylist(res)- if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {+ if (+ !await checkCanManagePlaylist({+ user: res.locals.oauth.token.User,+ videoPlaylist,+ right: UserRight.UPDATE_ANY_VIDEO_PLAYLIST,+ req,+ res+ })+ ) {return}@@ -225,9 +284,11 @@ export const videoPlaylistsAddVideoValidator = [export const videoPlaylistsUpdateOrRemoveVideoValidator = [isValidPlaylistIdParam('playlistId'),+param('playlistElementId').customSanitizer(toCompleteUUID).custom(isIdValid).withMessage('Should have an element id/uuid/short uuid'),+body('startTimestamp').optional().custom(isVideoPlaylistTimestampValid),@@ -238,7 +299,7 @@ export const videoPlaylistsUpdateOrRemoveVideoValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return+ if (!await doesVideoPlaylistExist({ id: req.params.playlistId, req, res, fetchType: 'all' })) returnconst videoPlaylist = getPlaylist(res)@@ -246,13 +307,21 @@ export const videoPlaylistsUpdateOrRemoveVideoValidator = [if (!videoPlaylistElement) {res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Video playlist element not found'+ message: req.t('Video playlist element not found')})return}res.locals.videoPlaylistElement = videoPlaylistElement- if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return+ if (+ !await checkCanManagePlaylist({+ user: res.locals.oauth.token.User,+ videoPlaylist,+ right: UserRight.UPDATE_ANY_VIDEO_PLAYLIST,+ req,+ res+ })+ ) returnreturn next()}@@ -273,7 +342,7 @@ export const videoPlaylistElementAPGetValidator = [if (!videoPlaylistElement) {res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Video playlist element not found'+ message: req.t('Video playlist element not found')})return}@@ -281,7 +350,7 @@ export const videoPlaylistElementAPGetValidator = [if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {return res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot get this private video playlist.'+ message: req.t('Cannot get this private video playlist.')})}@@ -309,12 +378,19 @@ export const videoPlaylistsReorderInChannelValidator = [const reorderLength: number = req.body.reorderLengthif (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {- res.fail({ message: `Start position or insert after position exceed the channel limits (max: ${nextPosition - 1})` })+ res.fail({+ message: req.t('Start position or insert after position exceed the channel limits (max: {max})', { max: nextPosition - 1 })+ })return}if (reorderLength && reorderLength + startPosition > nextPosition) {- res.fail({ message: `Reorder length with this start position exceeds the channel limits (max: ${nextPosition - startPosition})` })+ res.fail({+ message: req.t(+ 'Reorder length with this start position exceeds the channel limits (max: {max})',+ { max: nextPosition - startPosition }+ )+ })return}@@ -336,10 +412,18 @@ export const videoPlaylistsReorderVideosValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return+ if (!await doesVideoPlaylistExist({ id: req.params.playlistId, req, res, fetchType: 'all' })) returnconst videoPlaylist = getPlaylist(res)- if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return+ if (+ !await checkCanManagePlaylist({+ user: res.locals.oauth.token.User,+ videoPlaylist,+ right: UserRight.UPDATE_ANY_VIDEO_PLAYLIST,+ req,+ res+ })+ ) returnconst nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)const startPosition: number = req.body.startPosition@@ -347,12 +431,18 @@ export const videoPlaylistsReorderVideosValidator = [const reorderLength: number = req.body.reorderLengthif (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {- res.fail({ message: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })+ res.fail({+ message: req.t('Start position or insert after position exceed the playlist limits (max: {max})', { max: nextPosition - 1 })+ })return}if (reorderLength && reorderLength + startPosition > nextPosition) {- res.fail({ message: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })+ res.fail({+ message: req.t('Reorder length with this start position exceeds the playlist limits (max: {max})', {+ max: nextPosition - startPosition+ })+ })return}@@ -384,6 +474,8 @@ export const doVideosInPlaylistExistValidator = [}]+// ---------------------------------------------------------------------------+// Private// ---------------------------------------------------------------------------function getCommonPlaylistEditAttributes () {@@ -409,32 +501,49 @@ function getCommonPlaylistEditAttributes () {] as (ValidationChain | ExpressPromiseHandler)[]}-function checkUserCanManageVideoPlaylist (- user: MUserAccountId,- videoPlaylist: MVideoPlaylist,- right: UserRightType,+async function checkCanManagePlaylist (options: {+ user: MUserAccountId+ videoPlaylist: MVideoPlaylistFullSummary+ right: UserRightType+ req: express.Requestres: express.Response-) {- if (videoPlaylist.isOwned() === false) {+}) {+ const { user, videoPlaylist, right, res, req } = options++ if (videoPlaylist.isLocal() === false) {res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot manage video playlist of another server.'+ message: req.t('Cannot manage video playlist of another server.')})return false}- // Check if the user can manage the video playlist- // The user can delete it if s/he is an admin- // Or if s/he is the video playlist's owner- if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {- res.fail({- status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot manage video playlist of another user'- })- return false+ if (checkCanManageAccount({ user, account: videoPlaylist.OwnerAccount, specialRight: right, req, res: null })) return true++ if (videoPlaylist.videoChannelId) {+ const channel = await VideoChannelModel.loadAndPopulateAccount(videoPlaylist.videoChannelId)++ if (+ await checkCanManageChannel({+ channel,+ user,+ req,+ res: null,+ checkCanManage: true,+ checkIsOwner: false,+ specialRight: right+ })+ ) {+ return true+ }}- return true+ res.fail({+ status: HttpStatusCode.FORBIDDEN_403,+ message: req.t('Cannot manage video playlist of another user')+ })++ return false}function getPlaylist (res: express.Response) {diff --git a/server/core/middlewares/validators/videos/video-source.ts b/server/core/middlewares/validators/videos/video-source.tsindex 6d958ab586..c14eaa9ba0 100644--- a/server/core/middlewares/validators/videos/video-source.ts+++ b/server/core/middlewares/validators/videos/video-source.ts@@ -10,7 +10,7 @@ import { param } from 'express-validator'import {areValidationErrors,checkCanAccessVideoSourceFile,- checkUserCanManageVideo,+ checkCanManageVideo,doesVideoExist,isValidVideoIdParam} from '../shared/index.js'@@ -26,14 +26,16 @@ export const videoSourceGetLatestValidator = [const video = getVideoWithAttributes(res) as MVideoFullLightconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return+ if (!await checkCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res, checkIsLocal: true, checkIsOwner: false })) {+ return+ }res.locals.videoSource = await VideoSourceModel.loadLatest(video.id)if (!res.locals.videoSource) {return res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Video source not found'+ message: req.t('Video source not found')})}@@ -72,7 +74,7 @@ export const replaceVideoSourceResumableInitValidator = [const fileMetadata = res.locals.uploadVideoFileResumableMetadataconst files = { videofile: [ fileMetadata ] }- if (await commonVideoFileChecks({ res, user, videoFileSize: fileMetadata.size, files }) === false) return+ if (await commonVideoFileChecks({ req, res, user, videoFileSize: fileMetadata.size, files }) === false) returnreturn next()}@@ -88,7 +90,7 @@ export const originalVideoFileDownloadValidator = [if (!videoSource) {return res.fail({status: HttpStatusCode.NOT_FOUND_404,- message: 'Original video file not found'+ message: req.t('Original video file not found')})}@@ -113,7 +115,7 @@ async function checkCanUpdateVideoFile (options: {if (!CONFIG.VIDEO_FILE.UPDATE.ENABLED) {res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: 'Updating the file of an existing video is not allowed on this instance'+ message: req.t('Updating the file of an existing video is not allowed on this instance')})return false}@@ -123,9 +125,11 @@ async function checkCanUpdateVideoFile (options: {const user = res.locals.oauth.token.Userconst video = res.locals.videoAll- if (!checkUserCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return false+ if (!await checkCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res, checkIsLocal: true, checkIsOwner: false })) {+ return false+ }- if (!checkVideoFileCanBeEdited(video, res)) return false+ if (!checkVideoFileCanBeEdited(video, req, res)) return falsereturn true}diff --git a/server/core/middlewares/validators/videos/video-stats.ts b/server/core/middlewares/validators/videos/video-stats.tsindex 60ae29c707..3df58790a7 100644--- a/server/core/middlewares/validators/videos/video-stats.ts+++ b/server/core/middlewares/validators/videos/video-stats.ts@@ -4,7 +4,7 @@ import { isDateValid } from '@server/helpers/custom-validators/misc.js'import { isValidStatTimeserieMetric } from '@server/helpers/custom-validators/video-stats.js'import { STATS_TIMESERIE } from '@server/initializers/constants.js'import { HttpStatusCode, UserRight, VideoStatsTimeserieQuery } from '@peertube/peertube-models'-import { areValidationErrors, checkUserCanManageVideo, doesVideoExist, isValidVideoIdParam } from '../shared/index.js'+import { areValidationErrors, checkCanManageVideo, doesVideoExist, isValidVideoIdParam } from '../shared/index.js'export const videoOverallOrUserAgentStatsValidator = [isValidVideoIdParam('videoId'),@@ -89,8 +89,17 @@ export const videoTimeseriesStatsValidator = [async function commonStatsCheck (req: express.Request, res: express.Response) {if (!await doesVideoExist(req.params.videoId, res, 'all')) return false+if (- !checkUserCanManageVideo({ user: res.locals.oauth.token.User, video: res.locals.videoAll, right: UserRight.SEE_ALL_VIDEOS, req, res })+ !await checkCanManageVideo({+ user: res.locals.oauth.token.User,+ video: res.locals.videoAll,+ right: UserRight.SEE_ALL_VIDEOS,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })) {return false}diff --git a/server/core/middlewares/validators/videos/video-studio.ts b/server/core/middlewares/validators/videos/video-studio.tsindex 91ee10b513..5fa0eec5ac 100644--- a/server/core/middlewares/validators/videos/video-studio.ts+++ b/server/core/middlewares/validators/videos/video-studio.ts@@ -12,7 +12,7 @@ import { CONFIG } from '@server/initializers/config.js'import { approximateIntroOutroAdditionalSize, getTaskFileFromReq } from '@server/lib/video-studio.js'import { isAudioFile } from '@peertube/peertube-ffmpeg'import { HttpStatusCode, UserRight, VideoStudioCreateEdition, VideoStudioTask } from '@peertube/peertube-models'-import { areValidationErrors, checkUserCanManageVideo, checkUserQuota, doesVideoExist } from '../shared/index.js'+import { areValidationErrors, checkCanManageVideo, checkUserQuota, doesVideoExist } from '../shared/index.js'import { checkVideoFileCanBeEdited } from './shared/index.js'const videoStudioAddEditionValidator = [@@ -79,14 +79,16 @@ const videoStudioAddEditionValidator = [}}- if (!checkVideoFileCanBeEdited(video, res)) return cleanUpReqFiles(req)+ if (!checkVideoFileCanBeEdited(video, req, res)) return cleanUpReqFiles(req)const user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res })) return cleanUpReqFiles(req)+ if (!await checkCanManageVideo({ user, video, right: UserRight.UPDATE_ANY_VIDEO, req, res, checkIsLocal: true, checkIsOwner: false })) {+ return cleanUpReqFiles(req)+ }// Try to make an approximation of bytes added by the intro/outroconst additionalBytes = await approximateIntroOutroAdditionalSize(video, body.tasks, i => getTaskFileFromReq(files, i).path)- if (await checkUserQuota(user, additionalBytes, res) === false) return cleanUpReqFiles(req)+ if (await checkUserQuota({ user, videoFileSize: additionalBytes, req, res }) === false) return cleanUpReqFiles(req)return next()}diff --git a/server/core/middlewares/validators/videos/video-transcoding.ts b/server/core/middlewares/validators/videos/video-transcoding.tsindex 8bc10d0597..9b8263c469 100644--- a/server/core/middlewares/validators/videos/video-transcoding.ts+++ b/server/core/middlewares/validators/videos/video-transcoding.ts@@ -6,7 +6,7 @@ import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'import express from 'express'import { body } from 'express-validator'import { areValidationErrors, doesVideoExist, isValidVideoIdParam } from '../shared/index.js'-import { checkVideoCanBeTranscribedOrTranscripted } from './shared/video-validators.js'+import { checkVideoCanBeTranscribed } from './shared/video-validators.js'const createTranscodingValidator = [isValidVideoIdParam('videoId'),@@ -25,7 +25,7 @@ const createTranscodingValidator = [const video = res.locals.videoAll- if (!checkVideoCanBeTranscribedOrTranscripted(video, res)) return+ if (!checkVideoCanBeTranscribed(video, req, res)) returnif (CONFIG.TRANSCODING.ENABLED !== true) {return res.fail({diff --git a/server/core/middlewares/validators/videos/videos.ts b/server/core/middlewares/validators/videos/videos.tsindex be0add2a01..a01df965b3 100644--- a/server/core/middlewares/validators/videos/videos.ts+++ b/server/core/middlewares/validators/videos/videos.ts@@ -58,9 +58,9 @@ import { VideoModel } from '../../../models/video/video.js'import {areValidationErrors,checkCanAccessVideoStaticFiles,+ checkCanManageVideo,checkCanSeeVideo,- checkUserCanManageVideo,- doesVideoChannelOfAccountExist,+ doesChannelIdExist,doesVideoExist,doesVideoFileOfVideoExist,isValidVideoIdParam,@@ -122,7 +122,6 @@ export const videosAddLegacyValidator = [*/export const videosAddResumableValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {- const user = res.locals.oauth.token.Userconst file = buildUploadXFile(req.body as express.CustomUploadXFile<express.UploadNewVideoXFileMetadata>)const cleanup = () => {safeUploadXCleanup(file)@@ -139,13 +138,18 @@ export const videosAddResumableValidator = [return res.fail({status: HttpStatusCode.SERVICE_UNAVAILABLE_503,- message: 'The upload is already being processed'+ message: req.t('The upload is already being processed')})}await Redis.Instance.setUploadSession(uploadId)- if (!await doesVideoChannelOfAccountExist(file.metadata.channelId, user, res)) return cleanup()+ if (+ !await doesChannelIdExist({ id: file.metadata.channelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: false })+ ) {+ return cleanup()+ }+if (!await addDurationToVideoFileIfNeeded({ videoFile: file, res, middlewareName: 'videosAddResumableValidator' })) return cleanup()if (!await isVideoFileAccepted({ req, res, videoFile: file, hook: 'filter:api.video.upload.accept.result' })) return cleanup()@@ -224,18 +228,42 @@ export const videosUpdateValidator = getCommonVideoEditAttributes().concat([if (!isValidPasswordProtectedPrivacy(req, res)) return cleanUpReqFiles(req)- const video = getVideoWithAttributes(res)+ const video = res.locals.videoAllif (exists(req.body.privacy) && video.isLive && video.privacy !== req.body.privacy && video.state !== VideoState.WAITING_FOR_LIVE) {- return res.fail({ message: 'Cannot update privacy of a live that has already started' })+ return res.fail({ message: req.t('Cannot update privacy of a live that has already started') })}// Check if the user who did the request is able to update the videoconst user = res.locals.oauth.token.User- if (!checkUserCanManageVideo({ user, video: res.locals.videoAll, right: UserRight.UPDATE_ANY_VIDEO, req, res })) {+ if (+ !await checkCanManageVideo({+ user,+ video: res.locals.videoAll,+ right: UserRight.UPDATE_ANY_VIDEO,+ req,+ res,+ checkIsLocal: true,+ checkIsOwner: false+ })+ ) {return cleanUpReqFiles(req)}- if (req.body.channelId && !await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)+ if (+ req.body.channelId &&+ !await doesChannelIdExist({ id: req.body.channelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: false })+ ) {+ return cleanUpReqFiles(req)+ }++ if (res.locals.videoChannel && res.locals.videoChannel.accountId !== video.VideoChannel.accountId) {+ res.fail({+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('The channel must belong to the same account as the original channel')+ })++ return cleanUpReqFiles(req)+ }return next()}@@ -245,7 +273,7 @@ export async function checkVideoFollowConstraints (req: express.Request, res: exconst video = getVideoWithAttributes(res)// Anybody can watch local videos- if (video.isOwned() === true) return next()+ if (video.isLocal() === true) return next()// Logged userif (res.locals.oauth) {@@ -262,7 +290,7 @@ export async function checkVideoFollowConstraints (req: express.Request, res: exreturn res.fail({status: HttpStatusCode.FORBIDDEN_403,- message: 'Cannot get this video regarding follow constraints',+ message: req.t('Cannot get this video regarding follow constraints'),type: ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS,data: {originUrl: video.url@@ -346,12 +374,14 @@ export const videosRemoveValidator = [// Check if the user who did the request is able to delete the videoif (- !checkUserCanManageVideo({+ !await checkCanManageVideo({user: res.locals.oauth.token.User,video: res.locals.videoAll,right: UserRight.REMOVE_ANY_VIDEO,req,- res+ res,+ checkIsLocal: true,+ checkIsOwner: false})) return@@ -548,7 +578,7 @@ export const commonVideosFiltersValidator = [if (((query.nsfwFlagsExcluded || 0) & (query.nsfwFlagsIncluded || 0)) !== 0) {return res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Cannot use same flags in nsfwFlagsIncluded and nsfwFlagsExcluded at the same time'+ message: req.t('Cannot use same flags in nsfwFlagsIncluded and nsfwFlagsExcluded at the same time')})}@@ -558,7 +588,7 @@ export const commonVideosFiltersValidator = [if (query.include || query.privacyOneOf || query.autoTagOneOf) {return res.fail({status: HttpStatusCode.UNAUTHORIZED_401,- message: 'You are not allowed to see all videos, specify a custom include or auto tags filter.'+ message: req.t('You are not allowed to see all videos, specify a custom include or auto tags filter')})}}@@ -566,7 +596,7 @@ export const commonVideosFiltersValidator = [if (!user && exists(query.excludeAlreadyWatched)) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: 'Cannot use excludeAlreadyWatched parameter when auth token is not provided'+ message: req.t('Cannot use excludeAlreadyWatched parameter when auth token is not provided')})return false}@@ -574,7 +604,7 @@ export const commonVideosFiltersValidator = [if (req.query.filter) {res.fail({status: HttpStatusCode.BAD_REQUEST_400,- message: '"filter" query parameter is not supported anymore by PeerTube. Please use "isLocal" and "include" instead'+ message: req.t('"filter" query parameter is not supported anymore by PeerTube. Please use "isLocal" and "include" instead')})return false}@@ -588,12 +618,12 @@ export function areErrorsInNSFW (req: express.Request, res: express.Response) {if (!body.nsfw) {if (body.nsfwFlags) {- res.fail({ message: 'Cannot set nsfwFlags if the video is not NSFW.' })+ res.fail({ message: req.t('Cannot set nsfwFlags if the video is not NSFW') })return true}if (body.nsfwSummary) {- res.fail({ message: 'Cannot set nsfwSummary if the video is not NSFW.' })+ res.fail({ message: req.t('Cannot set nsfwSummary if the video is not NSFW') })return true}}@@ -610,7 +640,7 @@ function areErrorsInScheduleUpdate (req: express.Request, res: express.Response)if (!req.body.scheduleUpdate.updateAt) {logger.warn('Invalid parameters: scheduleUpdate.updateAt is mandatory.')- res.fail({ message: 'Schedule update at is mandatory.' })+ res.fail({ message: req.t('Schedule update at is mandatory') })return true}}@@ -625,12 +655,14 @@ async function commonVideoChecksPass (options: {videoFileSize: numberfiles: express.UploadFilesForCheck}): Promise<boolean> {- const { req, res, user } = options+ const { req, res } = optionsif (areErrorsInScheduleUpdate(req, res)) return falseif (areErrorsInNSFW(req, res)) return false- if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return false+ if (!await doesChannelIdExist({ id: req.body.channelId, req, res, checkCanManage: true, checkIsLocal: true, checkIsOwner: false })) {+ return false+ }if (!await commonVideoFileChecks(options)) return falsediff --git a/server/core/middlewares/validators/watched-words.ts b/server/core/middlewares/validators/watched-words.tsindex 774d30c623..51e75a9a8b 100644--- a/server/core/middlewares/validators/watched-words.ts+++ b/server/core/middlewares/validators/watched-words.ts@@ -16,7 +16,7 @@ export const manageAccountWatchedWordsListValidator = [async (req: express.Request, res: express.Response, next: express.NextFunction) => {if (areValidationErrors(req, res)) return- if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: true, checkManage: true })) return+ if (!await doesAccountHandleExist({ handle: req.params.accountName, req, res, checkIsLocal: true, checkCanManage: true })) returnreturn next()}diff --git a/server/core/models/account/account.ts b/server/core/models/account/account.tsindex c43f0aa915..b7464a5a61 100644--- a/server/core/models/account/account.ts+++ b/server/core/models/account/account.ts@@ -1,4 +1,5 @@import { Account, AccountSummary, ActivityPubActor, VideoPrivacy } from '@peertube/peertube-models'+import { AttributesOnly } from '@peertube/peertube-typescript-utils'import { ModelCache } from '@server/models/shared/model-cache.js'import { FindOptions, IncludeOptions, Includeable, Op, Transaction, WhereOptions, literal } from 'sequelize'import {@@ -33,15 +34,16 @@ import {} from '../../types/models/index.js'import { ActorFollowModel } from '../actor/actor-follow.js'import { ActorImageModel } from '../actor/actor-image.js'-import { ActorModel } from '../actor/actor.js'+import { ActorModel, actorSummaryAttributes } from '../actor/actor.js'import { ApplicationModel } from '../application/application.js'import { AccountAutomaticTagPolicyModel } from '../automatic-tag/account-automatic-tag-policy.js'import { CommentAutomaticTagModel } from '../automatic-tag/comment-automatic-tag.js'import { VideoAutomaticTagModel } from '../automatic-tag/video-automatic-tag.js'import { ServerBlocklistModel } from '../server/server-blocklist.js'-import { ServerModel } from '../server/server.js'+import { ServerModel, serverSummaryAttributes } from '../server/server.js'import { SequelizeModel, buildSQLAttributes, getSort, throwIfNotValid } from '../shared/index.js'import { UserModel } from '../user/user.js'+import { VideoChannelCollaboratorModel } from '../video/video-channel-collaborator.js'import { VideoChannelModel } from '../video/video-channel.js'import { VideoCommentModel } from '../video/video-comment.js'import { VideoPlaylistModel } from '../video/video-playlist.js'@@ -52,6 +54,8 @@ export enum ScopeNames {SUMMARY = 'SUMMARY'}+const accountSummaryAttributes = [ 'id', 'name', 'actorId' ] as const satisfies (keyof AttributesOnly<AccountModel>)[]+export type SummaryOptions = {actorRequired?: boolean // Default: truewhereActor?: WhereOptions@@ -71,14 +75,14 @@ export type SummaryOptions = {@Scopes(() => ({[ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {const serverInclude: IncludeOptions = {- attributes: [ 'host' ],+ attributes: serverSummaryAttributes,model: ServerModel.unscoped(),required: !!options.whereServer,where: options.whereServer}const actorInclude: Includeable = {- attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],+ attributes: actorSummaryAttributes,model: ActorModel.unscoped(),required: options.actorRequired ?? true,where: options.whereActor,@@ -98,7 +102,7 @@ export type SummaryOptions = {]const query: FindOptions = {- attributes: [ 'id', 'name', 'actorId' ]+ attributes: accountSummaryAttributes}if (options.withAccountBlockerIds) {@@ -259,6 +263,12 @@ export class AccountModel extends SequelizeModel<AccountModel> {})declare VideoAutomaticTags: Awaited<VideoAutomaticTagModel>[]+ @HasMany(() => VideoChannelCollaboratorModel, {+ foreignKey: 'accountId',+ onDelete: 'CASCADE'+ })+ declare VideoChannelCollaborators: Awaited<VideoChannelCollaboratorModel>[]+@BeforeDestroystatic async sendDeleteIfOwned (instance: AccountModel, options) {if (!instance.Actor) {@@ -267,7 +277,7 @@ export class AccountModel extends SequelizeModel<AccountModel> {await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)- if (instance.isOwned()) {+ if (instance.isLocal()) {return sendDeleteActor(instance.Actor, options.transaction)}@@ -296,6 +306,15 @@ export class AccountModel extends SequelizeModel<AccountModel> {})}+ static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix,+ includeAttributes: accountSummaryAttributes+ })+ }+// ---------------------------------------------------------------------------static load (id: number, transaction?: Transaction): Promise<MAccountDefault> {@@ -505,8 +524,8 @@ export class AccountModel extends SequelizeModel<AccountModel> {})}- isOwned () {- return this.Actor.isOwned()+ isLocal () {+ return this.Actor.isLocal()}isOutdated () {diff --git a/server/core/models/actor/actor-follow.ts b/server/core/models/actor/actor-follow.tsindex 6852a0b3a0..9922a01577 100644--- a/server/core/models/actor/actor-follow.ts+++ b/server/core/models/actor/actor-follow.ts@@ -385,15 +385,15 @@ export class ActorFollowModel extends SequelizeModel<ActorFollowModel> {static listInstanceFollowingForApi (options: ListFollowingOptions) {return Promise.all([- new InstanceListFollowingQueryBuilder(this.sequelize, options).countFollowing(),- new InstanceListFollowingQueryBuilder(this.sequelize, options).listFollowing()+ new InstanceListFollowingQueryBuilder(this.sequelize, options).count(),+ new InstanceListFollowingQueryBuilder(this.sequelize, options).list<MActorFollowFormattable>()]).then(([ total, data ]) => ({ total, data }))}static listFollowersForApi (options: ListFollowersOptions) {return Promise.all([- new InstanceListFollowersQueryBuilder(this.sequelize, options).countFollowers(),- new InstanceListFollowersQueryBuilder(this.sequelize, options).listFollowers()+ new InstanceListFollowersQueryBuilder(this.sequelize, options).count(),+ new InstanceListFollowersQueryBuilder(this.sequelize, options).list<MActorFollowFormattable>()]).then(([ total, data ]) => ({ total, data }))}diff --git a/server/core/models/actor/actor-image.ts b/server/core/models/actor/actor-image.tsindex b54b1ae678..49d87070a5 100644--- a/server/core/models/actor/actor-image.ts+++ b/server/core/models/actor/actor-image.ts@@ -190,7 +190,7 @@ export class ActorImageModel extends SequelizeModel<ActorImageModel> {return remove(imagePath)}- isOwned () {+ isLocal () {return !this.fileUrl}diff --git a/server/core/models/actor/actor.ts b/server/core/models/actor/actor.tsindex 371a2c57d8..8726c52613 100644--- a/server/core/models/actor/actor.ts+++ b/server/core/models/actor/actor.ts@@ -55,6 +55,13 @@ import { VideoModel } from '../video/video.js'import { ActorFollowModel } from './actor-follow.js'import { ActorImageModel } from './actor-image.js'+export const actorSummaryAttributes = [+ 'id',+ 'preferredUsername',+ 'url',+ 'serverId'+] as const satisfies (keyof AttributesOnly<ActorModel>)[]+enum ScopeNames {FULL = 'FULL'}@@ -330,6 +337,15 @@ export class ActorModel extends SequelizeModel<ActorModel> {})}+ static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: ActorModel,+ tableName,+ aliasPrefix,+ includeAttributes: actorSummaryAttributes+ })+ }+// ---------------------------------------------------------------------------// FIXME: have to specify the result type to not break peertube typings generation@@ -678,7 +694,7 @@ export class ActorModel extends SequelizeModel<ActorModel> {return this.url + '#main-key'}- isOwned () {+ isLocal () {return this.serverId === null}@@ -733,7 +749,7 @@ export class ActorModel extends SequelizeModel<ActorModel> {}isOutdated () {- if (this.isOwned()) return false+ if (this.isLocal()) return falsereturn isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL)}diff --git a/server/core/models/actor/sql/instance-list-followers-query-builder.ts b/server/core/models/actor/sql/instance-list-followers-query-builder.tsindex ce91bca0df..f116302436 100644--- a/server/core/models/actor/sql/instance-list-followers-query-builder.ts+++ b/server/core/models/actor/sql/instance-list-followers-query-builder.ts@@ -1,22 +1,16 @@-import { Sequelize } from 'sequelize'-import { ModelBuilder } from '@server/models/shared/index.js'-import { MActorFollowActorsDefault } from '@server/types/models/index.js'import { ActivityPubActorType, FollowState } from '@peertube/peertube-models'-import { parseRowCountResult } from '../../shared/index.js'+import { AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { Sequelize } from 'sequelize'import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder.js'-export interface ListFollowersOptions {+export interface ListFollowersOptions extends AbstractListQueryOptions {actorIds: number[]- start: number- count: number- sort: stringstate?: FollowStateactorType?: ActivityPubActorTypesearch?: string}-export class InstanceListFollowersQueryBuilder extends InstanceListFollowsQueryBuilder <ListFollowersOptions> {-+export class InstanceListFollowersQueryBuilder extends InstanceListFollowsQueryBuilder<ListFollowersOptions> {constructor (protected readonly sequelize: Sequelize,protected readonly options: ListFollowersOptions@@ -24,46 +18,29 @@ export class InstanceListFollowersQueryBuilder extends InstanceListFollowsQueryBsuper(sequelize, options)}- async listFollowers () {- this.buildListQuery()-- const results = await this.runQuery({ nest: true })- const modelBuilder = new ModelBuilder<MActorFollowActorsDefault>(this.sequelize)-- return modelBuilder.createModels(results, 'ActorFollow')- }+ protected buildSubQueryWhere () {+ this.buildActorFollowingJoin()- async countFollowers () {- this.buildCountQuery()-- const result = await this.runQuery()-- return parseRowCountResult(result)- }-- protected getWhere () {- let where = 'WHERE "ActorFollowing"."id" IN (:actorIds) '+ this.subQueryWhere = 'WHERE "ActorFollowing"."id" IN (:actorIds) 'this.replacements.actorIds = this.options.actorIdsif (this.options.state) {- where += 'AND "ActorFollowModel"."state" = :state '+ this.subQueryWhere += 'AND "ActorFollowModel"."state" = :state 'this.replacements.state = this.options.state}if (this.options.search) {const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')- where += `AND (` ++ this.subQueryWhere += `AND (` +`"ActorFollower->Server"."host" ILIKE ${escapedLikeSearch} ` +`OR "ActorFollower"."preferredUsername" ILIKE ${escapedLikeSearch} ` +- `)`+ `)`}if (this.options.actorType) {- where += `AND "ActorFollower"."type" = :actorType `+ this.subQueryWhere += `AND "ActorFollower"."type" = :actorType `this.replacements.actorType = this.options.actorType}-- return where}}diff --git a/server/core/models/actor/sql/instance-list-following-query-builder.ts b/server/core/models/actor/sql/instance-list-following-query-builder.tsindex dab70db43c..f49d65f24d 100644--- a/server/core/models/actor/sql/instance-list-following-query-builder.ts+++ b/server/core/models/actor/sql/instance-list-following-query-builder.ts@@ -1,22 +1,16 @@-import { Sequelize } from 'sequelize'-import { ModelBuilder } from '@server/models/shared/index.js'-import { MActorFollowActorsDefault } from '@server/types/models/index.js'import { ActivityPubActorType, FollowState } from '@peertube/peertube-models'-import { parseRowCountResult } from '../../shared/index.js'+import { AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { Sequelize } from 'sequelize'import { InstanceListFollowsQueryBuilder } from './shared/instance-list-follows-query-builder.js'-export interface ListFollowingOptions {+export interface ListFollowingOptions extends AbstractListQueryOptions {followerId: number- start: number- count: number- sort: stringstate?: FollowStateactorType?: ActivityPubActorTypesearch?: string}-export class InstanceListFollowingQueryBuilder extends InstanceListFollowsQueryBuilder <ListFollowingOptions> {-+export class InstanceListFollowingQueryBuilder extends InstanceListFollowsQueryBuilder<ListFollowingOptions> {constructor (protected readonly sequelize: Sequelize,protected readonly options: ListFollowingOptions@@ -24,46 +18,29 @@ export class InstanceListFollowingQueryBuilder extends InstanceListFollowsQueryBsuper(sequelize, options)}- async listFollowing () {- this.buildListQuery()-- const results = await this.runQuery({ nest: true })- const modelBuilder = new ModelBuilder<MActorFollowActorsDefault>(this.sequelize)-- return modelBuilder.createModels(results, 'ActorFollow')- }+ protected buildSubQueryWhere () {+ this.buildActorFollowingJoin()- async countFollowing () {- this.buildCountQuery()-- const result = await this.runQuery()-- return parseRowCountResult(result)- }-- protected getWhere () {- let where = 'WHERE "ActorFollowModel"."actorId" = :followerId '+ this.subQueryWhere = 'WHERE "ActorFollowModel"."actorId" = :followerId 'this.replacements.followerId = this.options.followerIdif (this.options.state) {- where += 'AND "ActorFollowModel"."state" = :state '+ this.subQueryWhere += 'AND "ActorFollowModel"."state" = :state 'this.replacements.state = this.options.state}if (this.options.search) {const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')- where += `AND (` ++ this.subQueryWhere += `AND (` +`"ActorFollowing->Server"."host" ILIKE ${escapedLikeSearch} ` +`OR "ActorFollowing"."preferredUsername" ILIKE ${escapedLikeSearch} ` +- `)`+ `)`}if (this.options.actorType) {- where += `AND "ActorFollowing"."type" = :actorType `+ this.subQueryWhere += `AND "ActorFollowing"."type" = :actorType `this.replacements.actorType = this.options.actorType}-- return where}}diff --git a/server/core/models/actor/sql/shared/actor-follow-table-attributes.ts b/server/core/models/actor/sql/shared/actor-follow-table-attributes.tsindex 409c2f0e2a..ac1f20cc11 100644--- a/server/core/models/actor/sql/shared/actor-follow-table-attributes.ts+++ b/server/core/models/actor/sql/shared/actor-follow-table-attributes.ts@@ -5,7 +5,6 @@ import { ActorFollowModel } from '../../actor-follow.js'import { ActorImageModel } from '../../actor-image.js'export class ActorFollowTableAttributes {-@Memoize()getFollowAttributes () {return ActorFollowModel.getSQLAttributes('ActorFollowModel').join(', ')@@ -13,7 +12,7 @@ export class ActorFollowTableAttributes {@Memoize()getActorAttributes (actorTableName: string) {- return ActorModel.getSQLAttributes(actorTableName, `${actorTableName}.`).join(', ')+ return ActorModel.getSQLAPIAttributes(actorTableName, `${actorTableName}.`).join(', ')}@Memoize()diff --git a/server/core/models/actor/sql/shared/instance-list-follows-query-builder.ts b/server/core/models/actor/sql/shared/instance-list-follows-query-builder.tsindex e0569e2f8e..2c87853c85 100644--- a/server/core/models/actor/sql/shared/instance-list-follows-query-builder.ts+++ b/server/core/models/actor/sql/shared/instance-list-follows-query-builder.ts@@ -1,97 +1,75 @@-import { Sequelize } from 'sequelize'-import { AbstractRunQuery } from '@server/models/shared/index.js'import { ActorImageType } from '@peertube/peertube-models'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { Sequelize } from 'sequelize'import { getInstanceFollowsSort } from '../../../shared/index.js'import { ActorFollowTableAttributes } from './actor-follow-table-attributes.js'-type BaseOptions = {- sort: string- count: number- start: number-}--export abstract class InstanceListFollowsQueryBuilder <T extends BaseOptions> extends AbstractRunQuery {+export abstract class InstanceListFollowsQueryBuilder<T extends AbstractListQueryOptions> extends AbstractListQuery {protected readonly tableAttributes = new ActorFollowTableAttributes()- protected innerQuery: string+ private builtActorFollowingJoin = falseconstructor (protected readonly sequelize: Sequelize,protected readonly options: T) {- super(sequelize)+ super(sequelize, { modelName: 'ActorFollowModel', tableName: 'actorFollow' }, options)}- protected abstract getWhere (): string-- protected getJoins () {- return 'INNER JOIN "actor" "ActorFollower" ON "ActorFollower"."id" = "ActorFollowModel"."actorId" ' +- 'INNER JOIN "actor" "ActorFollowing" ON "ActorFollowing"."id" = "ActorFollowModel"."targetActorId" '+ protected buildQueryJoin () {+ this.join = this.join += this.getAvatarsJoin('ActorFollower')+ this.join += this.getAvatarsJoin('ActorFollowing')}- protected getServerJoin (actorName: string) {- return `LEFT JOIN "server" "${actorName}->Server" ON "${actorName}"."serverId" = "${actorName}->Server"."id" `- }+ protected buildQueryAttributes () {+ this.attributes = [+ ...this.attributes,- protected getAvatarsJoin (actorName: string) {- return `LEFT JOIN "actorImage" "${actorName}->Avatars" ON "${actorName}.id" = "${actorName}->Avatars"."actorId" ` +- `AND "${actorName}->Avatars"."type" = ${ActorImageType.AVATAR}`+ this.tableAttributes.getAvatarAttributes('ActorFollower'),+ this.tableAttributes.getAvatarAttributes('ActorFollowing')+ ]}- private buildInnerQuery () {- this.innerQuery = `${this.getInnerSelect()} ` +- `FROM "actorFollow" AS "ActorFollowModel" ` +- `${this.getJoins()} ` +- `${this.getServerJoin('ActorFollowing')} ` +- `${this.getServerJoin('ActorFollower')} ` +- `${this.getWhere()} ` +- `${this.getOrder()} ` +- `LIMIT :limit OFFSET :offset `-- this.replacements.limit = this.options.count- this.replacements.offset = this.options.start+ protected buildSubQueryJoin () {+ this.buildActorFollowingJoin()}- protected buildListQuery () {- this.buildInnerQuery()+ protected buildSubQueryAttributes () {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,- this.query = `${this.getSelect()} ` +- `FROM (${this.innerQuery}) AS "ActorFollowModel" ` +- `${this.getAvatarsJoin('ActorFollower')} ` +- `${this.getAvatarsJoin('ActorFollowing')} ` +- `${this.getOrder()}`- }-- protected buildCountQuery () {- this.query = `SELECT COUNT(*) AS "total" ` +- `FROM "actorFollow" AS "ActorFollowModel" ` +- `${this.getJoins()} ` +- `${this.getServerJoin('ActorFollowing')} ` +- `${this.getServerJoin('ActorFollower')} ` +- `${this.getWhere()}`- }-- private getInnerSelect () {- return this.buildSelect([this.tableAttributes.getFollowAttributes(),this.tableAttributes.getActorAttributes('ActorFollower'),this.tableAttributes.getActorAttributes('ActorFollowing'),this.tableAttributes.getServerAttributes('ActorFollower'),this.tableAttributes.getServerAttributes('ActorFollowing')- ])+ ]}- private getSelect () {- return this.buildSelect([- '"ActorFollowModel".*',- this.tableAttributes.getAvatarAttributes('ActorFollower'),- this.tableAttributes.getAvatarAttributes('ActorFollowing')- ])+ protected getSort (sort: string) {+ return getInstanceFollowsSort(sort)}- private getOrder () {- const orders = getInstanceFollowsSort(this.options.sort)+ protected buildActorFollowingJoin () {+ if (this.builtActorFollowingJoin) return- return 'ORDER BY ' + orders.map(o => `"${o[0]}" ${o[1]}`).join(', ')+ this.subQueryJoin += 'INNER JOIN "actor" "ActorFollower" ON "ActorFollower"."id" = "ActorFollowModel"."actorId" ' ++ 'INNER JOIN "actor" "ActorFollowing" ON "ActorFollowing"."id" = "ActorFollowModel"."targetActorId" '++ this.subQueryJoin += this.getServerJoin('ActorFollowing')+ this.subQueryJoin += this.getServerJoin('ActorFollower')++ this.builtActorFollowingJoin = true+ }++ // ---------------------------------------------------------------------------++ private getServerJoin (actorName: string) {+ return `LEFT JOIN "server" "${actorName}->Server" ON "${actorName}"."serverId" = "${actorName}->Server"."id" `+ }++ private getAvatarsJoin (actorName: string) {+ return `LEFT JOIN "actorImage" "${actorName}->Avatars" ON "${actorName}.id" = "${actorName}->Avatars"."actorId" ` ++ `AND "${actorName}->Avatars"."type" = ${ActorImageType.AVATAR} `}}diff --git a/server/core/models/application/upload-image.ts b/server/core/models/application/upload-image.tsindex 9db64fd236..241eeb8a9c 100644--- a/server/core/models/application/upload-image.ts+++ b/server/core/models/application/upload-image.ts@@ -121,7 +121,7 @@ export class UploadImageModel extends SequelizeModel<UploadImageModel> {return remove(this.getPath())}- isOwned () {+ isLocal () {return !this.fileUrl}}diff --git a/server/core/models/redundancy/video-redundancy.ts b/server/core/models/redundancy/video-redundancy.tsindex 6c8b0787d4..c62072c7ca 100644--- a/server/core/models/redundancy/video-redundancy.ts+++ b/server/core/models/redundancy/video-redundancy.ts@@ -126,7 +126,7 @@ export class VideoRedundancyModel extends SequelizeModel<VideoRedundancyModel> {@BeforeDestroystatic async removeFile (instance: VideoRedundancyModel) {- if (!instance.isOwned()) return+ if (!instance.isLocal()) returnconst videoStreamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(instance.videoStreamingPlaylistId)@@ -578,7 +578,7 @@ export class VideoRedundancyModel extends SequelizeModel<VideoRedundancyModel> {return this.getVideo()?.uuid}- isOwned () {+ isLocal () {return !!this.strategy}diff --git a/server/core/models/server/server.ts b/server/core/models/server/server.tsindex 4538f17056..fc2acf7e0b 100644--- a/server/core/models/server/server.ts+++ b/server/core/models/server/server.ts@@ -5,6 +5,9 @@ import { isHostValid } from '../../helpers/custom-validators/servers.js'import { ActorModel } from '../actor/actor.js'import { SequelizeModel, buildSQLAttributes, throwIfNotValid } from '../shared/index.js'import { ServerBlocklistModel } from './server-blocklist.js'+import { AttributesOnly } from '@peertube/peertube-typescript-utils'++export const serverSummaryAttributes = [ 'id', 'host' ] as const satisfies (keyof AttributesOnly<ServerModel>)[]@Table({tableName: 'server',@@ -60,6 +63,15 @@ export class ServerModel extends SequelizeModel<ServerModel> {})}+ static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix,+ includeAttributes: serverSummaryAttributes+ })+ }+// ---------------------------------------------------------------------------static load (id: number, transaction?: Transaction): Promise<MServer> {diff --git a/server/core/models/shared/abstract-list-query.ts b/server/core/models/shared/abstract-list-query.tsnew file mode 100644index 0000000000..2de91065b4--- /dev/null+++ b/server/core/models/shared/abstract-list-query.ts@@ -0,0 +1,124 @@+import { AbstractRunQuery, ModelBuilder, parseRowCountResult } from '@server/models/shared/index.js'+import { Model, Sequelize, Transaction } from 'sequelize'++export interface AbstractListQueryOptions {+ start?: number+ count?: number+ sort?: string+ transaction?: Transaction+}++export interface ModelInfo {+ tableName: string+ modelName: string+}++export abstract class AbstractListQuery extends AbstractRunQuery {+ protected attributes: string[] = []+ protected join = ''++ private subQuery: string++ protected subQueryAttributes: string[] = []+ protected subQueryLateralJoin = ''+ protected subQueryJoin = ''+ protected subQueryWhere = ''++ protected abstract buildQueryAttributes (): void+ protected abstract buildQueryJoin (): void++ protected abstract buildSubQueryWhere (): void+ protected abstract buildSubQueryAttributes (): void+ protected abstract buildSubQueryJoin (): void++ protected buildSubQueryLateralJoin () {+ // Optional+ }++ protected getCalculatedAttributes () {+ return []+ }++ constructor (+ protected readonly sequelize: Sequelize,+ protected readonly modelInfo: ModelInfo,+ protected readonly options: AbstractListQueryOptions+ ) {+ super(sequelize)+ }++ async get<T extends Model> () {+ this.options.start = 0+ this.options.count = 1++ const rows = await this.list<T>()++ return rows.length === 1+ ? rows[0]+ : null+ }++ async list<T extends Model> () {+ this.buildListQuery()++ const results = await this.runQuery({ nest: true, transaction: this.options.transaction })+ const modelBuilder = new ModelBuilder<T>(this.sequelize)++ return modelBuilder.createModels(results, this.modelInfo.modelName.replace(/Model$/, ''))+ }++ async count () {+ this.buildCountQuery()++ const result = await this.runQuery({ transaction: this.options.transaction })++ return parseRowCountResult(result)+ }++ // ---------------------------------------------------------------------------++ private buildListQuery () {+ this.buildSubQuery()++ this.attributes = [ `"${this.modelInfo.modelName}".*` ]+ this.buildQueryAttributes()+ this.buildQueryJoin()++ this.query = `${this.buildSelect(this.attributes)} ` ++ `FROM (${this.subQuery}) AS "${this.modelInfo.modelName}" ` ++ `${this.join} ` ++ `${this.getOrder(this.modelInfo.modelName, this.options.sort)}`+ }++ private buildSubQuery () {+ this.buildSubQueryWhere()+ this.buildSubQueryJoin()+ this.buildSubQueryLateralJoin()+ this.buildSubQueryAttributes()++ this.subQuery = `${this.buildSelect(this.subQueryAttributes)} ` ++ `FROM "${this.modelInfo.tableName}" AS "${this.modelInfo.modelName}" ` ++ `${this.subQueryJoin} ` ++ `${this.subQueryLateralJoin} ` ++ `${this.subQueryWhere} `++ if (this.options.sort) {+ this.subQuery += `${this.getOrder(this.modelInfo.modelName, this.options.sort, this.getCalculatedAttributes())} `+ }++ if (this.options.start !== undefined && this.options.count !== undefined) {+ this.subQuery += this.getLimit(this.options.start, this.options.count)+ }+ }++ // ---------------------------------------------------------------------------++ private buildCountQuery () {+ this.buildSubQueryWhere()++ this.query = `SELECT COUNT(*) AS "total" ` ++ `FROM "${this.modelInfo.tableName}" AS "${this.modelInfo.modelName}" ` ++ `${this.subQueryJoin} ` ++ `${this.subQueryWhere}`+ }+}diff --git a/server/core/models/shared/abstract-run-query.ts b/server/core/models/shared/abstract-run-query.tsindex e856cc5230..dc8b5c3fa8 100644--- a/server/core/models/shared/abstract-run-query.ts+++ b/server/core/models/shared/abstract-run-query.ts@@ -1,9 +1,9 @@import { QueryTypes, Sequelize, Transaction } from 'sequelize'+import { getSort } from './sort.js'+import { Col } from 'sequelize/lib/utils'/**- ** Abstract builder to run video SQL queries- **/export class AbstractRunQuery {@@ -13,7 +13,6 @@ export class AbstractRunQuery {protected queryConfig = ''constructor (protected readonly sequelize: Sequelize) {-}protected async runQuery (options: { nest?: boolean, transaction?: Transaction, logging?: boolean } = {}) {@@ -32,7 +31,48 @@ export class AbstractRunQuery {return this.sequelize.query<any>(this.query, queryOptions)}- protected buildSelect (entities: string[]) {- return `SELECT ${entities.join(', ')} `+ protected buildSelect (attributes: string[]) {+ return `SELECT ${attributes.join(', ')} `+ }++ // ---------------------------------------------------------------------------++ protected getOrder (tableName: string, sort: string, calculatedAttributes: string[] = []) {+ if (!sort) return ''++ const orders = this.getSort(sort)++ const orderStr = orders.map(o => {+ const columnName = o[0] instanceof Col+ ? o[0].col+ : o[0]++ const direction = o[1]++ // Prefix with the table name if the column name isn't a full path+ // ("id", "displayName", etc. VS "ActorModel.id", "Server.redundancyAllowed", etc.)+ const prefix = calculatedAttributes.includes(columnName) || columnName.includes('.')+ ? ''+ : `"${tableName}".`++ return `${prefix}"${columnName}" ${direction}`+ }).join(', ')++ return 'ORDER BY ' + orderStr+ }++ protected getSort (sort: string) {+ return getSort(sort)+ }++ // ---------------------------------------------------------------------------++ protected getLimit (start: number, count: number) {+ if (!count) return ''++ this.replacements.limit = count+ this.replacements.offset = start || 0++ return `LIMIT :limit OFFSET :offset `}}diff --git a/server/core/models/shared/delete.ts b/server/core/models/shared/delete.tsnew file mode 100644index 0000000000..88a858333b--- /dev/null+++ b/server/core/models/shared/delete.ts@@ -0,0 +1,9 @@+import { MAX_SQL_DELETE_ITEMS } from '@server/initializers/constants.js'++export async function safeBulkDestroy (destroyFn: () => Promise<number>) {+ const destroyedRows = await destroyFn()++ if (destroyedRows === MAX_SQL_DELETE_ITEMS) {+ return safeBulkDestroy(destroyFn)+ }+}diff --git a/server/core/models/shared/index.ts b/server/core/models/shared/index.tsindex 77e9373bb3..fa920f6297 100644--- a/server/core/models/shared/index.ts+++ b/server/core/models/shared/index.ts@@ -5,5 +5,7 @@ export * from './query.js'export * from './sequelize-helpers.js'export * from './sequelize-type.js'export * from './sort.js'-export * from './sql.js'+export * from './sql/common-helpers.js'export * from './update.js'+export * from './delete.js'+export * from './table.js'diff --git a/server/core/models/shared/model-builder.ts b/server/core/models/shared/model-builder.tsindex 26ccfa90fe..3ec81ac2f5 100644--- a/server/core/models/shared/model-builder.ts+++ b/server/core/models/shared/model-builder.ts@@ -3,7 +3,6 @@ import isPlainObject from 'lodash-es/isPlainObject.js'import { ModelStatic, Sequelize, Model as SequelizeModel } from 'sequelize'/**- ** Build Sequelize models from sequelize raw query (that must use { nest: true } options)** In order to sequelize to correctly build the JSON this class will ingest,@@ -19,11 +18,32 @@ import { ModelStatic, Sequelize, Model as SequelizeModel } from 'sequelize'* * All tables must contain the row id*/-export class ModelBuilder <T extends SequelizeModel> {+export class ModelBuilder<T extends SequelizeModel> {private readonly modelRegistry = new Map<string, T>()- constructor (private readonly sequelize: Sequelize) {+ private readonly aliasToTableName = {+ ChannelCollab: 'VideoChannelCollaborator',+ Collabs: 'VideoChannelCollaborators'+ }+ private readonly tableNameToModelName = {+ Avatars: 'ActorImageModel',+ Banners: 'ActorImageModel',+ ActorFollowing: 'ActorModel',+ ActorFollower: 'ActorModel',+ FlaggedAccount: 'AccountModel',+ CommentAutomaticTags: 'CommentAutomaticTagModel',+ OwnerAccount: 'AccountModel',+ Thumbnails: 'ThumbnailModel',+ Channel: 'VideoChannelModel',+ VideoChannels: 'VideoChannelModel',+ VideoPlaylists: 'VideoPlaylistModel',+ NotificationSetting: 'UserNotificationSettingModel',+ VideoChannelCollaborators: 'VideoChannelCollaboratorModel',+ Tags: 'TagModel'+ }++ constructor (private readonly sequelize: Sequelize) {}createModels (jsonArray: any[], baseModelName: string): T[] {@@ -38,34 +58,41 @@ export class ModelBuilder <T extends SequelizeModel> {return result}- private createModel (json: any, modelName: string, keyPath: string) {+ private createModel (json: any, rootTableName: string, keyPath: string) {if (!json.id) return { created: false, model: null }- const { created, model } = this.createOrFindModel(json, modelName, keyPath)+ const { created, model } = this.createOrFindModel(json, rootTableName, keyPath)for (const key of Object.keys(json)) {const value = json[key]if (!value) continue+ const tableName = this.buildTableName(key)+// Child modelif (isPlainObject(value)) {- const { created, model: subModel } = this.createModel(value, key, `${keyPath}.${json.id}.${key}`)- if (!created || !subModel) continue-- const Model = this.findModelBuilder(modelName)- const association = Model.associations[key]+ const Model = this.findModelBuilder(rootTableName)+ const association = Model.associations[tableName]if (!association) {- logger.error('Cannot find association %s of model %s', key, modelName, { associations: Object.keys(Model.associations) })+ logger.error(`Cannot find association ${tableName} from key ${key} of model ${rootTableName}`, {+ associations: Object.keys(Model.associations)+ })continue}- if (association.isMultiAssociation) {- if (!Array.isArray(model[key])) model[key] = []+ const { created, model: subModel } = this.createModel(value, tableName, `${keyPath}.${json.id}.${key}`)- model[key].push(subModel)+ if (association.isMultiAssociation && !Array.isArray(model[tableName])) {+ model[tableName] = []+ }++ if (!created || !subModel) continue++ if (Array.isArray(model[tableName])) {+ model[tableName].push(subModel)} else {- model[key] = subModel+ model[tableName] = subModel}}}@@ -73,7 +100,7 @@ export class ModelBuilder <T extends SequelizeModel> {return { created, model }}- private createOrFindModel (json: any, modelName: string, keyPath: string) {+ private createOrFindModel (json: any, tableName: string, keyPath: string) {const registryKey = this.getModelRegistryKey(json, keyPath)if (this.modelRegistry.has(registryKey)) {return {@@ -82,11 +109,15 @@ export class ModelBuilder <T extends SequelizeModel> {}}- const Model = this.findModelBuilder(modelName)+ const Model = this.findModelBuilder(tableName)+ if (!Model) {+ throw new Error(`Cannot find model builder for ${tableName}. You may have to add an alias in ModelBuilder class`)+ }if (!Model) {logger.error(- 'Cannot build model %s that does not exist', this.buildSequelizeModelName(modelName),+ 'Cannot build model %s that does not exist',+ this.buildSequelizeModelName(tableName),{ existing: this.sequelize.modelManager.all.map(m => m.name) })return { created: false, model: null }@@ -99,18 +130,18 @@ export class ModelBuilder <T extends SequelizeModel> {return { created: true, model }}- private findModelBuilder (modelName: string) {- return this.sequelize.modelManager.getModel(this.buildSequelizeModelName(modelName)) as ModelStatic<T>+ private findModelBuilder (tableName: string) {+ return this.sequelize.modelManager.getModel(this.buildSequelizeModelName(tableName)) as ModelStatic<T>}- private buildSequelizeModelName (modelName: string) {- if (modelName === 'Avatars') return 'ActorImageModel'- if (modelName === 'ActorFollowing') return 'ActorModel'- if (modelName === 'ActorFollower') return 'ActorModel'- if (modelName === 'FlaggedAccount') return 'AccountModel'- if (modelName === 'CommentAutomaticTags') return 'CommentAutomaticTagModel'+ private buildSequelizeModelName (tableNameArg: string) {+ const tableName = this.buildTableName(tableNameArg)++ return this.tableNameToModelName[tableName] ?? tableName + 'Model'+ }- return modelName + 'Model'+ private buildTableName (tableName: string) {+ return this.aliasToTableName[tableName] ?? tableName}private getModelRegistryKey (json: any, keyPath: string) {diff --git a/server/core/models/shared/query.ts b/server/core/models/shared/query.tsindex 60dd92b27d..48890a6c19 100644--- a/server/core/models/shared/query.ts+++ b/server/core/models/shared/query.ts@@ -27,9 +27,7 @@ async function doesExist (options: {function createSimilarityAttribute (col: string, value: string): Fn {return Sequelize.fn('similarity',-searchTrigramNormalizeCol(col),-searchTrigramNormalizeValue(value))}@@ -47,7 +45,7 @@ function parseAggregateResult (result: any) {return total}-function parseRowCountResult (result: any) {+function parseRowCountResult (result: any): number {if (result.length !== 0) return result[0].totalreturn 0@@ -73,8 +71,13 @@ function searchAttribute (sourceField?: string, targetField?: string) {}export {- buildWhereIdOrUUID, createSafeIn, createSimilarityAttribute, doesExist, parseAggregateResult,- parseRowCountResult, searchAttribute+ buildWhereIdOrUUID,+ createSafeIn,+ createSimilarityAttribute,+ doesExist,+ parseAggregateResult,+ parseRowCountResult,+ searchAttribute}// ---------------------------------------------------------------------------diff --git a/server/core/models/shared/sql/actor-helpers.ts b/server/core/models/shared/sql/actor-helpers.tsnew file mode 100644index 0000000000..a26642cafb--- /dev/null+++ b/server/core/models/shared/sql/actor-helpers.ts@@ -0,0 +1,57 @@+import { ActorImageType } from '@peertube/peertube-models'++export function getActorJoin (options: {+ base?: string+ on: string+ includeAvatars?: boolean // default false+}) {+ const { base = '', on, includeAvatars = false } = options++ const avatarsJoin = includeAvatars+ ? getAvatarsJoin({ base: `${base}Actor`, on: `"${base}Actor"."id"` })+ : ''++ return ` LEFT JOIN "actor" "${base}Actor" ON "${base}Actor"."id" = ${on} ` ++ `LEFT JOIN "server" "${base}Actor->Server" ` ++ ` ON "${base}Actor->Server"."id" = "${base}Actor"."serverId" ` ++ avatarsJoin+}++export function getChannelJoin (options: {+ base?: string+ on: string+ includeAccount?: boolean // default false+ includeAvatars?: boolean // default false+}) {+ const { base = '', on, includeAccount = false, includeAvatars = false } = options++ const accountJoin = includeAccount+ ? getAccountJoin({ base: `${base}VideoChannel->`, on: `"${base}VideoChannel"."accountId"`, includeAvatars })+ : ''++ return ` LEFT JOIN "videoChannel" "${base}VideoChannel" ON "${base}VideoChannel"."id" = ${on} ` ++ getActorJoin({ base: `${base}VideoChannel->`, on: `"${base}VideoChannel"."actorId"`, includeAvatars }) ++ accountJoin+}++export function getAccountJoin (options: {+ base?: string+ on: string+ includeAvatars?: boolean // default false+}) {+ const { base = '', on, includeAvatars = false } = options++ return `LEFT JOIN "account" "${base}Account" ON "${base}Account"."id" = ${on} ` ++ getActorJoin({ base: `${base}Account->`, on: `"${base}Account"."actorId"`, includeAvatars })+}++export function getAvatarsJoin (options: {+ base?: string+ on: string+}) {+ const { base = '', on } = options++ return `LEFT JOIN "actorImage" "${base}Avatars" ` ++ `ON "${base}Avatars"."actorId" = ${on} ` ++ `AND "${base}Avatars"."type" = ${ActorImageType.AVATAR} `+}diff --git a/server/core/models/shared/sql.ts b/server/core/models/shared/sql/common-helpers.tssimilarity index 55%rename from server/core/models/shared/sql.tsrename to server/core/models/shared/sql/common-helpers.tsindex 98b8641a3e..8b3ce52e65 100644--- a/server/core/models/shared/sql.ts+++ b/server/core/models/shared/sql/common-helpers.ts@@ -1,8 +1,6 @@import { forceNumber } from '@peertube/peertube-core-utils'import { FollowState } from '@peertube/peertube-models'-import { AttributesOnly } from '@peertube/peertube-typescript-utils'-import { MAX_SQL_DELETE_ITEMS } from '@server/initializers/constants.js'-import { literal, Model, ModelStatic } from 'sequelize'+import { literal } from 'sequelize'import { Literal } from 'sequelize/types/utils'// FIXME: have to specify the result type to not break peertube typings generation@@ -39,45 +37,3 @@ export function buildServerIdsFollowedBy (actorId: any) {`WHERE "actorFollow"."actorId" = ${actorIdNumber} AND "actorFollow"."state" = '${followState}'` +')'}--export function buildSQLAttributes<M extends Model> (options: {- model: ModelStatic<M>- tableName: string-- excludeAttributes?: Exclude<keyof AttributesOnly<M>, symbol>[]- aliasPrefix?: string-- idBuilder?: string[]-}) {- const { model, tableName, aliasPrefix = '', excludeAttributes, idBuilder } = options-- const attributes = Object.keys(model.getAttributes()) as Exclude<keyof AttributesOnly<M>, symbol>[]-- const builtAttributes = attributes- .filter(a => {- if (!excludeAttributes) return true- if (excludeAttributes.includes(a)) return false-- return true- })- .map(a => {- return `"${tableName}"."${a}" AS "${aliasPrefix}${a}"`- })-- if (idBuilder) {- const idSelect = idBuilder.map(a => `"${tableName}"."${a}"`)- .join(` || '-' || `)-- builtAttributes.push(`${idSelect} AS "${aliasPrefix}id"`)- }-- return builtAttributes-}--export async function safeBulkDestroy (destroyFn: () => Promise<number>) {- const destroyedRows = await destroyFn()-- if (destroyedRows === MAX_SQL_DELETE_ITEMS) {- return safeBulkDestroy(destroyFn)- }-}diff --git a/server/core/models/shared/table.ts b/server/core/models/shared/table.tsnew file mode 100644index 0000000000..63b3ffb623--- /dev/null+++ b/server/core/models/shared/table.ts@@ -0,0 +1,44 @@+import { AttributesOnly } from '@peertube/peertube-typescript-utils'+import { Model, ModelStatic } from 'sequelize'++export function buildSQLAttributes<M extends Model> (options: {+ model: ModelStatic<M>+ tableName: string++ excludeAttributes?: readonly Exclude<keyof AttributesOnly<M>, symbol>[]+ includeAttributes?: readonly Exclude<keyof AttributesOnly<M>, symbol>[]++ aliasPrefix?: string++ idBuilder?: string[]+}) {+ const { model, tableName, aliasPrefix = '', excludeAttributes, includeAttributes, idBuilder } = options++ const attributes = Object.keys(model.getAttributes()) as Exclude<keyof AttributesOnly<M>, symbol>[]++ const builtAttributes = attributes+ .filter(a => {+ if (!excludeAttributes) return true+ if (excludeAttributes.includes(a)) return false++ return true+ })+ .filter(a => {+ if (!includeAttributes) return true+ if (includeAttributes.includes(a)) return true++ return false+ })+ .map(a => {+ return `"${tableName}"."${a}" AS "${aliasPrefix}${a}"`+ })++ if (idBuilder) {+ const idSelect = idBuilder.map(a => `"${tableName}"."${a}"`)+ .join(` || '-' || `)++ builtAttributes.push(`${idSelect} AS "${aliasPrefix}id"`)+ }++ return builtAttributes+}diff --git a/server/core/models/shared/update.ts b/server/core/models/shared/update.tsindex 96db437309..b5c075aac2 100644--- a/server/core/models/shared/update.ts+++ b/server/core/models/shared/update.ts@@ -3,7 +3,7 @@ import { QueryTypes, Sequelize, Transaction } from 'sequelize'const updating = new Set<string>()// Sequelize always skip the update if we only update updatedAt field-async function setAsUpdated (options: {+export async function setAsUpdated (options: {sequelize: Sequelizetable: stringid: number@@ -28,7 +28,3 @@ async function setAsUpdated (options: {updating.delete(key)}}--export {- setAsUpdated-}diff --git a/server/core/models/user/sql/user-notification-list-query-builder.ts b/server/core/models/user/sql/user-notification-list-query-builder.tsdeleted file mode 100644index 5f67b18543..0000000000--- a/server/core/models/user/sql/user-notification-list-query-builder.ts+++ /dev/null@@ -1,298 +0,0 @@-import { ActorImageType, UserNotificationType_Type } from '@peertube/peertube-models'-import { AbstractRunQuery, ModelBuilder } from '@server/models/shared/index.js'-import { UserNotificationModelForApi } from '@server/types/models/index.js'-import { Sequelize } from 'sequelize'-import { getSort } from '../../shared/index.js'--export interface ListNotificationsOptions {- userId: number- unread?: boolean- typeOneOf?: UserNotificationType_Type[]-- sort: string- offset: number- limit: number-}--export class UserNotificationListQueryBuilder extends AbstractRunQuery {- private innerQuery: string-- constructor (- protected readonly sequelize: Sequelize,- private readonly options: ListNotificationsOptions- ) {- super(sequelize)- }-- async listNotifications () {- this.buildQuery()-- const results = await this.runQuery({ nest: true })- const modelBuilder = new ModelBuilder<UserNotificationModelForApi>(this.sequelize)-- return modelBuilder.createModels(results, 'UserNotification')- }-- private buildInnerQuery () {- this.innerQuery = `SELECT * FROM "userNotification" AS "UserNotificationModel" ` +- `${this.getWhere()} ` +- `${this.getOrder()} ` +- `LIMIT :limit OFFSET :offset `-- this.replacements.limit = this.options.limit- this.replacements.offset = this.options.offset- }-- private buildQuery () {- this.buildInnerQuery()-- this.query = `- ${this.getSelect()}- FROM (${this.innerQuery}) "UserNotificationModel"- ${this.getJoins()}- ${this.getOrder()}`- }-- private getWhere () {- let base = '"UserNotificationModel"."userId" = :userId '- this.replacements.userId = this.options.userId-- if (this.options.unread === true) {- base += 'AND "UserNotificationModel"."read" IS FALSE '- } else if (this.options.unread === false) {- base += 'AND "UserNotificationModel"."read" IS TRUE '- }-- if (this.options.typeOneOf) {- base += 'AND "UserNotificationModel"."type" IN (:typeOneOf) '- this.replacements.typeOneOf = this.options.typeOneOf- }-- return `WHERE ${base}`- }-- private getOrder () {- const orders = getSort(this.options.sort)-- return 'ORDER BY ' + orders.map(o => `"UserNotificationModel"."${o[0]}" ${o[1]}`).join(', ')- }-- private getSelect () {- return `SELECT- "UserNotificationModel"."id",- "UserNotificationModel"."type",- "UserNotificationModel"."read",- "UserNotificationModel"."createdAt",- "UserNotificationModel"."updatedAt",- "Video"."id" AS "Video.id",- "Video"."uuid" AS "Video.uuid",- "Video"."name" AS "Video.name",- "Video"."state" AS "Video.state",- "Video->VideoChannel"."id" AS "Video.VideoChannel.id",- "Video->VideoChannel"."name" AS "Video.VideoChannel.name",- "Video->VideoChannel->Actor"."id" AS "Video.VideoChannel.Actor.id",- "Video->VideoChannel->Actor"."preferredUsername" AS "Video.VideoChannel.Actor.preferredUsername",- "Video->VideoChannel->Actor->Avatars"."id" AS "Video.VideoChannel.Actor.Avatars.id",- "Video->VideoChannel->Actor->Avatars"."width" AS "Video.VideoChannel.Actor.Avatars.width",- "Video->VideoChannel->Actor->Avatars"."type" AS "Video.VideoChannel.Actor.Avatars.type",- "Video->VideoChannel->Actor->Avatars"."filename" AS "Video.VideoChannel.Actor.Avatars.filename",- "Video->VideoChannel->Actor->Server"."id" AS "Video.VideoChannel.Actor.Server.id",- "Video->VideoChannel->Actor->Server"."host" AS "Video.VideoChannel.Actor.Server.host",- "VideoComment"."id" AS "VideoComment.id",- "VideoComment"."originCommentId" AS "VideoComment.originCommentId",- "VideoComment"."heldForReview" AS "VideoComment.heldForReview",- "VideoComment->Account"."id" AS "VideoComment.Account.id",- "VideoComment->Account"."name" AS "VideoComment.Account.name",- "VideoComment->Account->Actor"."id" AS "VideoComment.Account.Actor.id",- "VideoComment->Account->Actor"."preferredUsername" AS "VideoComment.Account.Actor.preferredUsername",- "VideoComment->Account->Actor->Avatars"."id" AS "VideoComment.Account.Actor.Avatars.id",- "VideoComment->Account->Actor->Avatars"."width" AS "VideoComment.Account.Actor.Avatars.width",- "VideoComment->Account->Actor->Avatars"."type" AS "VideoComment.Account.Actor.Avatars.type",- "VideoComment->Account->Actor->Avatars"."filename" AS "VideoComment.Account.Actor.Avatars.filename",- "VideoComment->Account->Actor->Server"."id" AS "VideoComment.Account.Actor.Server.id",- "VideoComment->Account->Actor->Server"."host" AS "VideoComment.Account.Actor.Server.host",- "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",- "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",- "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",- "Abuse->FlaggedAccount"."id" AS "Abuse.FlaggedAccount.id",- "Abuse->FlaggedAccount"."name" AS "Abuse.FlaggedAccount.name",- "Abuse->FlaggedAccount"."description" AS "Abuse.FlaggedAccount.description",- "Abuse->FlaggedAccount"."actorId" AS "Abuse.FlaggedAccount.actorId",- "Abuse->FlaggedAccount"."userId" AS "Abuse.FlaggedAccount.userId",- "Abuse->FlaggedAccount"."applicationId" AS "Abuse.FlaggedAccount.applicationId",- "Abuse->FlaggedAccount"."createdAt" AS "Abuse.FlaggedAccount.createdAt",- "Abuse->FlaggedAccount"."updatedAt" AS "Abuse.FlaggedAccount.updatedAt",- "Abuse->FlaggedAccount->Actor"."id" AS "Abuse.FlaggedAccount.Actor.id",- "Abuse->FlaggedAccount->Actor"."preferredUsername" AS "Abuse.FlaggedAccount.Actor.preferredUsername",- "Abuse->FlaggedAccount->Actor->Avatars"."id" AS "Abuse.FlaggedAccount.Actor.Avatars.id",- "Abuse->FlaggedAccount->Actor->Avatars"."width" AS "Abuse.FlaggedAccount.Actor.Avatars.width",- "Abuse->FlaggedAccount->Actor->Avatars"."type" AS "Abuse.FlaggedAccount.Actor.Avatars.type",- "Abuse->FlaggedAccount->Actor->Avatars"."filename" AS "Abuse.FlaggedAccount.Actor.Avatars.filename",- "Abuse->FlaggedAccount->Actor->Server"."id" AS "Abuse.FlaggedAccount.Actor.Server.id",- "Abuse->FlaggedAccount->Actor->Server"."host" AS "Abuse.FlaggedAccount.Actor.Server.host",- "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",- "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",- "Plugin"."id" AS "Plugin.id",- "Plugin"."name" AS "Plugin.name",- "Plugin"."type" AS "Plugin.type",- "Plugin"."latestVersion" AS "Plugin.latestVersion",- "Application"."id" AS "Application.id",- "Application"."latestPeerTubeVersion" AS "Application.latestPeerTubeVersion",- "ActorFollow"."id" AS "ActorFollow.id",- "ActorFollow"."state" AS "ActorFollow.state",- "ActorFollow->ActorFollower"."id" AS "ActorFollow.ActorFollower.id",- "ActorFollow->ActorFollower"."preferredUsername" AS "ActorFollow.ActorFollower.preferredUsername",- "ActorFollow->ActorFollower->Account"."id" AS "ActorFollow.ActorFollower.Account.id",- "ActorFollow->ActorFollower->Account"."name" AS "ActorFollow.ActorFollower.Account.name",- "ActorFollow->ActorFollower->Avatars"."id" AS "ActorFollow.ActorFollower.Avatars.id",- "ActorFollow->ActorFollower->Avatars"."width" AS "ActorFollow.ActorFollower.Avatars.width",- "ActorFollow->ActorFollower->Avatars"."type" AS "ActorFollow.ActorFollower.Avatars.type",- "ActorFollow->ActorFollower->Avatars"."filename" AS "ActorFollow.ActorFollower.Avatars.filename",- "ActorFollow->ActorFollower->Server"."id" AS "ActorFollow.ActorFollower.Server.id",- "ActorFollow->ActorFollower->Server"."host" AS "ActorFollow.ActorFollower.Server.host",- "ActorFollow->ActorFollowing"."id" AS "ActorFollow.ActorFollowing.id",- "ActorFollow->ActorFollowing"."preferredUsername" AS "ActorFollow.ActorFollowing.preferredUsername",- "ActorFollow->ActorFollowing"."type" AS "ActorFollow.ActorFollowing.type",- "ActorFollow->ActorFollowing->VideoChannel"."id" AS "ActorFollow.ActorFollowing.VideoChannel.id",- "ActorFollow->ActorFollowing->VideoChannel"."name" AS "ActorFollow.ActorFollowing.VideoChannel.name",- "ActorFollow->ActorFollowing->Account"."id" AS "ActorFollow.ActorFollowing.Account.id",- "ActorFollow->ActorFollowing->Account"."name" AS "ActorFollow.ActorFollowing.Account.name",- "ActorFollow->ActorFollowing->Server"."id" AS "ActorFollow.ActorFollowing.Server.id",- "ActorFollow->ActorFollowing->Server"."host" AS "ActorFollow.ActorFollowing.Server.host",- "Account"."id" AS "Account.id",- "Account"."name" AS "Account.name",- "Account->Actor"."id" AS "Account.Actor.id",- "Account->Actor"."preferredUsername" AS "Account.Actor.preferredUsername",- "Account->Actor->Avatars"."id" AS "Account.Actor.Avatars.id",- "Account->Actor->Avatars"."width" AS "Account.Actor.Avatars.width",- "Account->Actor->Avatars"."type" AS "Account.Actor.Avatars.type",- "Account->Actor->Avatars"."filename" AS "Account.Actor.Avatars.filename",- "Account->Actor->Server"."id" AS "Account.Actor.Server.id",- "Account->Actor->Server"."host" AS "Account.Actor.Server.host",- "UserRegistration"."id" AS "UserRegistration.id",- "UserRegistration"."username" AS "UserRegistration.username",- "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"`- }-- private getJoins () {- return `- LEFT JOIN (- "video" AS "Video"- INNER JOIN "videoChannel" AS "Video->VideoChannel" ON "Video"."channelId" = "Video->VideoChannel"."id"- INNER JOIN "actor" AS "Video->VideoChannel->Actor" ON "Video->VideoChannel"."actorId" = "Video->VideoChannel->Actor"."id"- LEFT JOIN "actorImage" AS "Video->VideoChannel->Actor->Avatars"- ON "Video->VideoChannel->Actor"."id" = "Video->VideoChannel->Actor->Avatars"."actorId"- AND "Video->VideoChannel->Actor->Avatars"."type" = ${ActorImageType.AVATAR}- LEFT JOIN "server" AS "Video->VideoChannel->Actor->Server"- ON "Video->VideoChannel->Actor"."serverId" = "Video->VideoChannel->Actor->Server"."id"- ) ON "UserNotificationModel"."videoId" = "Video"."id"-- LEFT JOIN (- "videoComment" AS "VideoComment"- INNER JOIN "account" AS "VideoComment->Account" ON "VideoComment"."accountId" = "VideoComment->Account"."id"- INNER JOIN "actor" AS "VideoComment->Account->Actor" ON "VideoComment->Account"."actorId" = "VideoComment->Account->Actor"."id"- LEFT JOIN "actorImage" AS "VideoComment->Account->Actor->Avatars"- ON "VideoComment->Account->Actor"."id" = "VideoComment->Account->Actor->Avatars"."actorId"- AND "VideoComment->Account->Actor->Avatars"."type" = ${ActorImageType.AVATAR}- LEFT JOIN "server" AS "VideoComment->Account->Actor->Server"- ON "VideoComment->Account->Actor"."serverId" = "VideoComment->Account->Actor->Server"."id"- INNER JOIN "video" AS "VideoComment->Video" ON "VideoComment"."videoId" = "VideoComment->Video"."id"- ) ON "UserNotificationModel"."commentId" = "VideoComment"."id"-- LEFT JOIN "abuse" AS "Abuse" ON "UserNotificationModel"."abuseId" = "Abuse"."id"- LEFT JOIN "videoAbuse" AS "Abuse->VideoAbuse" ON "Abuse"."id" = "Abuse->VideoAbuse"."abuseId"- LEFT JOIN "video" AS "Abuse->VideoAbuse->Video" ON "Abuse->VideoAbuse"."videoId" = "Abuse->VideoAbuse->Video"."id"- LEFT JOIN "commentAbuse" AS "Abuse->VideoCommentAbuse" ON "Abuse"."id" = "Abuse->VideoCommentAbuse"."abuseId"- LEFT JOIN "videoComment" AS "Abuse->VideoCommentAbuse->VideoComment"- ON "Abuse->VideoCommentAbuse"."videoCommentId" = "Abuse->VideoCommentAbuse->VideoComment"."id"- LEFT JOIN "video" AS "Abuse->VideoCommentAbuse->VideoComment->Video"- ON "Abuse->VideoCommentAbuse->VideoComment"."videoId" = "Abuse->VideoCommentAbuse->VideoComment->Video"."id"- LEFT JOIN (- "account" AS "Abuse->FlaggedAccount"- INNER JOIN "actor" AS "Abuse->FlaggedAccount->Actor" ON "Abuse->FlaggedAccount"."actorId" = "Abuse->FlaggedAccount->Actor"."id"- LEFT JOIN "actorImage" AS "Abuse->FlaggedAccount->Actor->Avatars"- ON "Abuse->FlaggedAccount->Actor"."id" = "Abuse->FlaggedAccount->Actor->Avatars"."actorId"- AND "Abuse->FlaggedAccount->Actor->Avatars"."type" = ${ActorImageType.AVATAR}- LEFT JOIN "server" AS "Abuse->FlaggedAccount->Actor->Server"- ON "Abuse->FlaggedAccount->Actor"."serverId" = "Abuse->FlaggedAccount->Actor->Server"."id"- ) ON "Abuse"."flaggedAccountId" = "Abuse->FlaggedAccount"."id"-- LEFT JOIN (- "videoBlacklist" AS "VideoBlacklist"- INNER JOIN "video" AS "VideoBlacklist->Video" ON "VideoBlacklist"."videoId" = "VideoBlacklist->Video"."id"- ) ON "UserNotificationModel"."videoBlacklistId" = "VideoBlacklist"."id"-- LEFT JOIN "videoImport" AS "VideoImport" ON "UserNotificationModel"."videoImportId" = "VideoImport"."id"- LEFT JOIN "video" AS "VideoImport->Video" ON "VideoImport"."videoId" = "VideoImport->Video"."id"-- LEFT JOIN "plugin" AS "Plugin" ON "UserNotificationModel"."pluginId" = "Plugin"."id"-- LEFT JOIN "application" AS "Application" ON "UserNotificationModel"."applicationId" = "Application"."id"-- LEFT JOIN (- "actorFollow" AS "ActorFollow"- INNER JOIN "actor" AS "ActorFollow->ActorFollower" ON "ActorFollow"."actorId" = "ActorFollow->ActorFollower"."id"- INNER JOIN "account" AS "ActorFollow->ActorFollower->Account"- ON "ActorFollow->ActorFollower"."id" = "ActorFollow->ActorFollower->Account"."actorId"- LEFT JOIN "actorImage" AS "ActorFollow->ActorFollower->Avatars"- ON "ActorFollow->ActorFollower"."id" = "ActorFollow->ActorFollower->Avatars"."actorId"- AND "ActorFollow->ActorFollower->Avatars"."type" = ${ActorImageType.AVATAR}- LEFT JOIN "server" AS "ActorFollow->ActorFollower->Server"- ON "ActorFollow->ActorFollower"."serverId" = "ActorFollow->ActorFollower->Server"."id"- INNER JOIN "actor" AS "ActorFollow->ActorFollowing" ON "ActorFollow"."targetActorId" = "ActorFollow->ActorFollowing"."id"- LEFT JOIN "videoChannel" AS "ActorFollow->ActorFollowing->VideoChannel"- ON "ActorFollow->ActorFollowing"."id" = "ActorFollow->ActorFollowing->VideoChannel"."actorId"- LEFT JOIN "account" AS "ActorFollow->ActorFollowing->Account"- ON "ActorFollow->ActorFollowing"."id" = "ActorFollow->ActorFollowing->Account"."actorId"- LEFT JOIN "server" AS "ActorFollow->ActorFollowing->Server"- ON "ActorFollow->ActorFollowing"."serverId" = "ActorFollow->ActorFollowing->Server"."id"- ) ON "UserNotificationModel"."actorFollowId" = "ActorFollow"."id"-- LEFT JOIN (- "account" AS "Account"- INNER JOIN "actor" AS "Account->Actor" ON "Account"."actorId" = "Account->Actor"."id"- LEFT JOIN "actorImage" AS "Account->Actor->Avatars"- ON "Account->Actor"."id" = "Account->Actor->Avatars"."actorId"- AND "Account->Actor->Avatars"."type" = ${ActorImageType.AVATAR}- LEFT JOIN "server" AS "Account->Actor->Server" ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"- ) ON "UserNotificationModel"."accountId" = "Account"."id"-- LEFT JOIN "userRegistration" as "UserRegistration" ON "UserNotificationModel"."userRegistrationId" = "UserRegistration"."id"-- LEFT JOIN (- "videoCaption" AS "VideoCaption"- INNER JOIN "video" AS "VideoCaption->Video" ON "VideoCaption"."videoId" = "VideoCaption->Video"."id"- ) ON "UserNotificationModel"."videoCaptionId" = "VideoCaption"."id"`- }-}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.tsnew file mode 100644index 0000000000..e2c0d1ce9f--- /dev/null+++ b/server/core/models/user/sql/user-notification/user-notification-list-query-builder.ts@@ -0,0 +1,271 @@+import { ActorImageType, UserNotificationType_Type } from '@peertube/peertube-models'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { Sequelize } from 'sequelize'++export interface ListNotificationsOptions extends AbstractListQueryOptions {+ userId: number+ unread?: boolean+ typeOneOf?: UserNotificationType_Type[]+}++export class UserNotificationListQueryBuilder extends AbstractListQuery {+ constructor (+ protected readonly sequelize: Sequelize,+ protected readonly options: ListNotificationsOptions+ ) {+ super(sequelize, { modelName: 'UserNotificationModel', tableName: 'userNotification' }, options)+ }++ protected buildSubQueryWhere () {+ this.subQueryWhere = 'WHERE "UserNotificationModel"."userId" = :userId '+ this.replacements.userId = this.options.userId++ if (this.options.unread === true) {+ this.subQueryWhere += 'AND "UserNotificationModel"."read" IS FALSE '+ } else if (this.options.unread === false) {+ this.subQueryWhere += 'AND "UserNotificationModel"."read" IS TRUE '+ }++ if (this.options.typeOneOf) {+ this.subQueryWhere += 'AND "UserNotificationModel"."type" IN (:typeOneOf) '+ this.replacements.typeOneOf = this.options.typeOneOf+ }+ }++ protected buildSubQueryJoin () {+ }++ protected buildSubQueryAttributes () {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,++ `*`+ ]+ }++ protected buildQueryAttributes () {+ this.attributes = [+ ...this.attributes,++ `"UserNotificationModel"."id"`,+ `"UserNotificationModel"."type"`,+ `"UserNotificationModel"."read"`,+ `"UserNotificationModel"."data"`,+ `"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.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.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"`,+ `"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.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"`,++ `"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"`,++ `"Plugin"."id" AS "Plugin.id"`,+ `"Plugin"."name" AS "Plugin.name"`,+ `"Plugin"."type" AS "Plugin.type"`,+ `"Plugin"."latestVersion" AS "Plugin.latestVersion"`,++ `"Application"."id" AS "Application.id"`,+ `"Application"."latestPeerTubeVersion" AS "Application.latestPeerTubeVersion"`,++ `"ActorFollow"."id" AS "ActorFollow.id"`,+ `"ActorFollow"."state" AS "ActorFollow.state"`,+ `"ActorFollow->ActorFollower"."id" AS "ActorFollow.ActorFollower.id"`,+ `"ActorFollow->ActorFollower"."preferredUsername" AS "ActorFollow.ActorFollower.preferredUsername"`,+ `"ActorFollow->ActorFollower->Account"."id" AS "ActorFollow.ActorFollower.Account.id"`,+ `"ActorFollow->ActorFollower->Account"."name" AS "ActorFollow.ActorFollower.Account.name"`,+ `"ActorFollow->ActorFollower->Avatars"."id" AS "ActorFollow.ActorFollower.Avatars.id"`,+ `"ActorFollow->ActorFollower->Avatars"."width" AS "ActorFollow.ActorFollower.Avatars.width"`,+ `"ActorFollow->ActorFollower->Avatars"."type" AS "ActorFollow.ActorFollower.Avatars.type"`,+ `"ActorFollow->ActorFollower->Avatars"."filename" AS "ActorFollow.ActorFollower.Avatars.filename"`,+ `"ActorFollow->ActorFollower->Server"."id" AS "ActorFollow.ActorFollower.Server.id"`,+ `"ActorFollow->ActorFollower->Server"."host" AS "ActorFollow.ActorFollower.Server.host"`,+ `"ActorFollow->ActorFollowing"."id" AS "ActorFollow.ActorFollowing.id"`,+ `"ActorFollow->ActorFollowing"."preferredUsername" AS "ActorFollow.ActorFollowing.preferredUsername"`,+ `"ActorFollow->ActorFollowing"."type" AS "ActorFollow.ActorFollowing.type"`,+ `"ActorFollow->ActorFollowing->VideoChannel"."id" AS "ActorFollow.ActorFollowing.VideoChannel.id"`,+ `"ActorFollow->ActorFollowing->VideoChannel"."name" AS "ActorFollow.ActorFollowing.VideoChannel.name"`,+ `"ActorFollow->ActorFollowing->Account"."id" AS "ActorFollow.ActorFollowing.Account.id"`,+ `"ActorFollow->ActorFollowing->Account"."name" AS "ActorFollow.ActorFollowing.Account.name"`,+ `"ActorFollow->ActorFollowing->Server"."id" AS "ActorFollow.ActorFollowing.Server.id"`,+ `"ActorFollow->ActorFollowing->Server"."host" AS "ActorFollow.ActorFollowing.Server.host"`,++ ...this.getAccountOrChannelAttributes('Account', 'Account'),++ `"UserRegistration"."id" AS "UserRegistration.id"`,+ `"UserRegistration"."username" AS "UserRegistration.username"`,++ `"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"`,++ `"ChannelCollab"."id" AS "ChannelCollab.id"`,+ `"ChannelCollab"."state" AS "ChannelCollab.state"`,+ ...this.getAccountOrChannelAttributes('ChannelCollab->Account', 'ChannelCollab.Account'),+ ...this.getAccountOrChannelAttributes('ChannelCollab->Channel->Account', 'ChannelCollab.Channel.Account'),+ ...this.getAccountOrChannelAttributes('ChannelCollab->Channel', 'ChannelCollab.Channel')+ ]+ }++ protected buildQueryJoin () {+ this.join = `+ LEFT JOIN (+ "video" AS "Video"+ ${this.getChannelJoin('Video', 'channelId')}+ ) ON "UserNotificationModel"."videoId" = "Video"."id"++ LEFT JOIN (+ "videoComment" AS "VideoComment"+ ${this.getAccountJoin('VideoComment', 'accountId')}+ INNER JOIN "video" AS "VideoComment->Video" ON "VideoComment"."videoId" = "VideoComment->Video"."id"+ ) ON "UserNotificationModel"."commentId" = "VideoComment"."id"++ LEFT JOIN "abuse" AS "Abuse" ON "UserNotificationModel"."abuseId" = "Abuse"."id"+ LEFT JOIN "videoAbuse" AS "Abuse->VideoAbuse" ON "Abuse"."id" = "Abuse->VideoAbuse"."abuseId"+ LEFT JOIN "video" AS "Abuse->VideoAbuse->Video" ON "Abuse->VideoAbuse"."videoId" = "Abuse->VideoAbuse->Video"."id"+ LEFT JOIN "commentAbuse" AS "Abuse->VideoCommentAbuse" ON "Abuse"."id" = "Abuse->VideoCommentAbuse"."abuseId"+ LEFT JOIN "videoComment" AS "Abuse->VideoCommentAbuse->VideoComment"+ ON "Abuse->VideoCommentAbuse"."videoCommentId" = "Abuse->VideoCommentAbuse->VideoComment"."id"+ LEFT JOIN "video" AS "Abuse->VideoCommentAbuse->VideoComment->Video"+ ON "Abuse->VideoCommentAbuse->VideoComment"."videoId" = "Abuse->VideoCommentAbuse->VideoComment->Video"."id"+ LEFT JOIN (+ "account" AS "Abuse->FlaggedAccount"+ ${this.getActorJoin('Abuse->FlaggedAccount')}+ ) ON "Abuse"."flaggedAccountId" = "Abuse->FlaggedAccount"."id"++ LEFT JOIN (+ "videoBlacklist" AS "VideoBlacklist"+ INNER JOIN "video" AS "VideoBlacklist->Video" ON "VideoBlacklist"."videoId" = "VideoBlacklist->Video"."id"+ ) ON "UserNotificationModel"."videoBlacklistId" = "VideoBlacklist"."id"++ LEFT JOIN "videoImport" AS "VideoImport" ON "UserNotificationModel"."videoImportId" = "VideoImport"."id"+ LEFT JOIN "video" AS "VideoImport->Video" ON "VideoImport"."videoId" = "VideoImport->Video"."id"++ LEFT JOIN "plugin" AS "Plugin" ON "UserNotificationModel"."pluginId" = "Plugin"."id"++ LEFT JOIN "application" AS "Application" ON "UserNotificationModel"."applicationId" = "Application"."id"++ LEFT JOIN (+ "actorFollow" AS "ActorFollow"+ INNER JOIN "actor" AS "ActorFollow->ActorFollower" ON "ActorFollow"."actorId" = "ActorFollow->ActorFollower"."id"+ INNER JOIN "account" AS "ActorFollow->ActorFollower->Account"+ ON "ActorFollow->ActorFollower"."id" = "ActorFollow->ActorFollower->Account"."actorId"+ ${this.getActorImageJoin('ActorFollow->ActorFollower')}+ ${this.getActorServerJoin('ActorFollow->ActorFollower')}++ INNER JOIN "actor" AS "ActorFollow->ActorFollowing" ON "ActorFollow"."targetActorId" = "ActorFollow->ActorFollowing"."id"+ LEFT JOIN "videoChannel" AS "ActorFollow->ActorFollowing->VideoChannel"+ ON "ActorFollow->ActorFollowing"."id" = "ActorFollow->ActorFollowing->VideoChannel"."actorId"+ LEFT JOIN "account" AS "ActorFollow->ActorFollowing->Account"+ ON "ActorFollow->ActorFollowing"."id" = "ActorFollow->ActorFollowing->Account"."actorId"+ ${this.getActorServerJoin('ActorFollow->ActorFollowing')}+ ) ON "UserNotificationModel"."actorFollowId" = "ActorFollow"."id"++ LEFT JOIN (+ "account" AS "Account"+ ${this.getActorJoin('Account')}+ ) ON "UserNotificationModel"."accountId" = "Account"."id"++ LEFT JOIN "userRegistration" as "UserRegistration" ON "UserNotificationModel"."userRegistrationId" = "UserRegistration"."id"++ LEFT JOIN (+ "videoCaption" AS "VideoCaption"+ INNER JOIN "video" AS "VideoCaption->Video" ON "VideoCaption"."videoId" = "VideoCaption->Video"."id"+ ) ON "UserNotificationModel"."videoCaptionId" = "VideoCaption"."id"++ LEFT JOIN (+ "videoChannelCollaborator" AS "ChannelCollab"+ ${this.getAccountJoin('ChannelCollab', 'accountId')}+ ${this.getChannelJoin('ChannelCollab', 'channelId', 'Channel')}+ ${this.getAccountJoin('ChannelCollab->Channel', 'accountId')}+ ) ON "UserNotificationModel"."channelCollaboratorId" = "ChannelCollab"."id"`+ }++ // ---------------------------------------------------------------------------++ private getAccountOrChannelAttributes (tableName: string, alias: string) {+ return [+ `"${tableName}"."id" AS "${alias}.id"`,+ `"${tableName}"."name" AS "${alias}.name"`,+ `"${tableName}->Actor"."id" AS "${alias}.Actor.id"`,+ `"${tableName}->Actor"."preferredUsername" AS "${alias}.Actor.preferredUsername"`,+ `"${tableName}->Actor->Avatars"."id" AS "${alias}.Actor.Avatars.id"`,+ `"${tableName}->Actor->Avatars"."width" AS "${alias}.Actor.Avatars.width"`,+ `"${tableName}->Actor->Avatars"."type" AS "${alias}.Actor.Avatars.type"`,+ `"${tableName}->Actor->Avatars"."filename" AS "${alias}.Actor.Avatars.filename"`,+ `"${tableName}->Actor->Server"."id" AS "${alias}.Actor.Server.id"`,+ `"${tableName}->Actor->Server"."host" AS "${alias}.Actor.Server.host"`+ ]+ }++ private getAccountJoin (tableName: string, columnJoin: string) {+ return `INNER JOIN "account" AS "${tableName}->Account" ON "${tableName}"."${columnJoin}" = "${tableName}->Account"."id" ` ++ this.getActorJoin(`${tableName}->Account`)+ }++ private getChannelJoin (tableName: string, columnJoin: string, aliasTableName = 'VideoChannel') {+ // eslint-disable-next-line max-len+ return `INNER JOIN "videoChannel" AS "${tableName}->${aliasTableName}" ON "${tableName}"."${columnJoin}" = "${tableName}->${aliasTableName}".id ` ++ this.getActorJoin(`${tableName}->${aliasTableName}`)+ }++ private getActorJoin (tableName: string) {+ return `INNER JOIN "actor" AS "${tableName}->Actor" ON "${tableName}"."actorId" = "${tableName}->Actor"."id" ` ++ this.getActorImageJoin(`${tableName}->Actor`) ++ this.getActorServerJoin(`${tableName}->Actor`)+ }++ private getActorImageJoin (tableName: string) {+ return `LEFT JOIN "actorImage" AS "${tableName}->Avatars"+ ON "${tableName}"."id" = "${tableName}->Avatars"."actorId"+ AND "${tableName}->Avatars"."type" = ${ActorImageType.AVATAR} `+ }++ private getActorServerJoin (tableName: string) {+ return `LEFT JOIN "server" AS "${tableName}->Server"+ ON "${tableName}"."serverId" = "${tableName}->Server"."id" `+ }+}diff --git a/server/core/models/user/sql/user/user-list-query-builder.ts b/server/core/models/user/sql/user/user-list-query-builder.tsnew file mode 100644index 0000000000..371e4ee46b--- /dev/null+++ b/server/core/models/user/sql/user/user-list-query-builder.ts@@ -0,0 +1,154 @@+import { ActorImageType, VideoChannelCollaboratorState, VideoPlaylistType } from '@peertube/peertube-models'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { Sequelize } from 'sequelize'+import { UserTableAttributes } from './user-table-attributes.js'++export interface ListUserOptions extends AbstractListQueryOptions {+ userId: number+}++export class UserListQueryBuilder extends AbstractListQuery {+ private readonly tableAttributes = new UserTableAttributes()++ private builtAccountJoin = false+ private builtChannelsJoin = false+ private builtChannelCollabsJoin = false+ private builtPlaylistsJoin = false+ private builtNotificationSettingsJoin = false++ constructor (+ protected readonly sequelize: Sequelize,+ protected readonly options: ListUserOptions+ ) {+ super(sequelize, { modelName: 'UserModel', tableName: 'user' }, options)+ }++ protected buildSubQueryWhere () {+ const where: string[] = []++ if (this.options.userId) {+ where.push('"UserModel"."id" = :userId')++ this.replacements.userId = this.options.userId+ }++ if (where.length !== 0) {+ this.subQueryWhere = `WHERE ${where.join(' AND ')}`+ }+ }++ private buildAccountJoin () {+ if (this.builtAccountJoin) return++ this.join += ' INNER JOIN "account" "Account" ON "Account"."userId" = "UserModel"."id" ' ++ 'INNER JOIN "actor" "Account->Actor" ON "Account->Actor"."id" = "Account"."actorId" ' ++ 'LEFT JOIN "server" "Account->Actor->Server" ON "Account->Actor"."serverId" = "Account->Actor->Server"."id" ' ++ 'LEFT JOIN "actorImage" "Account->Actor->Avatars" ON "Account->Actor->Avatars"."actorId" = "Account->Actor"."id" ' ++ ` AND "Account->Actor->Avatars"."type" = ${ActorImageType.AVATAR} `++ this.builtAccountJoin = true+ }++ private buildChannelsJoin () {+ if (this.builtChannelsJoin) return++ this.join += ' LEFT JOIN "videoChannel" "Account->VideoChannels" ON "Account"."id" = "Account->VideoChannels"."accountId" ' ++ 'LEFT JOIN "actor" "Account->VideoChannels->Actor" ON "Account->VideoChannels->Actor"."id" = "Account->VideoChannels"."actorId" ' ++ 'LEFT JOIN "server" "Account->VideoChannels->Actor->Server" ' ++ ' ON "Account->VideoChannels->Actor->Server"."id" = "Account->VideoChannels->Actor"."serverId" ' ++ 'LEFT JOIN "actorImage" "Account->VideoChannels->Actor->Avatars" ' ++ ' ON "Account->VideoChannels->Actor->Avatars"."actorId" = "Account->VideoChannels->Actor"."id" ' ++ ` AND "Account->VideoChannels->Actor->Avatars"."type" = ${ActorImageType.AVATAR} ` ++ 'LEFT JOIN "actorImage" "Account->VideoChannels->Actor->Banners" ' ++ ' ON "Account->VideoChannels->Actor->Banners"."actorId" = "Account->VideoChannels->Actor"."id" ' ++ ` AND "Account->VideoChannels->Actor->Banners"."type" = ${ActorImageType.BANNER} `++ this.builtChannelsJoin = true+ }++ private buildChannelCollabs () {+ if (this.builtChannelCollabsJoin) return++ this.join += 'LEFT JOIN "videoChannelCollaborator" AS "Account->Collabs" ' ++ `ON "Account"."id" = "Account->Collabs"."accountId" AND "Account->Collabs"."state" = ${VideoChannelCollaboratorState.ACCEPTED} ` ++ 'LEFT JOIN (' ++ ' "videoChannel" "Account->Collabs->Channel" ' ++ ' INNER JOIN "actor" AS "Account->Collabs->Channel->Actor" ' ++ ' ON "Account->Collabs->Channel"."actorId" = "Account->Collabs->Channel->Actor"."id"' ++ ' LEFT JOIN "server" AS "Account->Collabs->Channel->Actor->Server" ' ++ ' ON "Account->Collabs->Channel->Actor"."serverId" = "Account->Collabs->Channel->Actor->Server"."id"' ++ ' LEFT JOIN "actorImage" AS "Account->Collabs->Channel->Actor->Avatars" ' ++ ' ON "Account->Collabs->Channel->Actor"."id" = "Account->Collabs->Channel->Actor->Avatars"."actorId"' ++ ` AND "Account->Collabs->Channel->Actor->Avatars"."type" = ${ActorImageType.AVATAR}` ++ ' LEFT JOIN "actorImage" AS "Account->Collabs->Channel->Actor->Banners" ' ++ ' ON "Account->Collabs->Channel->Actor"."id" = "Account->Collabs->Channel->Actor->Banners"."actorId" ' ++ ` AND "Account->Collabs->Channel->Actor->Banners"."type" = ${ActorImageType.BANNER} ` ++ ') ON "Account->Collabs"."channelId" = "Account->Collabs->Channel"."id"'++ this.builtChannelCollabsJoin = true+ }++ private buildPlaylistsJoin () {+ if (this.builtPlaylistsJoin) return++ this.join += 'INNER JOIN "videoPlaylist" AS "Account->VideoPlaylists" ' ++ 'ON "Account"."id" = "Account->VideoPlaylists"."ownerAccountId" ' ++ `AND "Account->VideoPlaylists"."type" = ${VideoPlaylistType.WATCH_LATER} `++ this.builtPlaylistsJoin = true+ }++ private buildNotificationSettingsJoin () {+ if (this.builtNotificationSettingsJoin) return++ this.join += 'INNER JOIN "userNotificationSetting" AS "NotificationSetting" ON "UserModel"."id" = "NotificationSetting"."userId"'++ this.builtNotificationSettingsJoin = true+ }++ // ---------------------------------------------------------------------------++ protected buildQueryJoin () {+ this.buildAccountJoin()+ this.buildChannelsJoin()+ this.buildChannelCollabs()+ this.buildPlaylistsJoin()+ this.buildNotificationSettingsJoin()+ }++ protected buildQueryAttributes () {+ this.attributes = [+ ...this.attributes,++ this.tableAttributes.getAccountAttributes(),+ this.tableAttributes.getAccountActorAttributes(),+ this.tableAttributes.getAccountServerAttributes(),+ this.tableAttributes.getAccountAvatarAttributes(),+ this.tableAttributes.getChannelAttributes(),+ this.tableAttributes.getChannelActorAttributes(),+ this.tableAttributes.getChannelServerAttributes(),+ this.tableAttributes.getChannelAvatarAttributes(),+ this.tableAttributes.getChannelBannerAttributes(),+ this.tableAttributes.getPlaylistAttributes(),+ this.tableAttributes.getNotificationSettingAttributes(),+ this.tableAttributes.getCollabAttributes(),+ this.tableAttributes.getCollabChannelAttributes(),+ this.tableAttributes.getCollabChannelActorAttributes(),+ this.tableAttributes.getCollabChannelActorServerAttributes(),+ this.tableAttributes.getCollabChannelActorAvatarAttributes(),+ this.tableAttributes.getCollabChannelActorBannerAttributes()+ ]+ }++ protected buildSubQueryJoin () {+ // empty+ }++ protected buildSubQueryAttributes () {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,++ this.tableAttributes.getUserAttributes()+ ]+ }+}diff --git a/server/core/models/user/sql/user/user-table-attributes.ts b/server/core/models/user/sql/user/user-table-attributes.tsnew file mode 100644index 0000000000..764d1b0c2e--- /dev/null+++ b/server/core/models/user/sql/user/user-table-attributes.ts@@ -0,0 +1,120 @@+import { Memoize } from '@server/helpers/memoize.js'+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 { UserModel } from '../../user.js'+import { VideoChannelModel } from '@server/models/video/video-channel.js'+import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'+import { UserNotificationSettingModel } from '../../user-notification-setting.js'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'++export class UserTableAttributes {+ @Memoize()+ getUserAttributes () {+ return UserModel.getSQLAttributes('UserModel').join(', ')+ }+ // ---------------------------------------------------------------------------++ @Memoize()+ getAccountAttributes () {+ return AccountModel.getSQLAttributes('Account', 'Account.').join(', ')+ }++ @Memoize()+ getAccountActorAttributes () {+ return ActorModel.getSQLAPIAttributes('Account->Actor', `Account.Actor.`).join(', ')+ }++ @Memoize()+ getAccountServerAttributes () {+ return ServerModel.getSQLAttributes('Account->Actor->Server', `Account.Actor.Server.`).join(', ')+ }++ @Memoize()+ getAccountAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('Account->Actor->Avatars', 'Account.Actor.Avatars.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getChannelAttributes () {+ return VideoChannelModel.getSQLAttributes('Account->VideoChannels', 'Account.VideoChannels.').join(', ')+ }++ @Memoize()+ getChannelActorAttributes () {+ return ActorModel.getSQLAPIAttributes('Account->VideoChannels->Actor', `Account.VideoChannels.Actor.`).join(', ')+ }++ @Memoize()+ getChannelServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('Account->VideoChannels->Actor->Server', `Account.VideoChannels.Actor.Server.`).join(', ')+ }++ @Memoize()+ getChannelAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('Account->VideoChannels->Actor->Avatars', 'Account.VideoChannels.Actor.Avatars.').join(', ')+ }++ @Memoize()+ getChannelBannerAttributes () {+ return ActorImageModel.getSQLAttributes('Account->VideoChannels->Actor->Banners', 'Account.VideoChannels.Actor.Banners.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getPlaylistAttributes () {+ return VideoPlaylistModel.getSQLSummaryAttributes('Account->VideoPlaylists', 'Account.VideoPlaylists.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getNotificationSettingAttributes () {+ return UserNotificationSettingModel.getSQLAttributes('NotificationSetting', 'NotificationSetting.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getCollabAttributes () {+ return VideoChannelCollaboratorModel.getSQLAttributes('Account->Collabs', 'Account.Collabs.').join(', ')+ }++ @Memoize()+ getCollabChannelAttributes () {+ return VideoChannelModel.getSQLAttributes('Account->Collabs->Channel', 'Account.Collabs.Channel.').join(', ')+ }++ @Memoize()+ getCollabChannelActorAttributes () {+ return ActorModel.getSQLAPIAttributes('Account->Collabs->Channel->Actor', 'Account.Collabs.Channel.Actor.').join(', ')+ }++ @Memoize()+ getCollabChannelActorServerAttributes () {+ return ServerModel.getSQLAttributes(+ 'Account->Collabs->Channel->Actor->Server',+ 'Account.Collabs.Channel.Actor.Server.'+ ).join(', ')+ }++ @Memoize()+ getCollabChannelActorAvatarAttributes () {+ return ActorImageModel.getSQLAttributes(+ 'Account->Collabs->Channel->Actor->Avatars',+ 'Account.Collabs.Channel.Actor.Avatars.'+ ).join(', ')+ }++ @Memoize()+ getCollabChannelActorBannerAttributes () {+ return ActorImageModel.getSQLAttributes(+ 'Account->Collabs->Channel->Actor->Banners',+ 'Account.Collabs.Channel.Actor.Banners.'+ ).join(', ')+ }+}diff --git a/server/core/models/user/user-notification-setting.ts b/server/core/models/user/user-notification-setting.tsindex 0dbf7bd968..82879a308c 100644--- a/server/core/models/user/user-notification-setting.ts+++ b/server/core/models/user/user-notification-setting.ts@@ -15,7 +15,7 @@ import {UpdatedAt} from 'sequelize-typescript'import { isUserNotificationSettingValid } from '../../helpers/custom-validators/user-notifications.js'-import { SequelizeModel, throwIfNotValid } from '../shared/index.js'+import { buildSQLAttributes, SequelizeModel, throwIfNotValid } from '../shared/index.js'import { UserModel } from './user.js'@Table({@@ -214,6 +214,18 @@ export class UserNotificationSettingModel extends SequelizeModel<UserNotificatioreturn TokensCache.Instance.clearCacheByUserId(instance.userId)}+ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ // ---------------------------------------------------------------------------+static updateUserSettings (settings: UserNotificationSetting, userId: number) {const query = {where: {diff --git a/server/core/models/user/user-notification.ts b/server/core/models/user/user-notification.tsindex b7fcad0f9c..1264fe7fad 100644--- a/server/core/models/user/user-notification.ts+++ b/server/core/models/user/user-notification.ts@@ -1,27 +1,28 @@import { forceNumber, maxBy } from '@peertube/peertube-core-utils'-import { UserNotification, type UserNotificationType_Type } from '@peertube/peertube-models'+import type { UserNotification, UserNotificationData, UserNotificationType_Type } from '@peertube/peertube-models'import { uuidToShort } from '@peertube/peertube-node-utils'import { UserNotificationIncludes, UserNotificationModelForApi } from '@server/types/models/user/index.js'import { ModelIndexesOptions, Op, WhereOptions } from 'sequelize'-import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, Is, Table, UpdatedAt } from 'sequelize-typescript'+import { AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, Is, Table, UpdatedAt } from 'sequelize-typescript'import { isBooleanValid } from '../../helpers/custom-validators/misc.js'import { isUserNotificationTypeValid } from '../../helpers/custom-validators/user-notifications.js'import { AbuseModel } from '../abuse/abuse.js'import { AccountModel } from '../account/account.js'import { ActorFollowModel } from '../actor/actor-follow.js'+import { ActorImageModel } from '../actor/actor-image.js'import { ApplicationModel } from '../application/application.js'import { PluginModel } from '../server/plugin.js'import { SequelizeModel, throwIfNotValid } from '../shared/index.js'import { getStateLabel } from '../video/formatter/video-api-format.js'import { VideoBlacklistModel } from '../video/video-blacklist.js'import { VideoCaptionModel } from '../video/video-caption.js'+import { VideoChannelCollaboratorModel } from '../video/video-channel-collaborator.js'import { VideoCommentModel } from '../video/video-comment.js'import { VideoImportModel } from '../video/video-import.js'import { VideoModel } from '../video/video.js'-import { UserNotificationListQueryBuilder } from './sql/user-notification-list-query-builder.js'+import { UserNotificationListQueryBuilder } from './sql/user-notification/user-notification-list-query-builder.js'import { UserRegistrationModel } from './user-registration.js'import { UserModel } from './user.js'-import { ActorImageModel } from '../actor/actor-image.js'@Table({tableName: 'userNotification',@@ -108,6 +109,14 @@ import { ActorImageModel } from '../actor/actor-image.js'[Op.ne]: null}}+ },+ {+ fields: [ 'channelCollaboratorId' ],+ where: {+ channelCollaboratorId: {+ [Op.ne]: null+ }+ }}] as (ModelIndexesOptions & { where?: WhereOptions })[]})@@ -124,6 +133,10 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>@Columndeclare read: boolean+ @AllowNull(true)+ @Column(DataType.JSONB)+ declare data: UserNotificationData+@CreatedAtdeclare createdAt: Date@@ -274,6 +287,18 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>})declare VideoCaption: Awaited<VideoCaptionModel>+ @ForeignKey(() => VideoChannelCollaboratorModel)+ @Column+ declare channelCollaboratorId: number++ @BelongsTo(() => VideoChannelCollaboratorModel, {+ foreignKey: {+ allowNull: true+ },+ onDelete: 'cascade'+ })+ declare VideoChannelCollaborator: Awaited<VideoChannelCollaboratorModel>+static listForApi (options: {userId: numberstart: number@@ -287,8 +312,8 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>const countWhere = { userId }const query = {- offset: start,- limit: count,+ start,+ count,sort,userId,@@ -305,7 +330,7 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>count === 0? [] as UserNotificationModelForApi[]- : new UserNotificationListQueryBuilder(this.sequelize, query).listNotifications()+ : new UserNotificationListQueryBuilder(this.sequelize, query).list<UserNotificationModelForApi>()]).then(([ total, data ]) => ({ total, data }))}@@ -329,7 +354,11 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>return UserNotificationModel.update({ read: true }, query)}- static removeNotificationsOf (options: { id: number, type: 'account' | 'server', forUserId?: number }) {+ static removeNotificationsOf (options: {+ id: number+ type: 'account' | 'server'+ forUserId?: number+ }) {const id = forceNumber(options.id)function buildAccountWhereQuery (base: string) {@@ -347,6 +376,7 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>}const queries = [+ // Remove notifications from muted accountsbuildAccountWhereQuery(`SELECT "userNotification"."id" FROM "userNotification" ` +`INNER JOIN "account" ON "userNotification"."accountId" = "account"."id" ` +@@ -369,11 +399,21 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>`INNER JOIN account ON account."actorId" = actor.id `),+ // Remove notifications of comments from muted accountsbuildAccountWhereQuery(`SELECT "userNotification"."id" FROM "userNotification" ` +`INNER JOIN "videoComment" ON "videoComment".id = "userNotification"."commentId" ` +`INNER JOIN account ON account.id = "videoComment"."accountId" ` +`INNER JOIN actor ON "actor"."id" = "account"."actorId" `+ ),++ // Remove notifications from muted accounts that invited us to collaborate to a channel+ buildAccountWhereQuery(+ `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 actor ON "actor"."id" = "account"."actorId" `)]@@ -477,10 +517,24 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>}: undefined+ const videoChannelCollaborator = this.VideoChannelCollaborator+ ? {+ id: this.VideoChannelCollaborator.id,+ channelOwner: this.formatActor(this.VideoChannelCollaborator.Channel.Account),+ channel: this.formatActor(this.VideoChannelCollaborator.Channel),+ account: this.formatActor(this.VideoChannelCollaborator.Account),+ state: {+ id: this.VideoChannelCollaborator.state,+ label: VideoChannelCollaboratorModel.getStateLabel(this.VideoChannelCollaborator.state)+ }+ }+ : undefined+return {id: this.id,type: this.type,read: this.read,+ data: this.data,video,videoImport,comment,@@ -492,6 +546,7 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>peertube,registration,videoCaption,+ videoChannelCollaborator,createdAt: this.createdAt.toISOString(),updatedAt: this.updatedAt.toISOString()}diff --git a/server/core/models/user/user.ts b/server/core/models/user/user.tsindex 105f2cfe60..ad23315bf2 100644--- a/server/core/models/user/user.ts+++ b/server/core/models/user/user.ts@@ -1,4 +1,4 @@-import { forceNumber, hasUserRight, USER_ROLE_LABELS } from '@peertube/peertube-core-utils'+import { forceNumber, hasUserRight, sortBy, USER_ROLE_LABELS } from '@peertube/peertube-core-utils'import {AbuseState,MyUser,@@ -17,6 +17,7 @@ import { CONFIG } from '@server/initializers/config.js'import { TokensCache } from '@server/lib/auth/tokens-cache.js'import { LiveQuotaStore } from '@server/lib/live/index.js'import {+ MChannelFormattable,MMyUserFormattable,MUser,MUserDefault,@@ -68,21 +69,20 @@ import { DEFAULT_INSTANCE_THEME_NAME, NSFW_POLICY_TYPES } from '../../initializeimport { getThemeOrDefault } from '../../lib/plugins/theme-utils.js'import { AccountModel } from '../account/account.js'import { ActorFollowModel } from '../actor/actor-follow.js'-import { ActorImageModel } from '../actor/actor-image.js'import { ActorModel } from '../actor/actor.js'import { OAuthTokenModel } from '../oauth/oauth-token.js'-import { getAdminUsersSort, parseAggregateResult, SequelizeModel, throwIfNotValid } from '../shared/index.js'+import { buildSQLAttributes, getAdminUsersSort, parseAggregateResult, SequelizeModel, throwIfNotValid } from '../shared/index.js'import { VideoChannelModel } from '../video/video-channel.js'import { VideoImportModel } from '../video/video-import.js'import { VideoLiveModel } from '../video/video-live.js'import { VideoPlaylistModel } from '../video/video-playlist.js'import { VideoModel } from '../video/video.js'+import { ListUserOptions, UserListQueryBuilder } from './sql/user/user-list-query-builder.js'import { UserExportModel } from './user-export.js'import { UserNotificationSettingModel } from './user-notification-setting.js'enum ScopeNames {- FOR_ME_API = 'FOR_ME_API',- WITH_VIDEOCHANNELS = 'WITH_VIDEOCHANNELS',+ WITH_VIDEO_CHANNELS = 'WITH_VIDEO_CHANNELS',WITH_QUOTA = 'WITH_QUOTA',WITH_TOTAL_FILE_SIZES = 'WITH_TOTAL_FILE_SIZES',WITH_STATS = 'WITH_STATS'@@ -103,46 +103,7 @@ type WhereUserIdScopeOptions = { whereUserId?: '$userId' | '"UserModel"."id"' }]}))@Scopes(() => ({- [ScopeNames.FOR_ME_API]: {- include: [- {- model: AccountModel,- include: [- {- model: VideoChannelModel.unscoped(),- include: [- {- model: ActorModel,- required: true,- include: [- {- model: ActorImageModel,- as: 'Banners',- required: false- }- ]- }- ]- },- {- attributes: [ 'id', 'name', 'type' ],- model: VideoPlaylistModel.unscoped(),- required: true,- where: {- type: {- [Op.ne]: VideoPlaylistType.REGULAR- }- }- }- ]- },- {- model: UserNotificationSettingModel,- required: true- }- ]- },- [ScopeNames.WITH_VIDEOCHANNELS]: {+ [ScopeNames.WITH_VIDEO_CHANNELS]: {include: [{model: AccountModel,@@ -533,6 +494,18 @@ export class UserModel extends SequelizeModel<UserModel> {return TokensCache.Instance.clearCacheByUserId(instance.id)}+ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ // ---------------------------------------------------------------------------+static countTotal () {return UserModel.unscoped().count()}@@ -656,7 +629,7 @@ export class UserModel extends SequelizeModel<UserModel> {}static loadByIdWithChannels (id: number, withStats = false): Promise<MUserDefault> {- const scopes: (string | ScopeOptions)[] = [ ScopeNames.WITH_VIDEOCHANNELS ]+ const scopes: (string | ScopeOptions)[] = [ ScopeNames.WITH_VIDEO_CHANNELS ]if (withStats) {const scopeOptions: WhereUserIdScopeOptions = { whereUserId: '$userId' }@@ -682,14 +655,14 @@ export class UserModel extends SequelizeModel<UserModel> {return UserModel.findOne(query)}- static loadForMeAPI (id: number): Promise<MUserNotifSettingChannelDefault> {- const query = {- where: {- id- }+ static async loadForMeAPI (id: number) {+ const options: ListUserOptions = {+ userId: forceNumber(id),+ start: 0,+ count: 1}- return UserModel.scope(ScopeNames.FOR_ME_API).findOne(query)+ return new UserListQueryBuilder(UserModel.sequelize, options).get<MUserNotifSettingChannelDefault>()}static loadByEmailCaseInsensitive (email: string): Promise<MUserDefault[]> {@@ -730,6 +703,8 @@ export class UserModel extends SequelizeModel<UserModel> {return UserModel.findAll(query)}+ // ---------------------------------------------------------------------------+static loadByVideoId (videoId: number): Promise<MUserDefault> {const query = {include: [@@ -807,8 +782,7 @@ export class UserModel extends SequelizeModel<UserModel> {include: [{required: true,- attributes: [ 'id' ],- model: AccountModel.unscoped(),+ model: AccountModel,where: {id: accountId}@@ -1093,7 +1067,9 @@ export class UserModel extends SequelizeModel<UserModel> {? this.NotificationSetting.toFormattedJSON(): undefined,- videoChannels: [],+ videoChannels: Array.isArray(this.Account.VideoChannels)+ ? sortBy(this.Account.VideoChannels.map(c => this.formatChannel(c)), 'createdAt')+ : [],createdAt: this.createdAt,@@ -1108,17 +1084,6 @@ export class UserModel extends SequelizeModel<UserModel> {Object.assign(json, { adminFlags: this.adminFlags })}- if (Array.isArray(this.Account.VideoChannels) === true) {- json.videoChannels = this.Account.VideoChannels- .map(c => c.toFormattedJSON())- .sort((v1, v2) => {- if (v1.createdAt < v2.createdAt) return -1- if (v1.createdAt === v2.createdAt) return 0-- return 1- })- }-return json}@@ -1128,6 +1093,17 @@ export class UserModel extends SequelizeModel<UserModel> {const specialPlaylists = this.Account.VideoPlaylists.map(p => ({ id: p.id, name: p.name, type: p.type }))- return Object.assign(formatted, { specialPlaylists })+ const videoChannelCollaborations = Array.isArray(this.Account.VideoChannelCollaborators)+ ? sortBy(+ this.Account.VideoChannelCollaborators.map(c => this.formatChannel(c.Channel)),+ 'createdAt'+ )+ : []++ return Object.assign(formatted, { videoChannelCollaborations, specialPlaylists })+ }++ formatChannel (channel: MChannelFormattable) {+ return { ...channel.toFormattedJSON(), ownerAccountId: channel.accountId }}}diff --git a/server/core/models/video/formatter/video-api-format.ts b/server/core/models/video/formatter/video-api-format.tsindex d5d9dd3cbc..40e28221a4 100644--- a/server/core/models/video/formatter/video-api-format.ts+++ b/server/core/models/video/formatter/video-api-format.ts@@ -105,7 +105,7 @@ export function videoModelToFormattedJSON (video: MVideoFormattable, options: Vi? video.description: video.getTruncatedDescription(),- isLocal: video.isOwned(),+ isLocal: video.isLocal(),duration: video.duration,aspectRatio: video.aspectRatio,diff --git a/server/core/models/video/sql/channel/video-channel-list-query-builder.ts b/server/core/models/video/sql/channel/video-channel-list-query-builder.tsnew file mode 100644index 0000000000..51f736e167--- /dev/null+++ b/server/core/models/video/sql/channel/video-channel-list-query-builder.ts@@ -0,0 +1,275 @@+import { ActorImageType, VideoChannelCollaboratorState } from '@peertube/peertube-models'+import { WEBSERVER } from '@server/initializers/constants.js'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { buildServerIdsFollowedBy } from '@server/models/shared/index.js'+import { Sequelize } from 'sequelize'+import { VideoChannelTableAttributes } from './video-channel-table-attributes.js'++export interface ListVideoChannelsOptions extends AbstractListQueryOptions {+ actorId?: number+ search?: string+ host?: string+ handles?: string[]+ forCount?: boolean++ accountId?: number++ // If accountId is provided, include channels where the account is a collaborator+ // default: false+ includeCollaborations?: boolean++ statsDaysPrior?: number+}++export class VideoChannelListQueryBuilder extends AbstractListQuery {+ private readonly tableAttributes = new VideoChannelTableAttributes()++ private builtActorJoin = false+ private builtAccountJoin = false+ private builtChannelCollaboratorsJoin = false+ private builtAccountAvatarJoin = false+ private builtChannelAvatarJoin = false+ private builtChannelBannerJoin = false++ constructor (+ protected readonly sequelize: Sequelize,+ protected readonly options: ListVideoChannelsOptions+ ) {+ super(sequelize, { modelName: 'VideoChannelModel', tableName: 'videoChannel' }, options)+ }++ // ---------------------------------------------------------------------------++ protected buildSubQueryWhere () {+ const where: string[] = []++ if (this.options.host) {+ this.buildActorJoin()++ if (this.options.host === WEBSERVER.HOST) {+ where.push('"Actor"."serverId" IS NULL')+ } else {+ where.push('"Actor->Server"."host" = :host')++ this.replacements.host = this.options.host+ }+ }++ // Only list local channels OR channels that are on an instance followed by actorId+ if (this.options.actorId) {+ this.buildActorJoin()++ where.push(+ `(` ++ `"Actor"."serverId" IS NULL OR ` ++ `"Actor"."serverId" IN ${buildServerIdsFollowedBy(this.options.actorId)}` ++ `)`+ )+ }++ if (this.options.accountId) {+ this.buildAccountJoin()++ if (this.options.includeCollaborations !== true) {+ where.push('"VideoChannelModel"."accountId" = :accountId')++ this.replacements.accountId = this.options.accountId+ } else {+ this.buildChannelCollaboratorsJoin()++ where.push(+ `("VideoChannelModel"."accountId" = :accountId OR "VideoChannelCollaborators"."accountId" = :accountId)`+ )++ this.replacements.accountId = this.options.accountId+ }+ }++ if (Array.isArray(this.options.handles) && this.options.handles.length !== 0) {+ this.buildActorJoin()++ const or: string[] = []++ for (const handle of this.options.handles || []) {+ const [ preferredUsername, host ] = handle.split('@')++ const sanitizedPreferredUsername = this.sequelize.escape(preferredUsername.toLowerCase())+ const sanitizedHost = this.sequelize.escape(host)++ if (!host || host === WEBSERVER.HOST) {+ or.push(`(LOWER("Actor"."preferredUsername") = ${sanitizedPreferredUsername} AND "Actor"."serverId" IS NULL)`)+ } else {+ or.push(`(LOWER("Actor"."preferredUsername") = ${sanitizedPreferredUsername} AND "Actor->Server"."host" = ${sanitizedHost})`)+ }+ }++ where.push(`(${or.join(' OR ')})`)+ }++ if (this.options.search) {+ const escapedSearch = this.sequelize.escape(this.options.search)+ const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')++ this.subQueryAttributes.push(+ `word_similarity(lower(immutable_unaccent(${escapedSearch})), lower(immutable_unaccent("VideoChannelModel"."name"))) as similarity`+ )++ where.push(+ `(` ++ `lower(immutable_unaccent(${escapedSearch})) <% lower(immutable_unaccent("VideoChannelModel"."name")) OR ` ++ `lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(${escapedLikeSearch}))` ++ `)`+ )+ } else {+ this.subQueryAttributes.push('0 as similarity')+ }++ if (where.length !== 0) {+ this.subQueryWhere = `WHERE ${where.join(' AND ')}`+ }+ }++ // ---------------------------------------------------------------------------++ private buildActorJoin () {+ if (this.builtActorJoin) return++ this.subQueryJoin += ' INNER JOIN "actor" "Actor" ON "Actor"."id" = "VideoChannelModel"."actorId" ' ++ 'LEFT JOIN "server" "Actor->Server" ON "Actor"."serverId" = "Actor->Server"."id" '++ this.builtActorJoin = true+ }++ private buildAccountJoin () {+ if (this.builtAccountJoin) return++ this.subQueryJoin += ' INNER JOIN "account" "Account" ON "Account"."id" = "VideoChannelModel"."accountId" ' ++ 'INNER JOIN "actor" "Account->Actor" ON "Account->Actor"."id" = "Account"."actorId" ' ++ 'LEFT JOIN "server" "Account->Actor->Server" ON "Account->Actor"."serverId" = "Account->Actor->Server"."id" '++ this.builtAccountJoin = true+ }++ private buildChannelCollaboratorsJoin () {+ if (this.builtChannelCollaboratorsJoin) return++ this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "VideoChannelCollaborators" ' ++ 'ON "VideoChannelCollaborators"."channelId" = "VideoChannelModel"."id" ' ++ 'AND "VideoChannelCollaborators"."state" = :channelCollaboratorState ' ++ // Ensure we join with max 1 collaborator to not duplicate rows+ 'AND "VideoChannelCollaborators"."accountId" = :accountId '++ this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED+ this.replacements.accountId = this.options.accountId++ this.builtChannelCollaboratorsJoin = true+ }++ // ---------------------------------------------------------------------------++ private buildAccountAvatarsJoin () {+ if (this.builtAccountAvatarJoin) return++ this.join += `LEFT JOIN "actorImage" "Account->Actor->Avatars" ` ++ `ON "Account->Actor->Avatars"."actorId" = "VideoChannelModel"."Account.Actor.id" ` ++ `AND "Account->Actor->Avatars"."type" = ${ActorImageType.AVATAR} `++ this.builtAccountAvatarJoin = true+ }++ private buildChannelAvatarsJoin () {+ if (this.builtChannelAvatarJoin) return++ this.join += `LEFT JOIN "actorImage" "Actor->Avatars" ` ++ `ON "Actor->Avatars"."actorId" = "VideoChannelModel"."actorId" ` ++ `AND "Actor->Avatars"."type" = ${ActorImageType.AVATAR} `++ this.builtChannelAvatarJoin = true+ }++ private buildChannelBannersJoin () {+ if (this.builtChannelBannerJoin) return++ this.join += `LEFT JOIN "actorImage" "Actor->Banners" ` ++ `ON "Actor->Banners"."actorId" = "VideoChannelModel"."actorId" ` ++ `AND "Actor->Banners"."type" = ${ActorImageType.BANNER} `++ this.builtChannelBannerJoin = true+ }++ // ---------------------------------------------------------------------------++ protected buildQueryJoin () {+ this.buildChannelAvatarsJoin()+ this.buildAccountAvatarsJoin()+ this.buildChannelBannersJoin()+ }++ protected buildQueryAttributes () {+ this.attributes = [+ ...this.attributes,++ this.tableAttributes.getAccountAvatarAttributes(),+ this.tableAttributes.getChannelAvatarAttributes(),+ this.tableAttributes.getChannelBannerAttributes()+ ]++ if (this.options.statsDaysPrior) {+ this.attributes.push(+ `(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id") AS "videosCount"`+ )++ this.attributes.push(+ // dprint-ignore+ '(' ++ `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` ++ 'FROM ( ' ++ 'WITH days AS ( ' ++ `SELECT generate_series(date_trunc('day', now()) - '${this.options.statsDaysPrior} day'::interval, ` ++ `date_trunc('day', now()), '1 day'::interval) AS day ` ++ ') ' ++ 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' ++ 'FROM days ' ++ 'LEFT JOIN (' ++ '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' ++ 'AND "video"."channelId" = "VideoChannelModel"."id"' ++ `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` ++ 'GROUP BY day ORDER BY day ' ++ ') t' ++ ') AS "viewsPerDay"'+ )++ this.attributes.push(+ '(' ++ 'SELECT COALESCE(SUM("video".views), 0) AS totalViews ' ++ 'FROM "video" ' ++ 'WHERE "video"."channelId" = "VideoChannelModel"."id"' ++ ') AS "totalViews"'+ )+ }+ }++ protected buildSubQueryJoin () {+ this.buildActorJoin()+ this.buildAccountJoin()+ }++ protected buildSubQueryAttributes () {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,++ this.tableAttributes.getVideoChannelAttributes(),++ this.tableAttributes.getChannelActorAttributes(),+ this.tableAttributes.getChannelServerAttributes(),++ this.tableAttributes.getAccountAttributes(),+ this.tableAttributes.getAccountActorAttributes(),+ this.tableAttributes.getAccountServerAttributes()+ ]+ }++ protected getCalculatedAttributes () {+ return [ 'similarity' ]+ }+}diff --git a/server/core/models/video/sql/channel/video-channel-table-attributes.ts b/server/core/models/video/sql/channel/video-channel-table-attributes.tsnew file mode 100644index 0000000000..cf7df05cd5--- /dev/null+++ b/server/core/models/video/sql/channel/video-channel-table-attributes.ts@@ -0,0 +1,57 @@+import { Memoize } from '@server/helpers/memoize.js'+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 { VideoChannelModel } from '../../video-channel.js'++export class VideoChannelTableAttributes {+ @Memoize()+ getVideoChannelAttributes () {+ return VideoChannelModel.getSQLAttributes('VideoChannelModel').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getChannelActorAttributes () {+ return ActorModel.getSQLAPIAttributes('Actor', `Actor.`).join(', ')+ }++ @Memoize()+ getChannelServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('Actor->Server', `Actor.Server.`).join(', ')+ }++ @Memoize()+ getChannelAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('Actor->Avatars', 'Actor.Avatars.').join(', ')+ }++ @Memoize()+ getChannelBannerAttributes () {+ return ActorImageModel.getSQLAttributes('Actor->Banners', 'Actor.Banners.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getAccountAttributes () {+ return AccountModel.getSQLSummaryAttributes('Account', 'Account.').join(', ')+ }++ @Memoize()+ getAccountActorAttributes () {+ return ActorModel.getSQLSummaryAttributes('Account->Actor', `Account.Actor.`).join(', ')+ }++ @Memoize()+ getAccountServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('Account->Actor->Server', `Account.Actor.Server.`).join(', ')+ }++ @Memoize()+ getAccountAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('Account->Actor->Avatars', 'Account.Actor.Avatars.').join(', ')+ }+}diff --git a/server/core/models/video/sql/comment/video-comment-list-query-builder.ts b/server/core/models/video/sql/comment/video-comment-list-query-builder.tsindex 906a8889fb..41b2344e84 100644--- a/server/core/models/video/sql/comment/video-comment-list-query-builder.ts+++ b/server/core/models/video/sql/comment/video-comment-list-query-builder.ts@@ -1,18 +1,15 @@-import { ActorImageType, VideoPrivacy } from '@peertube/peertube-models'-import { AbstractRunQuery, ModelBuilder } from '@server/models/shared/index.js'-import { Model, Sequelize, Transaction } from 'sequelize'-import { createSafeIn, getSort, parseRowCountResult } from '../../../shared/index.js'+import { VideoChannelCollaboratorState, VideoPrivacy } from '@peertube/peertube-models'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { getAvatarsJoin, getChannelJoin } from '@server/models/shared/sql/actor-helpers.js'+import { Sequelize } from 'sequelize'+import { createSafeIn } from '../../../shared/index.js'import { VideoCommentTableAttributes } from './video-comment-table-attributes.js'-export interface ListVideoCommentsOptions {+export interface ListVideoCommentsOptions extends AbstractListQueryOptions {selectType: 'api' | 'feed' | 'comment-only'autoTagOfAccountId?: number- start?: number- count?: number- sort?: string-videoId?: numberthreadId?: numberaccountId?: number@@ -28,6 +25,7 @@ export interface ListVideoCommentsOptions {onPublicVideo?: booleanvideoChannelOwnerId?: numbervideoAccountOwnerId?: number+ videoAccountOwnerIncludeCollaborations?: booleanheldForReview: booleanheldForReviewAccountIdException?: number@@ -39,99 +37,31 @@ export interface ListVideoCommentsOptions {searchVideo?: stringincludeReplyCounters?: boolean-- transaction?: Transaction}-export class VideoCommentListQueryBuilder extends AbstractRunQuery {+export class VideoCommentListQueryBuilder extends AbstractListQuery {private readonly tableAttributes = new VideoCommentTableAttributes()- private innerQuery: string-- private select = ''- private joins = ''-- private innerSelect = ''- private innerJoins = ''- private innerLateralJoins = ''- private innerWhere = ''-- private readonly built = {- cte: false,- accountJoin: false,- videoJoin: false,- videoChannelJoin: false,- avatarJoin: false,- automaticTagsJoin: false- }+ private builtAccountJoin = false+ private builtVideoJoin = false+ private builtVideoChannelJoin = false+ private builtVideoChannelCollaboratorsJoin = false+ private builtAvatarJoin = false+ private builtAutomaticTagsJoin = falseconstructor (protected readonly sequelize: Sequelize,- private readonly options: ListVideoCommentsOptions+ protected readonly options: ListVideoCommentsOptions) {- super(sequelize)+ super(sequelize, { modelName: 'VideoCommentModel', tableName: 'videoComment' }, options)if (this.options.includeReplyCounters && !this.options.videoId) {throw new Error('Cannot include reply counters without videoId')}}-- async listComments <T extends Model> () {- this.buildListQuery()-- const results = await this.runQuery({ nest: true, transaction: this.options.transaction })- const modelBuilder = new ModelBuilder<T>(this.sequelize)-- return modelBuilder.createModels(results, 'VideoComment')- }-- async countComments () {- this.buildCountQuery()-- const result = await this.runQuery({ transaction: this.options.transaction })-- return parseRowCountResult(result)- }-- // ----------------------------------------------------------------------------- private buildListQuery () {- this.buildInnerListQuery()- this.buildListSelect()-- this.query = `${this.select} ` +- `FROM (${this.innerQuery}) AS "VideoCommentModel" ` +- `${this.joins} ` +- `${this.getOrder()}`- }-- private buildInnerListQuery () {- this.buildWhere()- this.buildInnerListSelect()-- this.innerQuery = `${this.innerSelect} ` +- `FROM "videoComment" AS "VideoCommentModel" ` +- `${this.innerJoins} ` +- `${this.innerLateralJoins} ` +- `${this.innerWhere} ` +- `${this.getOrder()} ` +- `${this.getInnerLimit()}`- }-// ---------------------------------------------------------------------------- private buildCountQuery () {- this.buildWhere()-- this.query = `SELECT COUNT(*) AS "total" ` +- `FROM "videoComment" AS "VideoCommentModel" ` +- `${this.innerJoins} ` +- `${this.innerWhere}`- }-- // ----------------------------------------------------------------------------- private buildWhere () {+ protected buildSubQueryWhere () {let where: string[] = []if (this.options.videoId) {@@ -218,7 +148,18 @@ export class VideoCommentListQueryBuilder extends AbstractRunQuery {this.replacements.videoAccountOwnerId = this.options.videoAccountOwnerId- where.push(`"Video->VideoChannel"."accountId" = :videoAccountOwnerId`)+ if (this.options.videoAccountOwnerIncludeCollaborations !== true) {+ where.push(`"Video->VideoChannel"."accountId" = :videoAccountOwnerId`)+ } else {+ this.buildVideoChannelCollaboratorsJoin()++ where.push(+ `(` ++ `"Video->VideoChannel"."accountId" = :videoAccountOwnerId OR ` ++ `"Video->VideoChannel->VideoChannelCollaborators"."accountId" = :videoAccountOwnerId` ++ `)`+ )+ }}if (this.options.videoChannelOwnerId) {@@ -241,7 +182,7 @@ export class VideoCommentListQueryBuilder extends AbstractRunQuery {`"Account->Actor"."preferredUsername" ILIKE ${escapedLikeSearch} OR ` +`"Account"."name" ILIKE ${escapedLikeSearch} OR ` +`"Video"."name" ILIKE ${escapedLikeSearch} ` +- `)`+ `)`)}@@ -254,7 +195,7 @@ export class VideoCommentListQueryBuilder extends AbstractRunQuery {`(` +`"Account->Actor"."preferredUsername" ILIKE ${escapedLikeSearch} OR ` +`"Account"."name" ILIKE ${escapedLikeSearch} ` +- `)`+ `)`)}@@ -267,186 +208,229 @@ export class VideoCommentListQueryBuilder extends AbstractRunQuery {}if (where.length !== 0) {- this.innerWhere = `WHERE ${where.join(' AND ')}`+ this.subQueryWhere = `WHERE ${where.join(' AND ')}`}}+ // ---------------------------------------------------------------------------+private buildAccountJoin () {- if (this.built.accountJoin) return+ if (this.builtAccountJoin) return- this.innerJoins += ' LEFT JOIN "account" "Account" ON "Account"."id" = "VideoCommentModel"."accountId" ' ++ this.subQueryJoin += ' LEFT JOIN "account" "Account" ON "Account"."id" = "VideoCommentModel"."accountId" ' +'LEFT JOIN "actor" "Account->Actor" ON "Account->Actor"."id" = "Account"."actorId" ' +'LEFT JOIN "server" "Account->Actor->Server" ON "Account->Actor"."serverId" = "Account->Actor->Server"."id" '- this.built.accountJoin = true+ this.builtAccountJoin = true}private buildVideoJoin () {- if (this.built.videoJoin) return+ if (this.builtVideoJoin) return- this.innerJoins += ' LEFT JOIN "video" "Video" ON "Video"."id" = "VideoCommentModel"."videoId" '+ this.subQueryJoin += ' LEFT JOIN "video" "Video" ON "Video"."id" = "VideoCommentModel"."videoId" '- this.built.videoJoin = true+ this.builtVideoJoin = true}private buildVideoChannelJoin () {- if (this.built.videoChannelJoin) return+ if (this.builtVideoChannelJoin) returnthis.buildVideoJoin()- this.innerJoins += ' LEFT JOIN "videoChannel" "Video->VideoChannel" ON "Video"."channelId" = "Video->VideoChannel"."id" '+ this.subQueryJoin += getChannelJoin({+ base: 'Video->',+ on: '"Video"."channelId"'+ })- this.built.videoChannelJoin = true+ this.builtVideoChannelJoin = true}+ private buildVideoChannelCollaboratorsJoin () {+ if (this.builtVideoChannelCollaboratorsJoin) return- private buildAvatarsJoin () {- if (this.built.avatarJoin) return+ this.buildVideoChannelJoin()- this.joins += `LEFT JOIN "actorImage" "Account->Actor->Avatars" ` +- `ON "VideoCommentModel"."Account.Actor.id" = "Account->Actor->Avatars"."actorId" ` +- `AND "Account->Actor->Avatars"."type" = ${ActorImageType.AVATAR}`+ this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "Video->VideoChannel->VideoChannelCollaborators" ' ++ 'ON "Video->VideoChannel->VideoChannelCollaborators"."channelId" = "Video->VideoChannel"."id" ' ++ 'AND "Video->VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' ++ // Ensure we join with max 1 collaborator to not duplicate rows+ 'AND "Video->VideoChannel->VideoChannelCollaborators"."accountId" = :videoAccountOwnerId '- this.built.avatarJoin = true+ this.replacements.videoAccountOwnerId = this.options.videoAccountOwnerId+ this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED++ this.builtVideoChannelCollaboratorsJoin = true}private buildAutomaticTagsJoin () {- if (this.built.automaticTagsJoin) return+ if (this.builtAutomaticTagsJoin) return- this.innerJoins += 'LEFT JOIN (' ++ this.subQueryJoin += 'LEFT JOIN (' +'"commentAutomaticTag" AS "CommentAutomaticTags" INNER JOIN "automaticTag" AS "CommentAutomaticTags->AutomaticTag" ' +- 'ON "CommentAutomaticTags->AutomaticTag"."id" = "CommentAutomaticTags"."automaticTagId" ' +- ') ON "VideoCommentModel"."id" = "CommentAutomaticTags"."commentId" AND "CommentAutomaticTags"."accountId" = :autoTagOfAccountId'+ 'ON "CommentAutomaticTags->AutomaticTag"."id" = "CommentAutomaticTags"."automaticTagId" ' ++ ') ON "VideoCommentModel"."id" = "CommentAutomaticTags"."commentId" AND "CommentAutomaticTags"."accountId" = :autoTagOfAccountId'this.replacements.autoTagOfAccountId = this.options.autoTagOfAccountId- this.built.automaticTagsJoin = true+ this.builtAutomaticTagsJoin = true}// ---------------------------------------------------------------------------- private buildListSelect () {- const toSelect = [ '"VideoCommentModel".*' ]+ private buildAvatarsJoin () {+ if (this.builtAvatarJoin) return++ this.join += getAvatarsJoin({+ base: 'Account->Actor->',+ on: '"VideoCommentModel"."Account.Actor.id"'+ })++ this.join += getAvatarsJoin({+ base: 'Video->VideoChannel->Actor->',+ on: '"VideoCommentModel"."Video.VideoChannel.Actor.id"'+ })+ this.builtAvatarJoin = true+ }++ // ---------------------------------------------------------------------------++ protected buildQueryJoin () {if (this.options.selectType === 'api' || this.options.selectType === 'feed') {this.buildAvatarsJoin()-- toSelect.push(this.tableAttributes.getAvatarAttributes())}-- this.select = this.buildSelect(toSelect)}- private buildInnerListSelect () {- let toSelect = [ this.tableAttributes.getVideoCommentAttributes() ]+ protected buildQueryAttributes () {+ if (this.options.selectType === 'api' || this.options.selectType === 'feed') {+ this.attributes.push(this.tableAttributes.getAccountAvatarAttributes())+ this.attributes.push(this.tableAttributes.getChannelAvatarAttributes())+ }+ }+ protected buildSubQueryJoin () {if (this.options.selectType === 'api' || this.options.selectType === 'feed') {this.buildAccountJoin()this.buildVideoJoin()+ }++ if (this.options.autoTagOfAccountId && this.options.selectType === 'api') {+ this.buildAutomaticTagsJoin()+ }+ }++ protected buildSubQueryAttributes () {+ this.buildVideoChannelJoin()++ this.subQueryAttributes = [+ ...this.subQueryAttributes,++ this.tableAttributes.getVideoCommentAttributes()+ ]++ if (this.options.selectType === 'api' || this.options.selectType === 'feed') {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,- toSelect = toSelect.concat([this.tableAttributes.getVideoAttributes(),++ this.tableAttributes.getChannelAttributes(),+ this.tableAttributes.getChannelActorAttributes(),+ this.tableAttributes.getChannelServerAttributes(),+this.tableAttributes.getAccountAttributes(),- this.tableAttributes.getActorAttributes(),- this.tableAttributes.getServerAttributes()- ])+ this.tableAttributes.getAccountActorAttributes(),+ this.tableAttributes.getAccountServerAttributes()+ ]}if (this.options.autoTagOfAccountId && this.options.selectType === 'api') {- this.buildAutomaticTagsJoin()+ this.subQueryAttributes = [+ ...this.subQueryAttributes,- toSelect = toSelect.concat([this.tableAttributes.getCommentAutomaticTagAttributes(),this.tableAttributes.getAutomaticTagAttributes()- ])+ ]}if (this.options.includeReplyCounters === true) {- this.buildTotalRepliesSelect()- this.buildAuthorTotalRepliesSelect()-- toSelect.push('"totalRepliesFromVideoAuthor"."count" AS "totalRepliesFromVideoAuthor"')- toSelect.push('"totalReplies"."count" AS "totalReplies"')+ this.subQueryAttributes.push('"totalRepliesFromVideoAuthor"."count" AS "totalRepliesFromVideoAuthor"')+ this.subQueryAttributes.push('"totalReplies"."count" AS "totalReplies"')}+ }- this.innerSelect = this.buildSelect(toSelect)+ protected getCalculatedAttributes () {+ return [+ 'totalRepliesFromVideoAuthor',+ 'totalReplies'+ ]}// ---------------------------------------------------------------------------- private getBlockWhere (commentTableName: string, channelTableName: string) {- const where: string[] = []-- const blockerIdsString = createSafeIn(- this.sequelize,- this.options.blockerAccountIds,- [ `"${channelTableName}"."accountId"` ]- )-- where.push(- `NOT EXISTS (` +- `SELECT 1 FROM "accountBlocklist" ` +- `WHERE "targetAccountId" = "${commentTableName}"."accountId" ` +- `AND "accountId" IN (${blockerIdsString})` +- `)`- )-- where.push(- `NOT EXISTS (` +- `SELECT 1 FROM "account" ` +- `INNER JOIN "actor" ON account."actorId" = actor.id ` +- `INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +- `WHERE "account"."id" = "${commentTableName}"."accountId" ` +- `AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +- `)`- )-- return where+ protected buildSubQueryLateralJoin () {+ if (this.options.includeReplyCounters === true) {+ this.buildTotalRepliesLateralJoin()+ this.buildAuthorTotalRepliesLateralJoin()+ }}- // ----------------------------------------------------------------------------- private buildTotalRepliesSelect () {+ private buildTotalRepliesLateralJoin () {const blockWhereString = this.getBlockWhere('replies', 'videoChannel').join(' AND ')// Help the planner by providing videoId that should filter out many commentsthis.replacements.videoId = this.options.videoId- this.innerLateralJoins += `LEFT JOIN LATERAL (` ++ this.subQueryLateralJoin += `LEFT JOIN LATERAL (` +`SELECT COUNT("replies"."id") AS "count" FROM "videoComment" AS "replies" ` +`INNER JOIN "video" ON "video"."id" = "replies"."videoId" AND "replies"."videoId" = :videoId ` +`LEFT JOIN "videoChannel" ON "video"."channelId" = "videoChannel"."id" ` +`WHERE ("replies"."inReplyToCommentId" = "VideoCommentModel"."id" OR "replies"."originCommentId" = "VideoCommentModel"."id") ` +- `AND "deletedAt" IS NULL ` +- `AND ${blockWhereString} ` +- `) "totalReplies" ON TRUE `+ `AND "deletedAt" IS NULL ` ++ `AND ${blockWhereString} ` ++ `) "totalReplies" ON TRUE `}- private buildAuthorTotalRepliesSelect () {+ private buildAuthorTotalRepliesLateralJoin () {// Help the planner by providing videoId that should filter out many commentsthis.replacements.videoId = this.options.videoId- this.innerLateralJoins += `LEFT JOIN LATERAL (` ++ this.subQueryLateralJoin += `LEFT JOIN LATERAL (` +`SELECT COUNT("replies"."id") AS "count" FROM "videoComment" AS "replies" ` +`INNER JOIN "video" ON "video"."id" = "replies"."videoId" AND "replies"."videoId" = :videoId ` +`INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ` +`WHERE ("replies"."inReplyToCommentId" = "VideoCommentModel"."id" OR "replies"."originCommentId" = "VideoCommentModel"."id") ` +- `AND "replies"."accountId" = "videoChannel"."accountId"` +- `) "totalRepliesFromVideoAuthor" ON TRUE `+ `AND "replies"."accountId" = "videoChannel"."accountId"` ++ `) "totalRepliesFromVideoAuthor" ON TRUE `}- private getOrder () {- if (!this.options.sort) return ''+ // ---------------------------------------------------------------------------- const orders = getSort(this.options.sort)+ private getBlockWhere (commentTableName: string, channelTableName: string) {+ const where: string[] = []- return 'ORDER BY ' + orders.map(o => `"${o[0]}" ${o[1]}`).join(', ')- }+ const blockerIdsString = createSafeIn(+ this.sequelize,+ this.options.blockerAccountIds,+ [ `"${channelTableName}"."accountId"` ]+ )- private getInnerLimit () {- if (!this.options.count) return ''+ where.push(+ `NOT EXISTS (` ++ `SELECT 1 FROM "accountBlocklist" ` ++ `WHERE "targetAccountId" = "${commentTableName}"."accountId" ` ++ `AND "accountId" IN (${blockerIdsString})` ++ `)`+ )- this.replacements.limit = this.options.count- this.replacements.offset = this.options.start || 0+ where.push(+ `NOT EXISTS (` ++ `SELECT 1 FROM "account" ` ++ `INNER JOIN "actor" ON account."actorId" = actor.id ` ++ `INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` ++ `WHERE "account"."id" = "${commentTableName}"."accountId" ` ++ `AND "serverBlocklist"."accountId" IN (${blockerIdsString})` ++ `)`+ )- return `LIMIT :limit OFFSET :offset `+ return where}}diff --git a/server/core/models/video/sql/comment/video-comment-table-attributes.ts b/server/core/models/video/sql/comment/video-comment-table-attributes.tsindex 353e5f04f8..33df439569 100644--- a/server/core/models/video/sql/comment/video-comment-table-attributes.ts+++ b/server/core/models/video/sql/comment/video-comment-table-attributes.ts@@ -2,24 +2,19 @@ import { Memoize } from '@server/helpers/memoize.js'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 { CommentAutomaticTagModel } from '@server/models/automatic-tag/comment-automatic-tag.js'import { ServerModel } from '@server/models/server/server.js'-import { buildSQLAttributes } from '@server/models/shared/sql.js'+import { buildSQLAttributes } from '@server/models/shared/table.js'import { AutomaticTagModel } from '../../../automatic-tag/automatic-tag.js'import { VideoCommentModel } from '../../video-comment.js'-import { CommentAutomaticTagModel } from '@server/models/automatic-tag/comment-automatic-tag.js'+import { VideoChannelModel } from '../../video-channel.js'export class VideoCommentTableAttributes {-@Memoize()getVideoCommentAttributes () {return VideoCommentModel.getSQLAttributes('VideoCommentModel').join(', ')}- @Memoize()- getAccountAttributes () {- return AccountModel.getSQLAttributes('Account', 'Account.').join(', ')- }-@Memoize()getVideoAttributes () {return [@@ -29,21 +24,52 @@ export class VideoCommentTableAttributes {].join(', ')}+ // ---------------------------------------------------------------------------++ @Memoize()+ getAccountAttributes () {+ return AccountModel.getSQLAttributes('Account', 'Account.').join(', ')+ }+@Memoize()- getActorAttributes () {+ getAccountActorAttributes () {return ActorModel.getSQLAPIAttributes('Account->Actor', `Account.Actor.`).join(', ')}@Memoize()- getServerAttributes () {+ getAccountServerAttributes () {return ServerModel.getSQLAttributes('Account->Actor->Server', `Account.Actor.Server.`).join(', ')}@Memoize()- getAvatarAttributes () {+ getAccountAvatarAttributes () {return ActorImageModel.getSQLAttributes('Account->Actor->Avatars', 'Account.Actor.Avatars.').join(', ')}+ // ---------------------------------------------------------------------------++ @Memoize()+ getChannelAttributes () {+ return VideoChannelModel.getSQLSummaryAttributes('Video->VideoChannel', 'Video.VideoChannel.').join(', ')+ }++ @Memoize()+ getChannelActorAttributes () {+ return ActorModel.getSQLSummaryAttributes('Video->VideoChannel->Actor', `Video.VideoChannel.Actor.`).join(', ')+ }++ @Memoize()+ getChannelServerAttributes () {+ return ServerModel.getSQLAttributes('Video->VideoChannel->Actor->Server', `Video.VideoChannel.Actor.Server.`).join(', ')+ }++ @Memoize()+ getChannelAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('Video->VideoChannel->Actor->Avatars', 'Video.VideoChannel.Actor.Avatars.').join(', ')+ }++ // ---------------------------------------------------------------------------+@Memoize()getCommentAutomaticTagAttributes () {return buildSQLAttributes({diff --git a/server/core/models/video/sql/import/video-import-list-query-builder.ts b/server/core/models/video/sql/import/video-import-list-query-builder.tsnew file mode 100644index 0000000000..424bd939cc--- /dev/null+++ b/server/core/models/video/sql/import/video-import-list-query-builder.ts@@ -0,0 +1,196 @@+import { VideoChannelCollaboratorState } from '@peertube/peertube-models'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { getAvatarsJoin, getChannelJoin } from '@server/models/shared/sql/actor-helpers.js'+import { Sequelize } from 'sequelize'+import { VideoImportTableAttributes } from './video-import-table-attributes.js'++export interface ListVideoImportsOptions extends AbstractListQueryOptions {+ userId: number++ search?: string+ targetUrl?: string+ videoChannelSyncId?: number++ collaborationAccountId?: number+}++export class VideoImportListQueryBuilder extends AbstractListQuery {+ private readonly tableAttributes = new VideoImportTableAttributes()++ private builtVideoJoin = false+ private builtTagJoin = false+ private builtChannelCollaboratorsJoin = false+ private builtThumbnailJoin = false+ private builtAccountAvatarJoin = false+ private builtChannelAvatarJoin = false++ constructor (+ protected readonly sequelize: Sequelize,+ protected readonly options: ListVideoImportsOptions+ ) {+ super(sequelize, { modelName: 'VideoImportModel', tableName: 'videoImport' }, options)+ }++ // ---------------------------------------------------------------------------++ protected buildSubQueryWhere () {+ const where: string[] = []++ this.buildVideoJoin()++ if (this.options.collaborationAccountId) {+ this.buildChannelCollaboratorsJoin()++ where.push(+ '(' ++ '"VideoImportModel"."userId" = :userId OR ' ++ '"Video->VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId OR ' ++ '"Video->VideoChannel->Account"."userId" = :userId' ++ ')'+ )++ this.replacements.collaborationAccountId = this.options.collaborationAccountId+ this.replacements.userId = this.options.userId+ } else {+ where.push(+ '(' ++ '"VideoImportModel"."userId" = :userId OR ' ++ '"Video->VideoChannel->Account"."userId" = :userId' ++ ')'+ )++ this.replacements.userId = this.options.userId+ }++ if (this.options.targetUrl) {+ where.push('"VideoImportModel"."targetUrl" = :targetUrl')++ this.replacements.targetUrl = this.options.targetUrl+ }++ if (this.options.videoChannelSyncId) {+ where.push('"VideoImportModel"."videoChannelSyncId" = :videoChannelSyncId')++ this.replacements.videoChannelSyncId = this.options.videoChannelSyncId+ }++ if (this.options.search) {+ const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')++ where.push(+ `(` ++ `lower(immutable_unaccent("Video"."name")) LIKE lower(immutable_unaccent(${escapedLikeSearch})) OR ` ++ `lower(immutable_unaccent("VideoImportModel"."targetUrl")) LIKE lower(immutable_unaccent(${escapedLikeSearch})) OR ` ++ `lower(immutable_unaccent("VideoImportModel"."torrentName")) LIKE lower(immutable_unaccent(${escapedLikeSearch})) OR ` ++ `lower(immutable_unaccent("VideoImportModel"."magnetUri")) LIKE lower(immutable_unaccent(${escapedLikeSearch}))` ++ `)`+ )+ }++ if (where.length !== 0) {+ this.subQueryWhere = `WHERE ${where.join(' AND ')}`+ }+ }++ private buildVideoJoin () {+ if (this.builtVideoJoin) return++ this.subQueryJoin += ` LEFT JOIN "video" "Video" ON "Video"."id" = "VideoImportModel"."videoId" ` ++ getChannelJoin({ base: 'Video->', on: '"Video"."channelId"', includeAccount: true })++ this.builtVideoJoin = 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 ' ++ // Ensure we join with max 1 collaborator to not duplicate rows+ 'AND "Video->VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId '++ this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED+ this.replacements.collaborationAccountId = this.options.collaborationAccountId++ this.builtChannelCollaboratorsJoin = true+ }++ // ---------------------------------------------------------------------------++ private buildThumbnailJoin () {+ if (this.builtThumbnailJoin) return++ this.join += ' LEFT JOIN "thumbnail" "Video->Thumbnails" ON "Video->Thumbnails"."videoId" = "Video.id" '++ this.builtThumbnailJoin = true+ }++ private buildTagJoin () {+ if (this.builtTagJoin) return++ this.join += ' LEFT JOIN "videoTag" ON "videoTag"."videoId" = "Video.id" ' ++ 'LEFT JOIN "tag" "Video->Tags" ON "Video->Tags"."id" = "videoTag"."tagId" '++ this.builtTagJoin = true+ }++ private buildAccountAvatarsJoin () {+ if (this.builtAccountAvatarJoin) return++ this.join += getAvatarsJoin({ base: 'Video->VideoChannel->Account->Actor->', on: '"Video.VideoChannel.Account.Actor.id"' })++ this.builtAccountAvatarJoin = true+ }++ private buildChannelAvatarsJoin () {+ if (this.builtChannelAvatarJoin) return++ this.join += getAvatarsJoin({ base: 'Video->VideoChannel->Actor->', on: '"Video.VideoChannel.Actor.id"' })++ this.builtChannelAvatarJoin = true+ }++ // ---------------------------------------------------------------------------++ protected buildQueryJoin () {+ this.buildChannelAvatarsJoin()+ this.buildAccountAvatarsJoin()+ this.buildTagJoin()+ this.buildThumbnailJoin()+ }++ protected buildQueryAttributes () {+ this.attributes = [+ ...this.attributes,++ this.tableAttributes.getVideoTagAttributes(),+ this.tableAttributes.getAccountAvatarAttributes(),+ this.tableAttributes.getChannelAvatarAttributes(),+ this.tableAttributes.getThumbnailAttributes()+ ]+ }++ protected buildSubQueryJoin () {+ this.buildVideoJoin()+ }++ protected buildSubQueryAttributes () {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,++ this.tableAttributes.getVideoImportAttributes(),+ this.tableAttributes.getVideoAttributes(),++ this.tableAttributes.getChannelAttributes(),+ this.tableAttributes.getChannelActorAttributes(),+ this.tableAttributes.getChannelServerAttributes(),++ this.tableAttributes.getAccountAttributes(),+ this.tableAttributes.getAccountActorAttributes(),+ this.tableAttributes.getAccountServerAttributes()+ ]+ }+}diff --git a/server/core/models/video/sql/import/video-import-table-attributes.ts b/server/core/models/video/sql/import/video-import-table-attributes.tsnew file mode 100644index 0000000000..910316195a--- /dev/null+++ b/server/core/models/video/sql/import/video-import-table-attributes.ts@@ -0,0 +1,81 @@+import { Memoize } from '@server/helpers/memoize.js'+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 { TagModel } from '../../tag.js'+import { ThumbnailModel } from '../../thumbnail.js'+import { VideoChannelModel } from '../../video-channel.js'+import { VideoImportModel } from '../../video-import.js'+import { VideoModel } from '../../video.js'++export class VideoImportTableAttributes {+ @Memoize()+ getVideoImportAttributes () {+ return VideoImportModel.getSQLAttributes('VideoImportModel').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getVideoAttributes () {+ return VideoModel.getSQLAttributes('Video', 'Video.').join(', ')+ }++ getVideoTagAttributes () {+ return TagModel.getSQLAttributes('Video->Tags', 'Video.Tags.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getChannelAttributes () {+ return VideoChannelModel.getSQLAttributes('Video->VideoChannel', 'Video.VideoChannel.').join(', ')+ }++ @Memoize()+ getChannelActorAttributes () {+ return ActorModel.getSQLSummaryAttributes('Video->VideoChannel->Actor', `Video.VideoChannel.Actor.`).join(', ')+ }++ @Memoize()+ getChannelServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('Video->VideoChannel->Actor->Server', `Video.VideoChannel.Actor.Server.`).join(', ')+ }++ @Memoize()+ getChannelAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('Video->VideoChannel->Actor->Avatars', 'Video.VideoChannel.Actor.Avatars.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getAccountAttributes () {+ return AccountModel.getSQLSummaryAttributes('Video->VideoChannel->Account', 'Video.VideoChannel.Account.').join(', ')+ }++ @Memoize()+ getAccountActorAttributes () {+ return ActorModel.getSQLSummaryAttributes('Video->VideoChannel->Account->Actor', `Video.VideoChannel.Account.Actor.`).join(', ')+ }++ @Memoize()+ getAccountServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('Video->VideoChannel->Account->Actor->Server', `Video.VideoChannel.Account.Actor.Server.`)+ .join(', ')+ }++ @Memoize()+ getAccountAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('Video->VideoChannel->Account->Actor->Avatars', 'Video.VideoChannel.Account.Actor.Avatars.')+ .join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getThumbnailAttributes () {+ return ThumbnailModel.getSQLAttributes('Video->Thumbnails', 'Video.Thumbnails.').join(', ')+ }+}diff --git a/server/core/models/video/sql/playlist/video-playlist-list-query-builder.ts b/server/core/models/video/sql/playlist/video-playlist-list-query-builder.tsnew file mode 100644index 0000000000..ad8f45df90--- /dev/null+++ b/server/core/models/video/sql/playlist/video-playlist-list-query-builder.ts@@ -0,0 +1,282 @@+import { ActorImageType, VideoChannelCollaboratorState, VideoPlaylistPrivacy, VideoPlaylistType_Type } from '@peertube/peertube-models'+import { WEBSERVER } from '@server/initializers/constants.js'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { buildServerIdsFollowedBy, getPlaylistSort } from '@server/models/shared/index.js'+import { Sequelize } from 'sequelize'+import { VideoPlaylistTableAttributes } from './video-playlist-table-attributes.js'++export interface ListVideoPlaylistsOptions extends AbstractListQueryOptions {+ followerActorId?: number+ type?: VideoPlaylistType_Type++ accountId?: number+ includeCollaborationsForAccount?: number++ videoChannelId?: number+ listMyPlaylists?: boolean+ search?: string+ host?: string+ uuids?: string[]+ channelNameOneOf?: string[]+ withVideos?: boolean+}++export class VideoPlaylistListQueryBuilder extends AbstractListQuery {+ private readonly tableAttributes = new VideoPlaylistTableAttributes()++ private builtAccountJoin = false+ private builtVideoChannelJoin = false+ private builtChannelCollaboratorsJoin = false+ private builtAccountAvatarJoin = false+ private builtChannelAvatarJoin = false+ private builtThumbnailJoin = false++ constructor (+ protected readonly sequelize: Sequelize,+ protected readonly options: ListVideoPlaylistsOptions+ ) {+ super(sequelize, { modelName: 'VideoPlaylistModel', tableName: 'videoPlaylist' }, options)+ }++ // ---------------------------------------------------------------------------++ protected buildSubQueryWhere () {+ const where: string[] = []++ if (this.options.host) {+ this.buildAccountJoin()++ if (this.options.host === WEBSERVER.HOST) {+ where.push('"OwnerAccount->Actor"."serverId" IS NULL')+ } else {+ where.push('"OwnerAccount->Actor->Server"."host" = :host')++ this.replacements.host = this.options.host+ }+ }++ if (this.options.listMyPlaylists !== true) {+ where.push('"VideoPlaylistModel"."privacy" = :privacy')++ this.replacements.privacy = VideoPlaylistPrivacy.PUBLIC+ }++ if (this.options.followerActorId) {+ this.buildAccountJoin()++ where.push(+ `(` ++ `"OwnerAccount->Actor"."serverId" IS NULL OR ` ++ `"OwnerAccount->Actor"."serverId" IN ${buildServerIdsFollowedBy(this.options.followerActorId)}` ++ `)`+ )+ }++ if (this.options.accountId) {+ if (this.options.includeCollaborationsForAccount) {+ this.buildChannelCollaboratorsJoin()++ where.push(+ `(` ++ ` "VideoPlaylistModel"."ownerAccountId" = :accountId OR ` ++ ` "VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId` ++ `)`+ )++ this.replacements.accountId = this.options.accountId+ this.replacements.collaborationAccountId = this.options.includeCollaborationsForAccount+ } else {+ where.push('"VideoPlaylistModel"."ownerAccountId" = :accountId')++ this.replacements.accountId = this.options.accountId+ }+ }++ if (this.options.videoChannelId) {+ if (this.options.includeCollaborationsForAccount) {+ this.buildChannelCollaboratorsJoin()++ where.push(+ `(` ++ ` "VideoPlaylistModel"."videoChannelId" = :videoChannelId OR ` ++ ` "VideoChannel->VideoChannelCollaborators"."accountId" = :collaborationAccountId` ++ `)`+ )++ this.replacements.videoChannelId = this.options.videoChannelId+ this.replacements.collaborationAccountId = this.options.includeCollaborationsForAccount+ } else {+ where.push('"VideoPlaylistModel"."videoChannelId" = :videoChannelId')++ this.replacements.videoChannelId = this.options.videoChannelId+ }+ }++ if (this.options.channelNameOneOf && this.options.channelNameOneOf.length !== 0) {+ this.buildChannelJoin()++ where.push('"VideoChannel->Actor"."preferredUsername" IN (:channelNameOneOf)')+ this.replacements.channelNameOneOf = this.options.channelNameOneOf+ }++ if (this.options.type) {+ where.push('"VideoPlaylistModel"."type" = :type')++ this.replacements.type = this.options.type+ }++ if (this.options.uuids) {+ where.push('"VideoPlaylistModel"."uuid" IN (:uuids)')++ this.replacements.uuids = this.options.uuids+ }++ if (this.options.withVideos === true) {+ where.push(`(${this.getTotalVideosQuery()}) != 0`)+ }++ if (this.options.search) {+ const escapedSearch = this.sequelize.escape(this.options.search)+ const escapedLikeSearch = this.sequelize.escape('%' + this.options.search + '%')++ this.subQueryAttributes.push(+ `word_similarity(lower(immutable_unaccent(${escapedSearch})), lower(immutable_unaccent("VideoPlaylistModel"."name"))) as similarity`+ )++ where.push(+ `(` ++ `lower(immutable_unaccent(${escapedSearch})) <% lower(immutable_unaccent("VideoPlaylistModel"."name")) OR ` ++ `lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(${escapedLikeSearch}))` ++ `)`+ )+ } else {+ this.subQueryAttributes.push('0 as similarity')+ }++ if (where.length !== 0) {+ this.subQueryWhere = `WHERE ${where.join(' AND ')}`+ }+ }++ private buildAccountJoin () {+ if (this.builtAccountJoin) return++ this.subQueryJoin += ' INNER JOIN "account" "OwnerAccount" ON "OwnerAccount"."id" = "VideoPlaylistModel"."ownerAccountId" ' ++ 'INNER JOIN "actor" "OwnerAccount->Actor" ON "OwnerAccount->Actor"."id" = "OwnerAccount"."actorId" ' ++ 'LEFT JOIN "server" "OwnerAccount->Actor->Server" ON "OwnerAccount->Actor"."serverId" = "OwnerAccount->Actor->Server"."id" '++ this.builtAccountJoin = true+ }++ private buildChannelJoin () {+ if (this.builtVideoChannelJoin) return++ this.subQueryJoin += ' LEFT JOIN "videoChannel" "VideoChannel" ON "VideoPlaylistModel"."videoChannelId" = "VideoChannel"."id" ' ++ 'LEFT JOIN "actor" "VideoChannel->Actor" ON "VideoChannel->Actor"."id" = "VideoChannel"."actorId" ' ++ 'LEFT JOIN "server" "VideoChannel->Actor->Server" ON "VideoChannel->Actor"."serverId" = "VideoChannel->Actor->Server"."id" '++ this.builtVideoChannelJoin = true+ }++ private buildChannelCollaboratorsJoin () {+ if (this.builtChannelCollaboratorsJoin) return++ this.buildChannelJoin()++ this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "VideoChannel->VideoChannelCollaborators" ' ++ 'ON "VideoChannel->VideoChannelCollaborators"."channelId" = "VideoChannel"."id" ' ++ 'AND "VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' ++ // Ensure we join with max 1 collaborator to not duplicate rows+ 'AND "VideoChannel->VideoChannelCollaborators"."accountId" = :accountId '++ this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED+ this.replacements.accountId = this.options.accountId++ this.builtChannelCollaboratorsJoin = true+ }++ private buildAccountAvatarsJoin () {+ if (this.builtAccountAvatarJoin) return++ this.join += `LEFT JOIN "actorImage" "OwnerAccount->Actor->Avatars" ` ++ `ON "OwnerAccount->Actor->Avatars"."actorId" = "VideoPlaylistModel"."OwnerAccount.Actor.id" ` ++ `AND "OwnerAccount->Actor->Avatars"."type" = ${ActorImageType.AVATAR} `++ this.builtAccountAvatarJoin = true+ }++ private buildChannelAvatarsJoin () {+ if (this.builtChannelAvatarJoin) return++ this.join += `LEFT JOIN "actorImage" "VideoChannel->Actor->Avatars" ` ++ `ON "VideoChannel->Actor->Avatars"."actorId" = "VideoPlaylistModel"."VideoChannel.actorId" ` ++ `AND "VideoChannel->Actor->Avatars"."type" = ${ActorImageType.AVATAR} `++ this.builtChannelAvatarJoin = true+ }++ private buildThumbnailJoin () {+ if (this.builtThumbnailJoin) return++ this.join += ' LEFT JOIN "thumbnail" "Thumbnail" ON "Thumbnail"."videoPlaylistId" = "VideoPlaylistModel"."id" '++ this.builtThumbnailJoin = true+ }++ // ---------------------------------------------------------------------------++ protected buildQueryJoin () {+ this.buildChannelAvatarsJoin()+ this.buildAccountAvatarsJoin()+ this.buildThumbnailJoin()+ }++ protected buildQueryAttributes () {+ this.attributes = [+ ...this.attributes,++ this.tableAttributes.getAccountAvatarAttributes(),+ this.tableAttributes.getChannelAvatarAttributes(),+ this.tableAttributes.getThumbnailAttributes()+ ]+ }++ protected buildSubQueryJoin () {+ this.buildAccountJoin()+ this.buildChannelJoin()+ }++ protected buildSubQueryAttributes () {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,++ this.tableAttributes.getVideoPlaylistAttributes(),++ this.tableAttributes.getChannelAttributes(),+ this.tableAttributes.getChannelActorAttributes(),+ this.tableAttributes.getChannelServerAttributes(),++ this.tableAttributes.getAccountAttributes(),+ this.tableAttributes.getAccountActorAttributes(),+ this.tableAttributes.getAccountServerAttributes(),++ this.getTotalVideosAttribute()+ ]+ }++ private getTotalVideosQuery () {+ return `SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"`+ }++ private getTotalVideosAttribute () {+ return `(${this.getTotalVideosQuery()}) AS "videosLength"`+ }++ protected getSort (sort: string) {+ return getPlaylistSort(sort)+ }++ protected getCalculatedAttributes () {+ return [ 'similarity', 'videosLength' ]+ }+}diff --git a/server/core/models/video/sql/playlist/video-playlist-table-attributes.ts b/server/core/models/video/sql/playlist/video-playlist-table-attributes.tsnew file mode 100644index 0000000000..24f22edb84--- /dev/null+++ b/server/core/models/video/sql/playlist/video-playlist-table-attributes.ts@@ -0,0 +1,66 @@+import { Memoize } from '@server/helpers/memoize.js'+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 { VideoChannelModel } from '../../video-channel.js'+import { VideoPlaylistModel } from '../../video-playlist.js'+import { ThumbnailModel } from '../../thumbnail.js'++export class VideoPlaylistTableAttributes {+ @Memoize()+ getVideoPlaylistAttributes () {+ return VideoPlaylistModel.getSQLAttributes('VideoPlaylistModel').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getChannelAttributes () {+ return VideoChannelModel.getSQLSummaryAttributes('VideoChannel', 'VideoChannel.').join(', ')+ }++ @Memoize()+ getChannelActorAttributes () {+ return ActorModel.getSQLSummaryAttributes('VideoChannel->Actor', `VideoChannel.Actor.`).join(', ')+ }++ @Memoize()+ getChannelServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('VideoChannel->Actor->Server', `VideoChannel.Actor.Server.`).join(', ')+ }++ @Memoize()+ getChannelAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('VideoChannel->Actor->Avatars', 'VideoChannel.Actor.Avatars.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getAccountAttributes () {+ return AccountModel.getSQLSummaryAttributes('OwnerAccount', 'OwnerAccount.').join(', ')+ }++ @Memoize()+ getAccountActorAttributes () {+ return ActorModel.getSQLSummaryAttributes('OwnerAccount->Actor', `OwnerAccount.Actor.`).join(', ')+ }++ @Memoize()+ getAccountServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('OwnerAccount->Actor->Server', `OwnerAccount.Actor.Server.`).join(', ')+ }++ @Memoize()+ getAccountAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('OwnerAccount->Actor->Avatars', 'OwnerAccount.Actor.Avatars.').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getThumbnailAttributes () {+ return ThumbnailModel.getSQLAttributes('Thumbnail', 'Thumbnail.').join(', ')+ }+}diff --git a/server/core/models/video/sql/video-channel-sync/video-channel-sync-list-query-builder.ts b/server/core/models/video/sql/video-channel-sync/video-channel-sync-list-query-builder.tsnew file mode 100644index 0000000000..51f8c879d3--- /dev/null+++ b/server/core/models/video/sql/video-channel-sync/video-channel-sync-list-query-builder.ts@@ -0,0 +1,119 @@+import { VideoChannelCollaboratorState } from '@peertube/peertube-models'+import { AbstractListQuery, AbstractListQueryOptions } from '@server/models/shared/abstract-list-query.js'+import { getChannelSyncSort } from '@server/models/shared/index.js'+import { OrderItem, Sequelize } from 'sequelize'+import { VideoChannelSyncTableAttributes } from './video-channel-sync-table-attributes.js'+import { getAvatarsJoin, getChannelJoin } from '@server/models/shared/sql/actor-helpers.js'++export interface ListVideoChannelSyncsOptions extends AbstractListQueryOptions {+ accountId: number++ includeCollaborations?: boolean+}++export class VideoChannelSyncListQueryBuilder extends AbstractListQuery {+ private readonly tableAttributes = new VideoChannelSyncTableAttributes()++ private builtChannelJoin = false+ private builtChannelAvatarsJoin = false+ private builtChannelCollaboratorsJoin = false++ constructor (+ protected readonly sequelize: Sequelize,+ protected readonly options: ListVideoChannelSyncsOptions+ ) {+ super(sequelize, { modelName: 'VideoChannelSyncModel', tableName: 'videoChannelSync' }, options)+ }++ // ---------------------------------------------------------------------------++ protected buildSubQueryWhere () {+ const where: string[] = []++ this.buildChannelJoin()++ if (this.options.includeCollaborations) {+ this.buildChannelCollaboratorsJoin()++ where.push(+ `("VideoChannel"."accountId" = :accountId OR "VideoChannel->VideoChannelCollaborators"."accountId" = :accountId)`+ )++ this.replacements.accountId = this.options.accountId+ } else {+ where.push(`"VideoChannel"."accountId" = :accountId`)++ this.replacements.accountId = this.options.accountId+ }++ if (where.length !== 0) {+ this.subQueryWhere = `WHERE ${where.join(' AND ')}`+ }+ }++ // ---------------------------------------------------------------------------++ private buildChannelJoin () {+ if (this.builtChannelJoin) return++ this.subQueryJoin += getChannelJoin({ on: `"VideoChannelSyncModel"."videoChannelId"` })+ this.builtChannelJoin = true+ }++ private buildChannelCollaboratorsJoin () {+ if (this.builtChannelCollaboratorsJoin) return++ this.subQueryJoin += ' LEFT JOIN "videoChannelCollaborator" "VideoChannel->VideoChannelCollaborators" ' ++ 'ON "VideoChannel->VideoChannelCollaborators"."channelId" = "VideoChannel"."id" ' ++ 'AND "VideoChannel->VideoChannelCollaborators"."state" = :channelCollaboratorState ' ++ // Ensure we join with max 1 collaborator to not duplicate rows+ 'AND "VideoChannel->VideoChannelCollaborators"."accountId" = :accountId '++ this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED+ this.replacements.accountId = this.options.accountId++ this.builtChannelCollaboratorsJoin = true+ }++ private buildChannelAvatarsJoin () {+ if (this.builtChannelAvatarsJoin) return++ this.join += getAvatarsJoin({ base: 'VideoChannel->Actor->', on: `"VideoChannelSyncModel"."VideoChannel.Actor.id"` })++ this.builtChannelAvatarsJoin = true+ }++ // ---------------------------------------------------------------------------++ protected buildQueryJoin () {+ this.buildChannelAvatarsJoin()+ }++ protected buildQueryAttributes () {+ this.attributes = [+ ...this.attributes,++ this.tableAttributes.getChannelAvatarAttributes()+ ]+ }++ protected buildSubQueryJoin () {+ this.buildChannelJoin()+ }++ protected buildSubQueryAttributes () {+ this.subQueryAttributes = [+ ...this.subQueryAttributes,++ this.tableAttributes.getVideoChannelSyncAttributes(),++ this.tableAttributes.getChannelAttributes(),+ this.tableAttributes.getChannelActorAttributes(),+ this.tableAttributes.getChannelServerAttributes()+ ]+ }++ protected getSort (sort: string): OrderItem[] {+ return getChannelSyncSort(sort)+ }+}diff --git a/server/core/models/video/sql/video-channel-sync/video-channel-sync-table-attributes.ts b/server/core/models/video/sql/video-channel-sync/video-channel-sync-table-attributes.tsnew file mode 100644index 0000000000..259905bfe6--- /dev/null+++ b/server/core/models/video/sql/video-channel-sync/video-channel-sync-table-attributes.ts@@ -0,0 +1,35 @@+import { Memoize } from '@server/helpers/memoize.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 { VideoChannelSyncModel } from '../../video-channel-sync.js'+import { VideoChannelModel } from '../../video-channel.js'++export class VideoChannelSyncTableAttributes {+ @Memoize()+ getVideoChannelSyncAttributes () {+ return VideoChannelSyncModel.getSQLAttributes('VideoChannelSyncModel').join(', ')+ }++ // ---------------------------------------------------------------------------++ @Memoize()+ getChannelAttributes () {+ return VideoChannelModel.getSQLSummaryAttributes('VideoChannel', `VideoChannel.`).join(', ')+ }++ @Memoize()+ getChannelActorAttributes () {+ return ActorModel.getSQLAPIAttributes('VideoChannel->Actor', `VideoChannel.Actor.`).join(', ')+ }++ @Memoize()+ getChannelServerAttributes () {+ return ServerModel.getSQLSummaryAttributes('VideoChannel->Actor->Server', `VideoChannel.Actor.Server.`).join(', ')+ }++ @Memoize()+ getChannelAvatarAttributes () {+ return ActorImageModel.getSQLAttributes('VideoChannel->Actor->Avatars', 'VideoChannel.Actor.Avatars.').join(', ')+ }+}diff --git a/server/core/models/video/sql/video/videos-id-list-query-builder.ts b/server/core/models/video/sql/video/videos-id-list-query-builder.tsindex 622b4ea139..8327426c0d 100644--- a/server/core/models/video/sql/video/videos-id-list-query-builder.ts+++ b/server/core/models/video/sql/video/videos-id-list-query-builder.ts@@ -1,5 +1,12 @@import { forceNumber } from '@peertube/peertube-core-utils'-import { VideoInclude, VideoIncludeType, VideoPrivacy, VideoPrivacyType, VideoState } from '@peertube/peertube-models'+import {+ VideoChannelCollaboratorState,+ VideoInclude,+ VideoIncludeType,+ VideoPrivacy,+ VideoPrivacyType,+ VideoState+} from '@peertube/peertube-models'import { exists } from '@server/helpers/custom-validators/misc.js'import { WEBSERVER } from '@server/initializers/constants.js'import { buildSortDirectionAndField } from '@server/models/shared/index.js'@@ -58,6 +65,7 @@ export type BuildVideosListQueryOptions = {hasWebVideoFiles?: booleanaccountId?: number+ includeCollaborations?: booleanvideoChannelId?: numberchannelNameOneOf?: string[]@@ -177,14 +185,14 @@ export class VideosIdListQueryBuilder extends AbstractRunQuery {}if (options.accountId) {- this.whereAccountId(options.accountId)+ this.whereAccountId({ accountId: options.accountId, includeCollaborations: options.includeCollaborations })}if (options.videoChannelId) {this.whereChannelId(options.videoChannelId)}- if (options.channelNameOneOf) {+ if (options.channelNameOneOf && options.channelNameOneOf.length !== 0) {this.whereChannelOneOf(options.channelNameOneOf)}@@ -405,9 +413,27 @@ export class VideosIdListQueryBuilder extends AbstractRunQuery {this.replacements.host = host}- private whereAccountId (accountId: number) {- this.and.push('"account"."id" = :accountId')- this.replacements.accountId = accountId+ private whereAccountId (options: {+ accountId: number+ includeCollaborations: boolean+ }) {+ if (options.includeCollaborations !== true) {+ this.and.push('"account"."id" = :accountId')+ this.replacements.accountId = options.accountId+ return+ }++ this.joins.push(+ 'LEFT JOIN "videoChannelCollaborator" ON "videoChannelCollaborator"."channelId" = "videoChannel".id ' ++ 'AND "videoChannelCollaborator"."state" = :channelCollaboratorState ' ++ // Ensure we join with max 1 collaborator to not duplicate rows+ 'AND "videoChannelCollaborator"."accountId" = :accountId'+ )++ this.and.push('("account"."id" = :accountId OR "videoChannelCollaborator"."accountId" = :accountId)')++ this.replacements.accountId = options.accountId+ this.replacements.channelCollaboratorState = VideoChannelCollaboratorState.ACCEPTED}private whereChannelId (channelId: number) {diff --git a/server/core/models/video/storyboard.ts b/server/core/models/video/storyboard.tsindex 00ce7b1d68..c2685dde5b 100644--- a/server/core/models/video/storyboard.ts+++ b/server/core/models/video/storyboard.ts@@ -133,7 +133,7 @@ export class StoryboardModel extends SequelizeModel<StoryboardModel> {// ---------------------------------------------------------------------------getOriginFileUrl (video: MVideo) {- if (video.isOwned()) {+ if (video.isLocal()) {return WEBSERVER.URL + this.getLocalStaticPath()}diff --git a/server/core/models/video/tag.ts b/server/core/models/video/tag.tsindex 9d69ab801f..f76f75ee12 100644--- a/server/core/models/video/tag.ts+++ b/server/core/models/video/tag.ts@@ -1,9 +1,9 @@import { VideoPrivacy, VideoState } from '@peertube/peertube-models'import { MTag } from '@server/types/models/video/tag.js'-import { QueryTypes, Transaction, col, fn } from 'sequelize'+import { col, fn, QueryTypes, Transaction } from 'sequelize'import { AllowNull, BelongsToMany, Column, Is, Table } from 'sequelize-typescript'import { isVideoTagValid } from '../../helpers/custom-validators/videos.js'-import { SequelizeModel, throwIfNotValid } from '../shared/index.js'+import { buildSQLAttributes, SequelizeModel, throwIfNotValid } from '../shared/index.js'import { VideoTagModel } from './video-tag.js'import { VideoModel } from './video.js'@@ -34,6 +34,18 @@ export class TagModel extends SequelizeModel<TagModel> {})declare Videos: Awaited<VideoModel>[]+ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ // ---------------------------------------------------------------------------+// threshold corresponds to how many video the field should have to be returnedstatic getRandomSamples (threshold: number, count: number): Promise<string[]> {const query = 'SELECT tag.name FROM tag ' +diff --git a/server/core/models/video/thumbnail.ts b/server/core/models/video/thumbnail.tsindex 27503ec080..6df4c20ccd 100644--- a/server/core/models/video/thumbnail.ts+++ b/server/core/models/video/thumbnail.ts@@ -20,9 +20,10 @@ import {import { logger } from '../../helpers/logger.js'import { CONFIG } from '../../initializers/config.js'import { CONSTRAINTS_FIELDS, LAZY_STATIC_PATHS, WEBSERVER } from '../../initializers/constants.js'+import { SequelizeModel } from '../shared/sequelize-type.js'+import { buildSQLAttributes } from '../shared/table.js'import { VideoPlaylistModel } from './video-playlist.js'import { VideoModel } from './video.js'-import { SequelizeModel } from '../shared/sequelize-type.js'@Table({tableName: 'thumbnail',@@ -132,6 +133,18 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {.catch(err => logger.error('Cannot remove thumbnail file %s.', instance.filename, { err }))}+ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ // ---------------------------------------------------------------------------+static loadByFilename (filename: string, thumbnailType: ThumbnailType_Type): Promise<MThumbnail> {const query = {where: {@@ -192,7 +205,7 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {const staticPath = ThumbnailModel.types[this.type].staticPath + this.filename// FIXME: typings- if ((videoOrPlaylist as MVideo).isOwned()) return WEBSERVER.URL + staticPath+ if ((videoOrPlaylist as MVideo).isLocal()) return WEBSERVER.URL + staticPathreturn this.fileUrl}@@ -223,7 +236,7 @@ export class ThumbnailModel extends SequelizeModel<ThumbnailModel> {this.previousThumbnailFilename = undefined}- isOwned () {+ isLocal () {return !this.fileUrl}diff --git a/server/core/models/video/video-caption.ts b/server/core/models/video/video-caption.tsindex 73edcd12df..06e1ef926f 100644--- a/server/core/models/video/video-caption.ts+++ b/server/core/models/video/video-caption.ts@@ -128,7 +128,7 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {instance.Video = await instance.$get('Video', { transaction: options.transaction })}- if (instance.isOwned()) {+ if (instance.isLocal()) {logger.info('Removing caption %s.', instance.filename)instance.removeAllCaptionFiles()@@ -278,7 +278,7 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {},automaticallyGenerated: this.automaticallyGenerated,- captionPath: this.Video.isOwned() && this.fileUrl+ captionPath: this.Video.isLocal() && this.fileUrl? null // On object storage: this.getFileStaticPath(),@@ -315,7 +315,7 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {// ---------------------------------------------------------------------------- isOwned () {+ isLocal () {return this.Video.remote === false}@@ -382,7 +382,7 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {// ---------------------------------------------------------------------------getFileUrl (this: MVideoCaptionUrl, video: MVideoOwned) {- if (video.isOwned() && this.storage === FileStorage.OBJECT_STORAGE) {+ if (video.isLocal() && this.storage === FileStorage.OBJECT_STORAGE) {return getObjectStoragePublicFileUrl(this.fileUrl, CONFIG.OBJECT_STORAGE.CAPTIONS)}@@ -390,7 +390,7 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {}getOriginFileUrl (this: MVideoCaptionUrl, video: MVideoOwned) {- if (video.isOwned()) return this.getFileUrl(video)+ if (video.isLocal()) return this.getFileUrl(video)return this.fileUrl}@@ -400,7 +400,7 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {getM3U8Url (this: MVideoCaptionUrl, video: MVideoOwned & MVideoPrivacy) {if (!this.m3u8Filename) return null- if (video.isOwned()) {+ if (video.isLocal()) {if (this.storage === FileStorage.OBJECT_STORAGE) {return getObjectStoragePublicFileUrl(this.m3u8Url, CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS)}diff --git a/server/core/models/video/video-channel-collaborator.ts b/server/core/models/video/video-channel-collaborator.tsnew file mode 100644index 0000000000..6deced8dbc--- /dev/null+++ b/server/core/models/video/video-channel-collaborator.ts@@ -0,0 +1,213 @@+import {+ VideoChannelCollaboratorState,+ type VideoChannelCollaborator,+ type VideoChannelCollaboratorStateType+} from '@peertube/peertube-models'+import { CHANNEL_COLLABORATOR_STATE } from '@server/initializers/constants.js'+import { MChannelCollaboratorAccount, MChannelId, MUserId } from '@server/types/models/index.js'+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'+}++@Table({+ tableName: 'videoChannelCollaborator',+ indexes: [+ {+ fields: [ 'channelId', 'accountId' ],+ unique: true+ }+ ]+})+@Scopes(() => ({+ [ScopeNames.WITH_ACCOUNT]: {+ include: [+ {+ model: AccountModel,+ required: true+ }+ ]+ }+}))+export class VideoChannelCollaboratorModel extends SequelizeModel<VideoChannelCollaboratorModel> {+ @CreatedAt+ declare createdAt: Date++ @UpdatedAt+ declare updatedAt: Date++ @AllowNull(false)+ @Column+ declare state: VideoChannelCollaboratorStateType++ @ForeignKey(() => AccountModel)+ @Column+ declare accountId: number++ @BelongsTo(() => AccountModel, {+ foreignKey: {+ name: 'accountId',+ allowNull: false+ },+ onDelete: 'cascade'+ })+ declare Account: Awaited<AccountModel>++ @ForeignKey(() => AccountModel)+ @Column+ declare channelId: number++ @BelongsTo(() => VideoChannelModel, {+ foreignKey: {+ name: 'channelId',+ allowNull: false+ },+ onDelete: 'cascade'+ })+ declare Channel: Awaited<VideoChannelModel>++ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ // ---------------------------------------------------------------------------++ static listForApi (options: {+ channelId: number+ start: number+ count: number+ sort: string+ }) {+ const { channelId, start, count, sort } = options++ const query = {+ offset: start,+ limit: count,+ order: getSort(sort),+ where: {+ channelId,+ state: {+ [Op.ne]: VideoChannelCollaboratorState.REJECTED+ }+ }+ }++ return Promise.all([+ VideoChannelCollaboratorModel.count(query),+ VideoChannelCollaboratorModel.scope([ ScopeNames.WITH_ACCOUNT ]).findAll<MChannelCollaboratorAccount>(query)+ ]).then(([ count, rows ]) => ({ total: count, data: rows }))+ }++ static countByChannel (channelId: number): Promise<number> {+ const query = {+ where: {+ channelId+ }+ }++ return VideoChannelCollaboratorModel.count(query)+ }++ static loadByChannelHandle (id: number, channelHandle: string): Promise<MChannelCollaboratorAccount> {+ return VideoChannelCollaboratorModel+ .scope([ ScopeNames.WITH_ACCOUNT ])+ .findOne({+ where: { id },+ include: [+ {+ model: VideoChannelModel.unscoped(),+ attributes: [ 'id' ],+ required: true,+ include: [+ {+ model: ActorModel.unscoped(),+ required: true,+ where: {+ preferredUsername: channelHandle+ }+ }+ ]+ }+ ]+ })+ }++ static loadByCollaboratorAccountName (options: {+ channelId: number+ accountName: string+ }): Promise<MChannelCollaboratorAccount | null> {+ const { channelId, accountName } = options++ return VideoChannelCollaboratorModel.findOne({+ where: {+ channelId+ },+ include: [+ {+ model: AccountModel.unscoped(),+ required: true,+ include: [+ {+ model: ActorModel.unscoped(),+ required: true,+ where: {+ preferredUsername: accountName+ }+ }+ ]+ }+ ]+ })+ }++ static async isCollaborator (options: {+ user: MUserId+ channel: MChannelId+ }): Promise<boolean> {+ const { user, channel } = options++ const query = `SELECT 1 FROM "videoChannelCollaborator" ` ++ `INNER JOIN "account" ON "account"."id" = "videoChannelCollaborator"."accountId" AND account."userId" = $userId ` ++ `WHERE "videoChannelCollaborator"."channelId" = $channelId AND "state" = $state ` ++ `LIMIT 1`++ return doesExist({+ sequelize: this.sequelize,+ query,+ bind: { userId: user.id, channelId: channel.id, state: VideoChannelCollaboratorState.ACCEPTED }+ })+ }++ // ---------------------------------------------------------------------------++ static getStateLabel (state: VideoChannelCollaboratorStateType) {+ return CHANNEL_COLLABORATOR_STATE[state]+ }++ toFormattedJSON (this: MChannelCollaboratorAccount): VideoChannelCollaborator {+ return {+ id: this.id,++ state: {+ id: this.state,+ label: VideoChannelCollaboratorModel.getStateLabel(this.state)+ },++ account: this.Account.toFormattedJSON(),+ updatedAt: this.updatedAt.toISOString(),+ createdAt: this.createdAt.toISOString()+ }+ }+}diff --git a/server/core/models/video/video-channel-sync.ts b/server/core/models/video/video-channel-sync.tsindex f3f7e09fc5..4a8fafe53a 100644--- a/server/core/models/video/video-channel-sync.ts+++ b/server/core/models/video/video-channel-sync.ts@@ -18,8 +18,9 @@ import {UpdatedAt} from 'sequelize-typescript'import { AccountModel } from '../account/account.js'-import { SequelizeModel, getChannelSyncSort, throwIfNotValid } from '../shared/index.js'+import { SequelizeModel, buildSQLAttributes, throwIfNotValid } from '../shared/index.js'import { UserModel } from '../user/user.js'+import { VideoChannelSyncListQueryBuilder } from './sql/video-channel-sync/video-channel-sync-list-query-builder.js'import { VideoChannelModel } from './video-channel.js'@DefaultScope(() => ({@@ -73,57 +74,35 @@ export class VideoChannelSyncModel extends SequelizeModel<VideoChannelSyncModel>})declare VideoChannel: Awaited<VideoChannelModel>+ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ // ---------------------------------------------------------------------------+static listByAccountForAPI (options: {accountId: numberstart: numbercount: numbersort: string+ includeCollaborations: boolean}) {- const getQuery = (forCount: boolean) => {- const videoChannelModel = forCount- ? VideoChannelModel.unscoped()- : VideoChannelModel-- return {- offset: options.start,- limit: options.count,- order: getChannelSyncSort(options.sort),- include: [- {- model: videoChannelModel,- required: true,- where: {- accountId: options.accountId- }- }- ]- }- }-return Promise.all([- VideoChannelSyncModel.unscoped().count(getQuery(true)),- VideoChannelSyncModel.unscoped().findAll(getQuery(false))- ]).then(([ total, data ]) => ({ total, data }))+ new VideoChannelSyncListQueryBuilder(VideoChannelSyncModel.sequelize, options).list<MChannelSyncFormattable>(),+ new VideoChannelSyncListQueryBuilder(VideoChannelSyncModel.sequelize, options).count()+ ]).then(([ rows, count ]) => {+ return { total: count, data: rows }+ })}static countByAccount (accountId: number) {- const query = {- include: [- {- model: VideoChannelModel.unscoped(),- required: true,- where: {- accountId- }- }- ]- }-- return VideoChannelSyncModel.unscoped().count(query)- }-- static loadWithChannel (id: number): Promise<MChannelSyncChannel> {- return VideoChannelSyncModel.findByPk(id)+ return new VideoChannelSyncListQueryBuilder(VideoChannelSyncModel.sequelize, { accountId }).count()}static async listSyncs (): Promise<MChannelSync[]> {@@ -157,6 +136,12 @@ export class VideoChannelSyncModel extends SequelizeModel<VideoChannelSyncModel>return VideoChannelSyncModel.unscoped().findAll(query)}+ static loadWithChannel (id: number): Promise<MChannelSyncChannel> {+ return VideoChannelSyncModel.findByPk(id)+ }++ // ---------------------------------------------------------------------------+toFormattedJSON (this: MChannelSyncFormattable): VideoChannelSync {return {id: this.id,diff --git a/server/core/models/video/video-channel.ts b/server/core/models/video/video-channel.tsindex e7d87e8ff7..28ad2a757b 100644--- a/server/core/models/video/video-channel.ts+++ b/server/core/models/video/video-channel.ts@@ -1,9 +1,9 @@-import { forceNumber, pick } from '@peertube/peertube-core-utils'import { ActivityPubActor, VideoChannel, VideoChannelSummary, VideoPrivacy } from '@peertube/peertube-models'+import { AttributesOnly } from '@peertube/peertube-typescript-utils'import { CONFIG } from '@server/initializers/config.js'import { InternalEventEmitter } from '@server/lib/internal-event-emitter.js'import { MAccountIdHost } from '@server/types/models/index.js'-import { FindOptions, Includeable, literal, Op, QueryTypes, ScopeOptions, Transaction, WhereOptions } from 'sequelize'+import { FindOptions, Includeable, literal, Op, QueryTypes, Transaction } from 'sequelize'import {AfterCreate,AfterDestroy,@@ -20,7 +20,6 @@ import {HasMany,Is,Scopes,- Sequelize,Table,UpdatedAt} from 'sequelize-typescript'@@ -44,40 +43,22 @@ import {import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account.js'import { ActorFollowModel } from '../actor/actor-follow.js'import { ActorImageModel } from '../actor/actor-image.js'-import { ActorModel, unusedActorAttributesForAPI } from '../actor/actor.js'-import { ServerModel } from '../server/server.js'-import {- buildServerIdsFollowedBy,- buildTrigramSearchIndex,- createSimilarityAttribute,- getSort,- SequelizeModel,- setAsUpdated,- throwIfNotValid-} from '../shared/index.js'+import { ActorModel, actorSummaryAttributes } from '../actor/actor.js'+import { ServerModel, serverSummaryAttributes } from '../server/server.js'+import { buildSQLAttributes, buildTrigramSearchIndex, getSort, SequelizeModel, setAsUpdated, throwIfNotValid } from '../shared/index.js'+import { ListVideoChannelsOptions, VideoChannelListQueryBuilder } from './sql/channel/video-channel-list-query-builder.js'+import { VideoChannelCollaboratorModel } from './video-channel-collaborator.js'import { VideoPlaylistModel } from './video-playlist.js'import { VideoModel } from './video.js'+const channelSummaryAttributes = [ 'id', 'name', 'description', 'actorId' ] as const satisfies (keyof AttributesOnly<AccountModel>)[]+export enum ScopeNames {- FOR_API = 'FOR_API',SUMMARY = 'SUMMARY',WITH_ACCOUNT = 'WITH_ACCOUNT',WITH_ACTOR = 'WITH_ACTOR',WITH_ACTOR_BANNER = 'WITH_ACTOR_BANNER',- WITH_VIDEOS = 'WITH_VIDEOS',- WITH_STATS = 'WITH_STATS'-}--type AvailableForListOptions = {- actorId: number- search?: string- host?: string- handles?: string[]- forCount?: boolean-}--type AvailableWithStatsOptions = {- daysPrior: number+ WITH_VIDEOS = 'WITH_VIDEOS'}export type SummaryOptions = {@@ -95,142 +76,15 @@ export type SummaryOptions = {]}))@Scopes(() => ({- [ScopeNames.FOR_API]: (options: AvailableForListOptions) => {- // Only list local channels OR channels that are on an instance followed by actorId- const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)-- const whereActorAnd: WhereOptions[] = [- {- [Op.or]: [- {- serverId: null- },- {- serverId: {- [Op.in]: Sequelize.literal(inQueryInstanceFollow)- }- }- ]- }- ]-- let serverRequired = false- let whereServer: WhereOptions-- if (options.host && options.host !== WEBSERVER.HOST) {- serverRequired = true- whereServer = { host: options.host }- }-- if (options.host === WEBSERVER.HOST) {- whereActorAnd.push({- serverId: null- })- }-- if (Array.isArray(options.handles) && options.handles.length !== 0) {- const or: string[] = []-- for (const handle of options.handles || []) {- const [ preferredUsername, host ] = handle.split('@')-- const sanitizedPreferredUsername = VideoChannelModel.sequelize.escape(preferredUsername.toLowerCase())- const sanitizedHost = VideoChannelModel.sequelize.escape(host)-- if (!host || host === WEBSERVER.HOST) {- or.push(`(LOWER("preferredUsername") = ${sanitizedPreferredUsername} AND "serverId" IS NULL)`)- } else {- or.push(- `(` +- `LOWER("preferredUsername") = ${sanitizedPreferredUsername} ` +- `AND "host" = ${sanitizedHost}` +- `)`- )- }- }-- whereActorAnd.push({- id: {- [Op.in]: literal(`(SELECT "actor".id FROM actor LEFT JOIN server on server.id = actor."serverId" WHERE ${or.join(' OR ')})`)- }- })- }-- const channelActorInclude: Includeable[] = []- const accountActorInclude: Includeable[] = []-- if (options.forCount !== true) {- accountActorInclude.push({- model: ServerModel,- required: false- })-- accountActorInclude.push({- model: ActorImageModel,- as: 'Avatars',- required: false- })-- channelActorInclude.push({- model: ActorImageModel,- as: 'Avatars',- required: false- })-- channelActorInclude.push({- model: ActorImageModel,- as: 'Banners',- required: false- })- }-- if (options.forCount !== true || serverRequired) {- channelActorInclude.push({- model: ServerModel,- duplicating: false,- required: serverRequired,- where: whereServer- })- }-- return {- include: [- {- attributes: {- exclude: unusedActorAttributesForAPI- },- model: ActorModel.unscoped(),- where: {- [Op.and]: whereActorAnd- },- include: channelActorInclude- },- {- model: AccountModel.unscoped(),- required: true,- include: [- {- attributes: {- exclude: unusedActorAttributesForAPI- },- model: ActorModel.unscoped(),- required: true,- include: accountActorInclude- }- ]- }- ]- }- },[ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {const include: Includeable[] = [{- attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],+ attributes: actorSummaryAttributes,model: ActorModel.unscoped(),required: options.actorRequired ?? true,include: [{- attributes: [ 'host' ],+ attributes: serverSummaryAttributes,model: ServerModel.unscoped(),required: false},@@ -244,7 +98,7 @@ export type SummaryOptions = {]const base: FindOptions = {- attributes: [ 'id', 'name', 'description', 'actorId' ]+ attributes: channelSummaryAttributes}if (options.withAccount === true) {@@ -291,53 +145,6 @@ export type SummaryOptions = {include: [VideoModel]- },- [ScopeNames.WITH_STATS]: (options: AvailableWithStatsOptions = { daysPrior: 30 }) => {- const daysPrior = forceNumber(options.daysPrior)-- return {- attributes: {- include: [- [- literal('(SELECT COUNT(*) FROM "video" WHERE "channelId" = "VideoChannelModel"."id")'),- 'videosCount'- ],- [- literal(- '(' +- `SELECT string_agg(concat_ws('|', t.day, t.views), ',') ` +- 'FROM ( ' +- 'WITH ' +- 'days AS ( ' +- `SELECT generate_series(date_trunc('day', now()) - '${daysPrior} day'::interval, ` +- `date_trunc('day', now()), '1 day'::interval) AS day ` +- ') ' +- 'SELECT days.day AS day, COALESCE(SUM("videoView".views), 0) AS views ' +- 'FROM days ' +- 'LEFT JOIN (' +- '"videoView" INNER JOIN "video" ON "videoView"."videoId" = "video"."id" ' +- 'AND "video"."channelId" = "VideoChannelModel"."id"' +- `) ON date_trunc('day', "videoView"."startDate") = date_trunc('day', days.day) ` +- 'GROUP BY day ' +- 'ORDER BY day ' +- ') t' +- ')'- ),- 'viewsPerDay'- ],- [- literal(- '(' +- 'SELECT COALESCE(SUM("video".views), 0) AS totalViews ' +- 'FROM "video" ' +- 'WHERE "video"."channelId" = "VideoChannelModel"."id"' +- ')'- ),- 'totalViews'- ]- ]- }- }}}))@Table({@@ -419,6 +226,12 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {})declare VideoPlaylists: Awaited<VideoPlaylistModel>[]+ @HasMany(() => VideoChannelCollaboratorModel, {+ foreignKey: 'accountId',+ onDelete: 'CASCADE'+ })+ declare VideoChannelCollaborators: Awaited<VideoChannelCollaboratorModel>[]+@AfterCreatestatic notifyCreate (channel: MChannel) {InternalEventEmitter.Instance.emit('channel-created', { channel })@@ -442,7 +255,7 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)- if (instance.Actor.isOwned()) {+ if (instance.Actor.isLocal()) {return sendDeleteActor(instance.Actor, options.transaction)}@@ -461,6 +274,27 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {}}+ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix,+ includeAttributes: channelSummaryAttributes+ })+ }++ // ---------------------------------------------------------------------------+static countByAccount (accountId: number) {const query = {where: {@@ -536,147 +370,32 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {.findAll(query)}- static listForApi (- parameters: Pick<AvailableForListOptions, 'actorId'> & {- start: number- count: number- sort: string- }- ) {- const { actorId } = parameters-- const query = {- offset: parameters.start,- limit: parameters.count,- order: getSort(parameters.sort)- }-- const getScope = (forCount: boolean) => {- return { method: [ ScopeNames.FOR_API, { actorId, forCount } as AvailableForListOptions ] }- }+ // ---------------------------------------------------------------------------+ static listForApi (options: ListVideoChannelsOptions) {return Promise.all([- VideoChannelModel.scope(getScope(true)).count(),- VideoChannelModel.scope(getScope(false)).findAll(query)- ]).then(([ total, data ]) => ({ total, data }))+ new VideoChannelListQueryBuilder(VideoChannelModel.sequelize, options).list<VideoChannelModel>() as Promise<MChannelFormattable[]>,+ new VideoChannelListQueryBuilder(VideoChannelModel.sequelize, options).count()+ ]).then(([ rows, count ]) => {+ return { total: count, data: rows }+ })}- static searchForApi (- options: Pick<AvailableForListOptions, 'actorId' | 'search' | 'host' | 'handles'> & {- start: number- count: number- sort: string+ static listByAccountForAPI (+ options: Pick<ListVideoChannelsOptions, 'accountId' | 'includeCollaborations' | 'search' | 'start' | 'count' | 'sort'> & {+ withStats?: boolean}) {- let attributesInclude: any[] = [ literal('0 as similarity') ]- let where: WhereOptions-- if (options.search) {- const escapedSearch = VideoChannelModel.sequelize.escape(options.search)- const escapedLikeSearch = VideoChannelModel.sequelize.escape('%' + options.search + '%')- attributesInclude = [ createSimilarityAttribute('VideoChannelModel.name', options.search) ]-- where = {- [Op.or]: [- Sequelize.literal(- 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'- ),- Sequelize.literal(- 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'- )- ]- }- }-- const query = {- attributes: {- include: attributesInclude- },- offset: options.start,- limit: options.count,- order: getSort(options.sort),- where- }+ const listOptions = options.withStats+ ? { ...options, statsDaysPrior: 30 }+ : options- const getScope = (forCount: boolean) => {- return {- method: [- ScopeNames.FOR_API,- {- ...pick(options, [ 'actorId', 'host', 'handles' ]),-- forCount- } as AvailableForListOptions- ]- }- }-- return Promise.all([- VideoChannelModel.scope(getScope(true)).count(query),- VideoChannelModel.scope(getScope(false)).findAll(query)- ]).then(([ total, data ]) => ({ total, data }))+ return this.listForApi(listOptions)}- static listByAccountForAPI (options: {- accountId: number- start: number- count: number- sort: string- withStats?: boolean- search?: string- }) {- const escapedSearch = VideoModel.sequelize.escape(options.search)- const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')- const where = options.search- ? {- [Op.or]: [- Sequelize.literal(- 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'- ),- Sequelize.literal(- 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'- )- ]- }- : null-- const getQuery = (forCount: boolean) => {- const accountModel = forCount- ? AccountModel.unscoped()- : AccountModel-- return {- offset: options.start,- limit: options.count,- order: getSort(options.sort),- include: [- {- model: accountModel,- where: {- id: options.accountId- },- required: true- }- ],- where- }- }+ // ---------------------------------------------------------------------------- const findScopes: string | ScopeOptions | (string | ScopeOptions)[] = [ ScopeNames.WITH_ACTOR_BANNER ]-- if (options.withStats === true) {- findScopes.push({- method: [ ScopeNames.WITH_STATS, { daysPrior: 30 } as AvailableWithStatsOptions ]- })- }-- return Promise.all([- VideoChannelModel.unscoped().count(getQuery(true)),- VideoChannelModel.scope(findScopes).findAll(getQuery(false))- ]).then(([ total, data ]) => ({ total, data }))- }-- static listAllByAccount (accountId: number): Promise<MChannelDefault[]> {+ static listAllOwnedByAccount (accountId: number): Promise<MChannelDefault[]> {const query = {limit: CONFIG.VIDEO_CHANNELS.MAX_PER_USER,include: [@@ -828,7 +547,7 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {displayName: this.getDisplayName(),description: this.description,support: this.support,- isLocal: this.Actor.isOwned(),+ isLocal: this.Actor.isLocal(),updatedAt: this.updatedAt,ownerAccount: undefined,@@ -890,6 +609,10 @@ export class VideoChannelModel extends SequelizeModel<VideoChannelModel> {return WEBSERVER.URL + '/c/' + this.Actor.getIdentifier() + suffix}+ getClientManageUrl (this: MAccountIdHost | MChannelIdHost) {+ return WEBSERVER.URL + '/my-library/video-channels/manage/' + this.Actor.getIdentifier()+ }+getDisplayName () {return this.name}diff --git a/server/core/models/video/video-comment.ts b/server/core/models/video/video-comment.tsindex 862e98110d..c8dd73d1b9 100644--- a/server/core/models/video/video-comment.ts+++ b/server/core/models/video/video-comment.ts@@ -259,7 +259,7 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {heldForReview: false,notDeleted: true,transaction- }).countComments()+ }).count()await video.save({ transaction })})@@ -340,7 +340,7 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {// ---------------------------------------------------------------------------- static listCommentsForApi (parameters: {+ static listForApi (parameters: {start: numbercount: numbersort: string@@ -348,6 +348,8 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {autoTagOfAccountId: numbervideoAccountOwnerId?: number+ videoAccountOwnerIncludeCollaborations?: boolean+videoChannelOwnerId?: numberonLocalVideo?: boolean@@ -378,6 +380,7 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {'autoTagOneOf','autoTagOfAccountId','videoAccountOwnerId',+ 'videoAccountOwnerIncludeCollaborations','videoChannelOwnerId','heldForReview']),@@ -387,8 +390,8 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {}return Promise.all([- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentAdminOrUserFormattable>(),- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MCommentAdminOrUserFormattable>(),+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).count()]).then(([ rows, count ]) => {return { total: count, data: rows }})@@ -437,9 +440,9 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {}return Promise.all([- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, listOptions).listComments<MCommentAdminOrUserFormattable>(),- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, countOptions).countComments(),- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, notDeletedCountOptions).countComments()+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, listOptions).list<MCommentAdminOrUserFormattable>(),+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, countOptions).count(),+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, notDeletedCountOptions).count()]).then(([ rows, count, totalNotDeletedComments ]) => {return { total: count, data: rows, totalNotDeletedComments }})@@ -471,8 +474,8 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {}return Promise.all([- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentAdminOrUserFormattable>(),- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MCommentAdminOrUserFormattable>(),+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).count()]).then(([ rows, count ]) => {return { total: count, data: rows }})@@ -533,8 +536,8 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {}return Promise.all([- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MComment>(),- new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).countComments()+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MComment>(),+ new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).count()]).then(([ rows, count ]) => {return { total: count, data: rows }})@@ -563,15 +566,22 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {blockerAccountIds}- return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MCommentOwnerVideoFeed>()+ return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MCommentOwnerVideoFeed>()}- static listForBulkDelete (ofAccount: MAccount, filter: { onVideosOfAccount?: MAccountId } = {}) {+ static listForBulkDelete (+ ofAccount: MAccount,+ filter: {+ onVideosOfAccount?: MAccountId+ includeCollaborations?: boolean+ } = {}+ ) {const queryOptions: ListVideoCommentsOptions = {selectType: 'comment-only',accountId: ofAccount.id,videoAccountOwnerId: filter.onVideosOfAccount?.id,+ videoAccountOwnerIncludeCollaborations: filter.includeCollaborations,heldForReview: undefined,@@ -579,7 +589,7 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {count: 5000}- return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).listComments<MComment>()+ return new VideoCommentListQueryBuilder(VideoCommentModel.sequelize, queryOptions).list<MComment>()}static listForExport (ofAccountId: number): Promise<MCommentExport[]> {@@ -686,10 +696,10 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {return this.originCommentId || this.id}- isOwned () {+ isLocal () {if (!this.Account) return false- return this.Account.isOwned()+ return this.Account.isLocal()}markAsDeleted () {@@ -703,7 +713,7 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {}extractMentions () {- return extractMentions(this.text, this.isOwned())+ return extractMentions(this.text, this.isLocal())}toFormattedJSON (this: MCommentFormattable) {@@ -752,7 +762,9 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {video: {id: this.Video.id,uuid: this.Video.uuid,- name: this.Video.name+ name: this.Video.name,++ channel: this.Video.VideoChannel.toFormattedSummaryJSON()},account: this.Account@@ -792,7 +804,7 @@ export class VideoCommentModel extends SequelizeModel<VideoCommentModel> {}let replyApproval = this.replyApproval- if (this.Video.isOwned() && !this.heldForReview) {+ if (this.Video.isLocal() && !this.heldForReview) {replyApproval = getLocalApproveReplyActivityPubUrl(this.Video, this)}diff --git a/server/core/models/video/video-file.ts b/server/core/models/video/video-file.tsindex 3da015762a..d6650155b8 100644--- a/server/core/models/video/video-file.ts+++ b/server/core/models/video/video-file.ts@@ -527,7 +527,7 @@ export class VideoFileModel extends SequelizeModel<VideoFileModel> {// ---------------------------------------------------------------------------getFileUrl (video: MVideo) {- if (video.isOwned()) {+ if (video.isLocal()) {if (this.storage === FileStorage.OBJECT_STORAGE) {return this.getObjectStorageUrl(video)}@@ -569,14 +569,14 @@ export class VideoFileModel extends SequelizeModel<VideoFileModel> {? join(DOWNLOAD_PATHS.HLS_VIDEOS, `${video.uuid}-${this.resolution}-fragmented${this.extname}`): join(DOWNLOAD_PATHS.WEB_VIDEOS, `${video.uuid}-${this.resolution}${this.extname}`)- if (video.isOwned()) return WEBSERVER.URL + path+ if (video.isLocal()) return WEBSERVER.URL + path// FIXME: don't guess remote URLreturn buildRemoteUrl(video, path)}getRemoteTorrentUrl (video: MVideo) {- if (video.isOwned()) throw new Error(`Video ${video.url} is not a remote video`)+ if (video.isLocal()) throw new Error(`Video ${video.url} is not a remote video`)return this.torrentUrl}diff --git a/server/core/models/video/video-import.ts b/server/core/models/video/video-import.tsindex 4d366fc580..1b50961ded 100644--- a/server/core/models/video/video-import.ts+++ b/server/core/models/video/video-import.ts@@ -1,7 +1,7 @@import { VideoImport, VideoImportState, type VideoImportStateType } from '@peertube/peertube-models'import { afterCommitIfTransaction } from '@server/helpers/database-utils.js'import { MVideoImportDefault, MVideoImportFormattable } from '@server/types/models/video/video-import.js'-import { IncludeOptions, Op, WhereOptions } from 'sequelize'+import { Op } from 'sequelize'import {AfterUpdate,AllowNull,@@ -19,8 +19,9 @@ import {import { isVideoImportStateValid, isVideoImportTargetUrlValid } from '../../helpers/custom-validators/video-imports.js'import { isVideoMagnetUriValid } from '../../helpers/custom-validators/videos.js'import { CONSTRAINTS_FIELDS, VIDEO_IMPORT_STATES } from '../../initializers/constants.js'-import { SequelizeModel, getSort, searchAttribute, throwIfNotValid } from '../shared/index.js'+import { buildSQLAttributes, SequelizeModel, throwIfNotValid } from '../shared/index.js'import { UserModel } from '../user/user.js'+import { ListVideoImportsOptions, VideoImportListQueryBuilder } from './sql/import/video-import-list-query-builder.js'import { VideoChannelSyncModel } from './video-channel-sync.js'import { VideoModel, ScopeNames as VideoModelScopeNames } from './video.js'@@ -140,72 +141,29 @@ export class VideoImportModel extends SequelizeModel<VideoImportModel> {return undefined}- static loadAndPopulateVideo (id: number): Promise<MVideoImportDefault> {- return VideoImportModel.findByPk(id)- }+ // ---------------------------------------------------------------------------- static listUserVideoImportsForApi (options: {- userId: number- start: number- count: number- sort: string-- search?: string- targetUrl?: string- videoChannelSyncId?: number- }) {- const { userId, start, count, sort, targetUrl, videoChannelSyncId, search } = options-- const where: WhereOptions = [ { userId } ]- const include: IncludeOptions[] = [- {- attributes: [ 'id' ],- model: UserModel.unscoped(), // FIXME: Without this, sequelize try to COUNT(DISTINCT(*)) which is an invalid SQL query- required: true- },- {- model: VideoChannelSyncModel.unscoped(),- required: false- }- ]-- if (targetUrl) where.push({ targetUrl })- if (videoChannelSyncId) where.push({ videoChannelSyncId })-- if (search) {- include.push({- model: defaultVideoScope(),- required: false- })+ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }- where.push({- [Op.or]: [- searchAttribute(search, '$Video.name$'),- searchAttribute(search, 'targetUrl'),- searchAttribute(search, 'torrentName'),- searchAttribute(search, 'magnetUri')- ]- })- } else {- include.push({- model: defaultVideoScope(),- required: false- })- }+ // ---------------------------------------------------------------------------- const query = {- distinct: true,- include,- offset: start,- limit: count,- order: getSort(sort),- where- }+ static loadAndPopulateVideo (id: number): Promise<MVideoImportDefault> {+ return VideoImportModel.findByPk(id)+ }+ static listUserVideoImportsForApi (options: ListVideoImportsOptions) {return Promise.all([- VideoImportModel.unscoped().count(query),- VideoImportModel.findAll<MVideoImportDefault>(query)- ]).then(([ total, data ]) => ({ total, data }))+ new VideoImportListQueryBuilder(VideoImportModel.sequelize, options).list<MVideoImportFormattable>(),+ new VideoImportListQueryBuilder(VideoImportModel.sequelize, options).count()+ ]).then(([ rows, count ]) => {+ return { total: count, data: rows }+ })}static async urlAlreadyImported (options: {diff --git a/server/core/models/video/video-playlist.ts b/server/core/models/video/video-playlist.tsindex 6afdaded21..28bf82ad99 100644--- a/server/core/models/video/video-playlist.ts+++ b/server/core/models/video/video-playlist.ts@@ -1,4 +1,4 @@-import { buildPlaylistEmbedPath, buildPlaylistWatchPath, pick } from '@peertube/peertube-core-utils'+import { buildPlaylistEmbedPath, buildPlaylistWatchPath } from '@peertube/peertube-core-utils'import {ActivityIconObject,PlaylistObject,@@ -12,7 +12,7 @@ import { buildUUID, uuidToShort } from '@peertube/peertube-node-utils'import { activityPubCollectionPagination } from '@server/lib/activitypub/collection.js'import { MAccountId, MChannelId, MVideoPlaylistElement } from '@server/types/models/index.js'import { join } from 'path'-import { FindOptions, Includeable, Op, ScopeOptions, Sequelize, Transaction, WhereOptions, literal } from 'sequelize'+import { FindOptions, Op, Transaction, literal } from 'sequelize'import {AllowNull,BelongsTo,@@ -55,26 +55,24 @@ import {MVideoPlaylistFullSummary,MVideoPlaylistSummaryWithElements} from '../../types/models/video/video-playlist.js'-import { AccountModel, ScopeNames as AccountScopeNames, SummaryOptions } from '../account/account.js'+import { AccountModel, ScopeNames as AccountScopeNames } from '../account/account.js'import { ActorModel } from '../actor/actor.js'import {SequelizeModel,- buildServerIdsFollowedBy,+ buildSQLAttributes,buildTrigramSearchIndex,buildWhereIdOrUUID,- createSimilarityAttribute,- getPlaylistSort,isOutdated,setAsUpdated,throwIfNotValid} from '../shared/index.js'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 { VideoChannelModel, ScopeNames as VideoChannelScopeNames } from './video-channel.js'import { VideoPlaylistElementModel } from './video-playlist-element.js'enum ScopeNames {- AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',WITH_VIDEOS_LENGTH = 'WITH_VIDEOS_LENGTH',WITH_ACCOUNT_AND_CHANNEL_SUMMARY = 'WITH_ACCOUNT_AND_CHANNEL_SUMMARY',WITH_ACCOUNT = 'WITH_ACCOUNT',@@ -82,20 +80,6 @@ enum ScopeNames {WITH_ACCOUNT_AND_CHANNEL = 'WITH_ACCOUNT_AND_CHANNEL'}-type AvailableForListOptions = {- followerActorId?: number- type?: VideoPlaylistType_Type- accountId?: number- videoChannelId?: number- listMyPlaylists?: boolean- search?: string- host?: string- uuids?: string[]- channelNameOneOf?: string[]- withVideos?: boolean- forCount?: boolean-}-function getVideoLengthSelect () {return 'SELECT COUNT("id") FROM "videoPlaylistElement" WHERE "videoPlaylistId" = "VideoPlaylistModel"."id"'}@@ -150,126 +134,6 @@ function getVideoLengthSelect () {required: false}]- },- [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {- const whereAnd: WhereOptions[] = []-- const whereServer = options.host && options.host !== WEBSERVER.HOST- ? { host: options.host }- : undefined-- let whereActor: WhereOptions = {}-- if (options.host === WEBSERVER.HOST) {- whereActor = {- [Op.and]: [ { serverId: null } ]- }- }-- if (options.listMyPlaylists !== true) {- whereAnd.push({- privacy: VideoPlaylistPrivacy.PUBLIC- })-- // … OR playlists that are on an instance followed by actorId- if (options.followerActorId) {- // Only list local playlists- const whereActorOr: WhereOptions[] = [- {- serverId: null- }- ]-- const inQueryInstanceFollow = buildServerIdsFollowedBy(options.followerActorId)-- whereActorOr.push({- serverId: {- [Op.in]: literal(inQueryInstanceFollow)- }- })-- Object.assign(whereActor, { [Op.or]: whereActorOr })- }- }-- if (options.accountId) {- whereAnd.push({- ownerAccountId: options.accountId- })- }-- if (options.videoChannelId) {- whereAnd.push({- videoChannelId: options.videoChannelId- })- }-- if (options.type) {- whereAnd.push({- type: options.type- })- }-- if (options.uuids) {- whereAnd.push({- uuid: {- [Op.in]: options.uuids- }- })- }-- if (options.withVideos === true) {- whereAnd.push(- literal(`(${getVideoLengthSelect()}) != 0`)- )- }-- let attributesInclude: any[] = [ literal('0 as similarity') ]-- if (options.search) {- const escapedSearch = VideoPlaylistModel.sequelize.escape(options.search)- const escapedLikeSearch = VideoPlaylistModel.sequelize.escape('%' + options.search + '%')- attributesInclude = [ createSimilarityAttribute('VideoPlaylistModel.name', options.search) ]-- whereAnd.push({- [Op.or]: [- Sequelize.literal(- 'lower(immutable_unaccent("VideoPlaylistModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'- ),- Sequelize.literal(- 'lower(immutable_unaccent("VideoPlaylistModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'- )- ]- })- }-- const where = {- [Op.and]: whereAnd- }-- const include: Includeable[] = [- {- model: AccountModel.scope({- method: [ AccountScopeNames.SUMMARY, { whereActor, whereServer, forCount: options.forCount } as SummaryOptions ]- }),- required: true- }- ]-- if (options.forCount !== true) {- include.push({- model: VideoChannelModel.scope(VideoChannelScopeNames.SUMMARY),- required: false- })- }-- return {- attributes: {- include: attributesInclude- },- where,- include- } as FindOptions}}))@Table({@@ -374,74 +238,38 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {})declare Thumbnail: Awaited<ThumbnailModel>- static listForApi (- options: AvailableForListOptions & {- start: number- count: number- sort: string- }- ) {- const query = {- offset: options.start,- limit: options.count,- order: getPlaylistSort(options.sort)- }-- const commonAvailableForListOptions = pick(options, [- 'type',- 'followerActorId',- 'accountId',- 'videoChannelId',- 'listMyPlaylists',- 'search',- 'host',- 'channelNameOneOf',- 'uuids'- ])-- const scopesFind: (string | ScopeOptions)[] = [- {- method: [- ScopeNames.AVAILABLE_FOR_LIST,- {- ...commonAvailableForListOptions,-- withVideos: options.withVideos || false- } as AvailableForListOptions- ]- },- ScopeNames.WITH_VIDEOS_LENGTH,- ScopeNames.WITH_THUMBNAIL- ]+ // ---------------------------------------------------------------------------- const scopesCount: (string | ScopeOptions)[] = [- {- method: [- ScopeNames.AVAILABLE_FOR_LIST,+ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }- {- ...commonAvailableForListOptions,+ static getSQLSummaryAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix,+ includeAttributes: [ 'id', 'name', 'type' ]+ })+ }- withVideos: options.withVideos || false,- forCount: true- } as AvailableForListOptions- ]- },- ScopeNames.WITH_VIDEOS_LENGTH- ]+ // ---------------------------------------------------------------------------+ static listForApi (options: ListVideoPlaylistsOptions) {return Promise.all([- VideoPlaylistModel.scope(scopesCount).count(),- VideoPlaylistModel.scope(scopesFind).findAll(query)- ]).then(([ count, rows ]) => ({ total: count, data: rows }))+ new VideoPlaylistListQueryBuilder(VideoPlaylistModel.sequelize, options).list<MVideoPlaylistFormattable>(),+ new VideoPlaylistListQueryBuilder(VideoPlaylistModel.sequelize, options).count()+ ]).then(([ rows, count ]) => {+ return { total: count, data: rows }+ })}static searchForApi (- options: Pick<AvailableForListOptions, 'followerActorId' | 'search' | 'host' | 'uuids'> & {- start: number- count: number- sort: string- }+ options: Pick<ListVideoPlaylistsOptions, 'followerActorId' | 'search' | 'host' | 'uuids' | 'start' | 'count' | 'sort'>) {return VideoPlaylistModel.listForApi({...options,@@ -783,12 +611,12 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {this.set('videosLength' as any, videosLength, { raw: true })}- isOwned () {- return this.OwnerAccount.isOwned()+ isLocal () {+ return this.OwnerAccount.isLocal()}isOutdated () {- if (this.isOwned()) return false+ if (this.isLocal()) return falsereturn isOutdated(this, ACTIVITY_PUB.VIDEO_PLAYLIST_REFRESH_INTERVAL)}@@ -799,7 +627,7 @@ export class VideoPlaylistModel extends SequelizeModel<VideoPlaylistModel> {uuid: this.uuid,shortUUID: uuidToShort(this.uuid),- isLocal: this.isOwned(),+ isLocal: this.isLocal(),url: this.url,diff --git a/server/core/models/video/video-streaming-playlist.ts b/server/core/models/video/video-streaming-playlist.tsindex bd78566970..29dec28b6a 100644--- a/server/core/models/video/video-streaming-playlist.ts+++ b/server/core/models/video/video-streaming-playlist.ts@@ -272,7 +272,7 @@ export class VideoStreamingPlaylistModel extends SequelizeModel<VideoStreamingPl// ---------------------------------------------------------------------------getMasterPlaylistUrl (video: MVideo) {- if (video.isOwned()) {+ if (video.isLocal()) {if (this.storage === FileStorage.OBJECT_STORAGE) {return this.getMasterPlaylistObjectStorageUrl(video)}@@ -294,7 +294,7 @@ export class VideoStreamingPlaylistModel extends SequelizeModel<VideoStreamingPl// ---------------------------------------------------------------------------getSha256SegmentsUrl (video: MVideo) {- if (video.isOwned()) {+ if (video.isLocal()) {if (!this.segmentsSha256Filename) return nullif (this.storage === FileStorage.OBJECT_STORAGE) {diff --git a/server/core/models/video/video-tag.ts b/server/core/models/video/video-tag.tsindex 5ed543873a..c3dd5e1ee9 100644--- a/server/core/models/video/video-tag.ts+++ b/server/core/models/video/video-tag.ts@@ -1,7 +1,7 @@import { Column, CreatedAt, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'+import { SequelizeModel } from '../shared/index.js'import { TagModel } from './tag.js'import { VideoModel } from './video.js'-import { SequelizeModel } from '../shared/index.js'@Table({tableName: 'videoTag',diff --git a/server/core/models/video/video.ts b/server/core/models/video/video.tsindex 84142cbe2d..a66e8aecb2 100644--- a/server/core/models/video/video.ts+++ b/server/core/models/video/video.ts@@ -122,6 +122,7 @@ import { TrackerModel } from '../server/tracker.js'import { VideoTrackerModel } from '../server/video-tracker.js'import {SequelizeModel,+ buildSQLAttributes,buildTrigramSearchIndex,buildWhereIdOrUUID,doesExist,@@ -826,7 +827,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {@BeforeDestroystatic async sendDelete (instance: MVideoAccountLight, options: { transaction: Transaction }) {- if (!instance.isOwned()) return undefined+ if (!instance.isLocal()) return undefined// Lazy load channelsif (!instance.VideoChannel) {@@ -848,7 +849,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {logger.info('Removing files of video ' + instance.url)- if (instance.isOwned()) {+ if (instance.isLocal()) {if (!Array.isArray(instance.VideoFiles)) {instance.VideoFiles = await instance.$get('VideoFiles', { transaction: options.transaction })}@@ -906,6 +907,18 @@ export class VideoModel extends SequelizeModel<VideoModel> {await Promise.all(tasks)}+ // ---------------------------------------------------------------------------++ static getSQLAttributes (tableName: string, aliasPrefix = '') {+ return buildSQLAttributes({+ model: this,+ tableName,+ aliasPrefix+ })+ }++ // ---------------------------------------------------------------------------+static listLocalIds (): Promise<number[]> {const query = {attributes: [ 'id' ],@@ -1102,6 +1115,8 @@ export class VideoModel extends SequelizeModel<VideoModel> {excludeAlreadyWatched?: boolean // default falseautoTagOneOf?: string[]++ includeCollaborations?: boolean // default false}) {VideoModel.throwIfPrivateIncludeWithoutUser(options)VideoModel.throwIfPrivacyOneOfWithoutUser(options)@@ -1131,6 +1146,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {'displayOnlyForFollower','hasFiles','accountId',+ 'includeCollaborations','videoChannelId','channelNameOneOf','videoPlaylistId',@@ -1848,7 +1864,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {// ---------------------------------------------------------------------------- isOwned (this: MVideoOwned) {+ isLocal (this: MVideoOwned) {return this.remote === false}@@ -2133,7 +2149,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {// ---------------------------------------------------------------------------isOutdated () {- if (this.isOwned()) return false+ if (this.isLocal()) return falsereturn isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)}@@ -2194,7 +2210,7 @@ export class VideoModel extends SequelizeModel<VideoModel> {}getTrackerUrls () {- if (this.isOwned()) {+ if (this.isLocal()) {return [WEBSERVER.URL + '/tracker/announce',WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket'diff --git a/server/core/types/express.d.ts b/server/core/types/express.d.tsindex 563ef3828d..8f880cf88e 100644--- a/server/core/types/express.d.ts+++ b/server/core/types/express.d.ts@@ -14,7 +14,9 @@ import {MActorFollowActorsDefault,MActorUrl,MChannelBannerAccountDefault,+ MChannelCollaboratorAccount,MChannelSyncChannel,+ MLocalVideoViewerWithWatchSections,MRegistration,MStreamingPlaylist,MUserAccountUrl,@@ -25,6 +27,7 @@ import {MVideoId,MVideoImmutable,MVideoLiveSessionReplay,+ MVideoLiveWithSettingSchedules,MVideoPassword,MVideoPlaylistFull,MVideoPlaylistFullSummary,@@ -248,6 +251,8 @@ declare module 'express' {watchedWordsList?: MWatchedWordsListtokenSession?: MOAuthToken++ channelCollaborator?: MChannelCollaboratorAccount}}}diff --git a/server/core/types/models/account/account.ts b/server/core/types/models/account/account.tsindex aab8f3b2dd..7edc2ba052 100644--- a/server/core/types/models/account/account.ts+++ b/server/core/types/models/account/account.ts@@ -16,6 +16,7 @@ import {} from '../actor/index.js'import { MChannelDefault } from '../video/video-channel.js'import { MAccountBlocklistId } from './account-blocklist.js'+import { MChannelCollaboratorChannel } from '../video/video-channel-collaborator.js'type Use<K extends keyof AccountModel, M> = PickWith<AccountModel, K, M>@@ -57,6 +58,12 @@ export type MAccountDefaultChannelDefault =& Use<'Actor', MActorDefault>& Use<'VideoChannels', MChannelDefault[]>+export type MAccountDefaultAllChannelDefault =+ & MAccount+ & Use<'Actor', MActorDefault>+ & Use<'VideoChannels', MChannelDefault[]>+ & Use<'VideoChannelCollaborators', MChannelCollaboratorChannel[]>+// We don't need some actors attributesexport type MAccountLight =& MAccountdiff --git a/server/core/types/models/actor/actor-follow.ts b/server/core/types/models/actor/actor-follow.tsindex c92ad1ff29..8db7aa9513 100644--- a/server/core/types/models/actor/actor-follow.ts+++ b/server/core/types/models/actor/actor-follow.ts@@ -1,4 +1,5 @@import { PickWith } from '@peertube/peertube-typescript-utils'+import { Model } from 'sequelize-typescript'import { ActorFollowModel } from '../../../models/actor/actor-follow.js'import {MActor,@@ -60,6 +61,7 @@ export type MActorFollowSubscriptions =// Format for API or AP objectexport type MActorFollowFormattable =- & Pick<MActorFollow, 'id' | 'score' | 'state' | 'createdAt' | 'updatedAt'>+ & Model<Pick<MActorFollow, 'id' | 'score' | 'state' | 'createdAt' | 'updatedAt'>>+ & Pick<MActorFollow, 'id' | 'score' | 'state' | 'createdAt' | 'updatedAt' | 'toFormattedJSON'>& Use<'ActorFollower', MActorFormattable>& Use<'ActorFollowing', MActorFormattable>diff --git a/server/core/types/models/user/user-notification.ts b/server/core/types/models/user/user-notification.tsindex 9c09877ce4..191e89b04f 100644--- a/server/core/types/models/user/user-notification.ts+++ b/server/core/types/models/user/user-notification.ts@@ -1,30 +1,31 @@/* eslint-disable @typescript-eslint/prefer-namespace-keyword */+import { PickWith, PickWithOpt } from '@peertube/peertube-typescript-utils'import { VideoAbuseModel } from '@server/models/abuse/video-abuse.js'import { VideoCommentAbuseModel } from '@server/models/abuse/video-comment-abuse.js'import { ApplicationModel } from '@server/models/application/application.js'import { PluginModel } from '@server/models/server/plugin.js'import { UserNotificationModel } from '@server/models/user/user-notification.js'import { UserRegistrationModel } from '@server/models/user/user-registration.js'-import { PickWith, PickWithOpt } from '@peertube/peertube-typescript-utils'+import { VideoCaptionModel } from '@server/models/video/video-caption.js'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'import { AbuseModel } from '../../../models/abuse/abuse.js'import { AccountModel } from '../../../models/account/account.js'-import { ActorModel } from '../../../models/actor/actor.js'import { ActorFollowModel } from '../../../models/actor/actor-follow.js'import { ActorImageModel } from '../../../models/actor/actor-image.js'+import { ActorModel } from '../../../models/actor/actor.js'import { ServerModel } from '../../../models/server/server.js'-import { VideoModel } from '../../../models/video/video.js'import { VideoBlacklistModel } from '../../../models/video/video-blacklist.js'import { VideoChannelModel } from '../../../models/video/video-channel.js'import { VideoCommentModel } from '../../../models/video/video-comment.js'import { VideoImportModel } from '../../../models/video/video-import.js'-import { VideoCaptionModel } from '@server/models/video/video-caption.js'+import { VideoModel } from '../../../models/video/video.js'type Use<K extends keyof UserNotificationModel, M> = PickWith<UserNotificationModel, K, M>// ############################################################################-export module UserNotificationIncludes {+export namespace UserNotificationIncludes {export type ActorImageInclude = Pick<ActorImageModel, 'createdAt' | 'filename' | 'type' | 'getStaticPath' | 'width' | 'updatedAt'>export type VideoInclude = Pick<VideoModel, 'id' | 'uuid' | 'name' | 'state'>@@ -41,6 +42,10 @@ export module UserNotificationIncludes {export type VideoChannelIncludeActor =& VideoChannelInclude& PickWith<VideoChannelModel, 'Actor', ActorInclude>+ export type VideoChannelIncludeActorOwnerActor =+ & VideoChannelInclude+ & PickWith<VideoChannelModel, 'Actor', ActorInclude>+ & PickWith<VideoChannelModel, 'Account', AccountIncludeActor>export type AccountInclude = Pick<AccountModel, 'id' | 'name' | 'getDisplayName'>export type AccountIncludeActor =@@ -105,6 +110,11 @@ export module UserNotificationIncludes {export type VideoCaptionInclude =& Pick<VideoCaptionModel, 'id' | 'language'>& PickWith<VideoCaptionModel, 'Video', VideoInclude>++ export type VideoChannelCollaboratorInclude =+ & Pick<VideoChannelCollaboratorModel, 'id' | 'state'>+ & PickWith<VideoChannelCollaboratorModel, 'Account', AccountIncludeActor>+ & PickWith<VideoChannelCollaboratorModel, 'Channel', VideoChannelIncludeActorOwnerActor>}// ############################################################################@@ -123,6 +133,7 @@ export type MUserNotification = Omit<| 'Application'| 'UserRegistration'| 'VideoCaption'+ | 'VideoChannelCollaborator'>// ############################################################################@@ -140,3 +151,4 @@ export type UserNotificationModelForApi =& Use<'Account', UserNotificationIncludes.AccountIncludeActor>& Use<'UserRegistration', UserNotificationIncludes.UserRegistrationInclude>& Use<'VideoCaption', UserNotificationIncludes.VideoCaptionInclude>+ & Use<'VideoChannelCollaborator', UserNotificationIncludes.VideoChannelCollaboratorInclude>diff --git a/server/core/types/models/user/user.ts b/server/core/types/models/user/user.tsindex c32e80dce4..010f6bd00d 100644--- a/server/core/types/models/user/user.ts+++ b/server/core/types/models/user/user.ts@@ -1,11 +1,11 @@+import { PickWith, PickWithOpt } from '@peertube/peertube-typescript-utils'import { AccountModel } from '@server/models/account/account.js'import { UserModel } from '@server/models/user/user.js'-import { MVideoPlaylist } from '@server/types/models/index.js'-import { PickWith, PickWithOpt } from '@peertube/peertube-typescript-utils'+import { MChannelCollaboratorChannel, MVideoPlaylist } from '@server/types/models/index.js'import {MAccount,MAccountDefault,- MAccountDefaultChannelDefault,+ MAccountDefaultAllChannelDefault,MAccountFormattable,MAccountId,MAccountIdActorId,@@ -50,7 +50,7 @@ export type MUserAccountDefault =export type MUserNotifSettingChannelDefault =& MUser& Use<'NotificationSetting', MNotificationSetting>- & Use<'Account', MAccountDefaultChannelDefault>+ & Use<'Account', MAccountDefaultAllChannelDefault>// With notification settings@@ -75,8 +75,11 @@ export type MUserDefault =// Format for API or AP objecttype MAccountWithChannels = MAccountFormattable & PickWithOpt<AccountModel, 'VideoChannels', MChannelFormattable[]>-type MAccountWithChannelsAndSpecialPlaylists =- & MAccountWithChannels++type MAccountWithAllChannels = MAccountWithChannels & PickWithOpt<AccountModel, 'VideoChannelCollaborators', MChannelCollaboratorChannel[]>++type MAccountWithAllChannelsAndSpecialPlaylists =+ & MAccountWithAllChannels& PickWithOpt<AccountModel, 'VideoPlaylists', MVideoPlaylist[]>export type MUserFormattable =@@ -86,4 +89,4 @@ export type MUserFormattable =export type MMyUserFormattable =& MUserFormattable- & Use<'Account', MAccountWithChannelsAndSpecialPlaylists>+ & Use<'Account', MAccountWithAllChannelsAndSpecialPlaylists>diff --git a/server/core/types/models/video/index.ts b/server/core/types/models/video/index.tsindex 0eeb7aad20..bd44af21b7 100644--- a/server/core/types/models/video/index.ts+++ b/server/core/types/models/video/index.ts@@ -11,6 +11,7 @@ export * from './video-caption.js'export * from './video-change-ownership.js'export * from './video-channel-sync.js'export * from './video-channel.js'+export * from './video-channel-collaborator.js'export * from './video-chapter.js'export * from './video-comment.js'export * from './video-file.js'diff --git a/server/core/types/models/video/video-caption.ts b/server/core/types/models/video/video-caption.tsindex 278ca15aa2..a47f474816 100644--- a/server/core/types/models/video/video-caption.ts+++ b/server/core/types/models/video/video-caption.ts@@ -37,7 +37,7 @@ export type MVideoCaptionLanguageUrl = Pick<export type MVideoCaptionVideo =& MVideoCaption- & Use<'Video', Pick<MVideo, 'id' | 'name' | 'remote' | 'uuid' | 'url' | 'state' | 'getWatchStaticPath' | 'isOwned' | 'privacy'>>+ & Use<'Video', Pick<MVideo, 'id' | 'name' | 'remote' | 'uuid' | 'url' | 'state' | 'getWatchStaticPath' | 'isLocal' | 'privacy'>>// ############################################################################diff --git a/server/core/types/models/video/video-channel-collaborator.ts b/server/core/types/models/video/video-channel-collaborator.tsnew file mode 100644index 0000000000..d4dbfdb30d--- /dev/null+++ b/server/core/types/models/video/video-channel-collaborator.ts@@ -0,0 +1,18 @@+import { PickWith } from '@peertube/peertube-typescript-utils'+import { VideoChannelCollaboratorModel } from '@server/models/video/video-channel-collaborator.js'+import { MAccountDefault } from '../account/account.js'+import { MChannelFormattable } from './video-channel.js'++type Use<K extends keyof VideoChannelCollaboratorModel, M> = PickWith<VideoChannelCollaboratorModel, K, M>++// ############################################################################++export type MChannelCollaborator = Omit<VideoChannelCollaboratorModel, 'Account' | 'Channel'>++export type MChannelCollaboratorAccount =+ & MChannelCollaborator+ & Use<'Account', MAccountDefault>++export type MChannelCollaboratorChannel =+ & MChannelCollaborator+ & Use<'Channel', MChannelFormattable>diff --git a/server/core/types/models/video/video-channel.ts b/server/core/types/models/video/video-channel.tsindex 4a92e9b382..cd5bdcce5f 100644--- a/server/core/types/models/video/video-channel.ts+++ b/server/core/types/models/video/video-channel.ts@@ -5,6 +5,7 @@ import {MAccountActor,MAccountDefault,MAccountFormattable,+ MAccountId,MAccountIdActorId,MAccountLight,MAccountSummaryBlocks,@@ -48,8 +49,13 @@ export type MChannelIdActor =& Use<'Actor', MActorAccountChannelId>export type MChannelUserId =- & Pick<MChannel, 'accountId'>- & Use<'Account', MAccountUserId>+ & Pick<MChannel, 'id' | 'accountId'>+ & Use<'Account', MAccountId & MAccountUserId>++export type MChannelAccountId =+ & Pick<MChannel, 'id' | 'accountId'>+ & Use<'Actor', MActorId>+ & Use<'Account', MAccountIdActorId>export type MChannelAccountIdUrl =& Pick<MChannel, 'id' | 'accountId'>@@ -154,7 +160,7 @@ export type MChannelAccountSummaryFormattable =export type MChannelFormattable =& FunctionProperties<MChannel>- & Pick<MChannel, 'id' | 'name' | 'description' | 'createdAt' | 'updatedAt' | 'support'>+ & Pick<MChannel, 'id' | 'name' | 'description' | 'createdAt' | 'updatedAt' | 'support' | 'accountId'>& Use<'Actor', MActorFormattable>& PickWithOpt<VideoChannelModel, 'Account', MAccountFormattable>diff --git a/server/core/types/models/video/video-comment.ts b/server/core/types/models/video/video-comment.tsindex 248940f0f7..f430513a48 100644--- a/server/core/types/models/video/video-comment.ts+++ b/server/core/types/models/video/video-comment.ts@@ -1,7 +1,9 @@import { PickWith, PickWithOpt } from '@peertube/peertube-typescript-utils'+import { VideoModel } from '@server/models/video/video.js'import { VideoCommentModel } from '../../../models/video/video-comment.js'import { MAccountDefault, MAccountFormattable, MAccountUrl } from '../account/index.js'import { MCommentAutomaticTagWithTag } from '../automatic-tag/comment-automatic-tag.js'+import { MChannelSummary } from './video-channel.js'import { MVideo, MVideoAccountIdUrl, MVideoAccountLight, MVideoFeed, MVideoIdUrl, MVideoImmutable, MVideoUUID } from './video.js'type Use<K extends keyof VideoCommentModel, M> = PickWith<VideoCommentModel, K, M>@@ -74,7 +76,7 @@ export type MCommentFormattable =export type MCommentAdminOrUserFormattable =& MComment& Use<'Account', MAccountFormattable>- & Use<'Video', MVideo>+ & Use<'Video', MVideo & PickWith<VideoModel, 'VideoChannel', MChannelSummary>>& Use<'CommentAutomaticTags', MCommentAutomaticTagWithTag[]>export type MCommentAP =diff --git a/server/core/types/models/video/video.ts b/server/core/types/models/video/video.tsindex bf31ba4c1f..a7bed4af9f 100644--- a/server/core/types/models/video/video.ts+++ b/server/core/types/models/video/video.ts@@ -63,8 +63,8 @@ export type MVideoUrl = Pick<MVideo, 'url'>export type MVideoUUID = Pick<MVideo, 'uuid'>export type MVideoPrivacy = Pick<MVideo, 'privacy' | 'uuid'>-export type MVideoImmutable = Pick<MVideo, 'id' | 'url' | 'uuid' | 'remote' | 'isOwned'>-export type MVideoOwned = Pick<MVideo, 'remote' | 'isOwned'>+export type MVideoImmutable = Pick<MVideo, 'id' | 'url' | 'uuid' | 'remote' | 'isLocal'>+export type MVideoOwned = Pick<MVideo, 'remote' | 'isLocal'>export type MVideoIdUrl = MVideoId & MVideoUrlexport type MVideoFeed = Pick<MVideo, 'name' | 'uuid'>diff --git a/server/scripts/create-import-video-file-job.ts b/server/scripts/create-import-video-file-job.tsindex fb3263a60e..004c3f2e91 100644--- a/server/scripts/create-import-video-file-job.ts+++ b/server/scripts/create-import-video-file-job.ts@@ -37,7 +37,7 @@ async function run () {const video = await VideoModel.load(uuid)if (!video) throw new Error('Video not found.')- if (video.isOwned() === false) throw new Error('Cannot import files of a non owned video.')+ if (video.isLocal() === false) throw new Error('Cannot import files of a non owned video.')const dataInput = {videoUUID: video.uuid,diff --git a/server/scripts/prune-storage.ts b/server/scripts/prune-storage.tsindex ca0e6495bd..256e9def45 100755--- a/server/scripts/prune-storage.ts+++ b/server/scripts/prune-storage.ts@@ -271,7 +271,7 @@ class FSPruner {if (keepOnlyOwned) {const video = await VideoModel.load(thumbnail.videoId)- if (video.isOwned() === false) return false+ if (video.isLocal() === false) return false}return true@@ -343,6 +343,6 @@ async function askPruneConfirmation (yes?: boolean) {return askConfirmation('These unknown files can be deleted, but please check your backups first (bugs happen). ' +- 'Can we delete these files?'+ 'Can we delete these files?')}diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yamlindex 3bc6310874..2084967adf 100644--- a/support/doc/api/openapi.yaml+++ b/support/doc/api/openapi.yaml@@ -2201,6 +2201,7 @@ paths:- $ref: '#/components/parameters/videoChannelId'- $ref: '#/components/parameters/autoTagOneOfComment'- $ref: '#/components/parameters/isHeldForReview'+ - $ref: '#/components/parameters/includeCollaborations'responses:'200':description: successful operation@@ -2230,6 +2231,7 @@ paths:- $ref: '#/components/parameters/start'- $ref: '#/components/parameters/count'- $ref: '#/components/parameters/sort'+ - $ref: '#/components/parameters/includeCollaborations'-name: targetUrlin: query@@ -2342,6 +2344,7 @@ paths:- $ref: '#/components/parameters/privacyOneOf'- $ref: '#/components/parameters/excludeAlreadyWatched'- $ref: '#/components/parameters/search'+ - $ref: '#/components/parameters/includeCollaborations'responses:'200':description: successful operation@@ -5515,6 +5518,19 @@ paths:- $ref: '#/components/parameters/sort'- $ref: '#/components/parameters/search'- $ref: '#/components/parameters/videoPlaylistType'+ - $ref: '#/components/parameters/includeCollaborations'+ - name: channelNameOneOf+ in: query+ required: false+ description: "**PeerTube >= 8.0** Filter on playlists that are published on a channel with one of these names"+ schema:+ oneOf:+ - type: string+ - type: array+ items:+ type: string+ style: form+ explode: trueresponses:'200':description: successful operation@@ -5541,12 +5557,14 @@ paths:- $ref: '#/components/parameters/name'- name: withStatsin: query- description: include daily view statistics for the last 30 days and total views (only if authentified as the account user)+ description: include daily view statistics for the last 30 days and total views (only if authenticated as the account user)schema:type: boolean- $ref: '#/components/parameters/start'- $ref: '#/components/parameters/count'+ - $ref: '#/components/parameters/search'- $ref: '#/components/parameters/sort'+ - $ref: '#/components/parameters/includeCollaborations'responses:'200':description: successful operation@@ -5567,6 +5585,7 @@ paths:- $ref: '#/components/parameters/start'- $ref: '#/components/parameters/count'- $ref: '#/components/parameters/sort'+ - $ref: '#/components/parameters/includeCollaborations'responses:'200':description: successful operation@@ -7447,6 +7466,111 @@ paths:'204':description: successful operation+ /api/v1/video-channels/{channelHandle}/collaborators:+ get:+ tags:+ - Video Channels+ summary: List channel collaborators+ operationId: listVideoChannelCollaborators+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/channelHandle'+ responses:+ '200':+ description: successful operation+ content:+ application/json:+ schema:+ type: object+ properties:+ total:+ type: integer+ example: 1+ data:+ type: array+ items:+ $ref: '#/components/schemas/VideoChannelCollaborator'++ /api/v1/video-channels/{channelHandle}/collaborators/invite:+ post:+ tags:+ - Video Channels+ summary: Invite a collaborator+ operationId: inviteVideoChannelCollaborator+ description: >+ Invite a local user to collaborate on the specified video channel.+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/channelHandle'+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ accountHandle:+ type: string+ description: Local user username to invite+ responses:+ '200':+ description: Collaborator invited+ content:+ application/json:+ schema:+ type: object+ properties:+ collaborator:+ $ref: '#/components/schemas/VideoChannelCollaborator'++ /api/v1/video-channels/{channelHandle}/collaborators/{collaboratorId}/accept:+ post:+ tags:+ - Video Channels+ summary: Accept a collaboration invitation+ operationId: acceptVideoChannelCollaborator+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/channelHandle'+ - $ref: '#/components/parameters/collaboratorId'+ responses:+ '204':+ description: Collaboration accepted++ /api/v1/video-channels/{channelHandle}/collaborators/{collaboratorId}/reject:+ post:+ tags:+ - Video Channels+ summary: Reject a collaboration invitation+ operationId: rejectVideoChannelCollaborator+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/channelHandle'+ - $ref: '#/components/parameters/collaboratorId'+ responses:+ '204':+ description: Collaboration rejected++ /api/v1/video-channels/{channelHandle}/collaborators/{collaboratorId}:+ delete:+ tags:+ - Video Channels+ summary: Remove a channel collaborator+ description: Only the channel owner or the collaborator themselves can remove a collaborator from a channel+ operationId: removeVideoChannelCollaborator+ security:+ - OAuth2: []+ parameters:+ - $ref: '#/components/parameters/channelHandle'+ - $ref: '#/components/parameters/collaboratorId'+ responses:+ '204':+ description: successful operation+servers:- url: 'https://peertube2.cpy.re'description: Live Test Server (live data - latest nightly version)@@ -8251,6 +8375,20 @@ components:- 'header-wide'- 'header-square'- 'opengraph'+ includeCollaborations:+ name: includeCollaborations+ in: query+ required: false+ description: "**PeerTube >= 8.0** Include objects from collaborated channels"+ schema:+ type: boolean+ collaboratorId:+ name: collaboratorId+ in: path+ required: true+ description: The collaborator id+ schema:+ $ref: '#/components/schemas/id'securitySchemes:OAuth2:@@ -12217,3 +12355,35 @@ components:The file storage type:- `0` File system- `1` Object storage++ VideoChannelCollaborator:+ type: object+ description: Representation of a channel collaboration+ properties:+ id:+ $ref: '#/components/schemas/id'+ account:+ $ref: '#/components/schemas/AccountSummary'+ state:+ type: object+ properties:+ id:+ $ref: '#/components/schemas/VideoChannelCollaboratorState'+ label:+ type: string+ createdAt:+ type: string+ format: date-time+ updatedAt:+ type: string+ format: date-time++ VideoChannelCollaboratorState:+ type: integer+ enum:+ - 1+ - 2+ description: |+ The user import state:+ - `1`: Pending+ - `2`: Accepted