ActivityPub-federated video streaming platform using P2P directly in your web browser
Add auto mute subscription feature
Chocobozzz34ce07a55a45
diff --git a/.dprint.json b/.dprint.jsonindex 34db0aa264..dbf61f9988 100644--- a/.dprint.json+++ b/.dprint.json@@ -88,6 +88,6 @@"https://plugins.dprint.dev/markdown-0.17.1.wasm","https://plugins.dprint.dev/toml-0.6.2.wasm","https://plugins.dprint.dev/g-plane/malva-v0.12.0.wasm",- "https://plugins.dprint.dev/g-plane/markup_fmt-v0.26.0.wasm"+ "https://plugins.dprint.dev/g-plane/markup_fmt-v0.27.0.wasm"]}diff --git a/client/src/app/+about/about-instance/children/about-instance-moderation.component.html b/client/src/app/+about/about-instance/children/about-instance-moderation.component.htmlindex 12a77a7594..38c8cae319 100644--- a/client/src/app/+about/about-instance/children/about-instance-moderation.component.html+++ b/client/src/app/+about/about-instance/children/about-instance-moderation.component.html@@ -1,5 +1,4 @@<div myPluginSelector pluginSelectorId="about-instance-moderation">-@if (aboutHTML.moderationInformation) {<div class="block moderation-information"><h4 i18n class="section-title">Moderation information</h4>@@ -14,4 +13,20 @@</div>}+ @if (isPublicBlocklistEnabled()) {+ <div class="block public-blocklist">+ <h4 i18n class="section-title">Public blocklist</h4>++ <div>+ <div i18n>+ {{ instanceName }} publicly shares <a href="/api/v1/server/blocklist/public-log" target="_blank" rel="noopener noreferrer">its instance blocklist+ <my-global-icon iconName="external-link"></my-global-icon></a>.+ </div>++ <div i18n>+ Other platforms can subscribe to it to automatically mute the same accounts and servers.+ </div>+ </div>+ </div>+ }</div>diff --git a/client/src/app/+about/about-instance/children/about-instance-moderation.component.ts b/client/src/app/+about/about-instance/children/about-instance-moderation.component.tsindex be19aa2292..84e6d7046b 100644--- a/client/src/app/+about/about-instance/children/about-instance-moderation.component.ts+++ b/client/src/app/+about/about-instance/children/about-instance-moderation.component.ts@@ -1,6 +1,7 @@import { Component, OnInit, inject } from '@angular/core'import { ActivatedRoute } from '@angular/router'import { ServerService } from '@app/core'+import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'import { AboutHTML } from '@app/shared/shared-main/instance/instance.service'import { PluginSelectorDirective } from '@app/shared/shared-main/plugins/plugin-selector.directive'import { ResolverData } from '../about-instance.resolver'@@ -8,7 +9,7 @@ import { ResolverData } from '../about-instance.resolver'@Component({templateUrl: './about-instance-moderation.component.html',styleUrls: [ './about-instance-common.component.scss' ],- imports: [ PluginSelectorDirective ]+ imports: [ PluginSelectorDirective, GlobalIconComponent ]})export class AboutInstanceModerationComponent implements OnInit {private route = inject(ActivatedRoute)@@ -20,6 +21,10 @@ export class AboutInstanceModerationComponent implements OnInit {return this.serverService.getHTMLConfig().instance.name}+ isPublicBlocklistEnabled () {+ return this.serverService.getHTMLConfig().blocklist.publicLog.enabled === true+ }+ngOnInit () {const { aboutHTML }: ResolverData = this.route.parent.snapshot.data.instanceDatadiff --git a/client/src/app/+admin/admin-moderation.component.ts b/client/src/app/+admin/admin-moderation.component.tsindex cb1aa0fce7..666a7c9309 100644--- a/client/src/app/+admin/admin-moderation.component.ts+++ b/client/src/app/+admin/admin-moderation.component.ts@@ -45,27 +45,37 @@ export class AdminModerationComponent implements OnInit {})}- if (this.hasRight(UserRight.MANAGE_ACCOUNTS_BLOCKLIST) || this.hasRight(UserRight.MANAGE_SERVERS_BLOCKLIST)) {+ if (+ this.hasRight(UserRight.MANAGE_SERVER_ACCOUNTS_BLOCKLIST) || this.hasRight(UserRight.MANAGE_SERVER_SERVERS_BLOCKLIST) ||+ this.hasRight(UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS)+ ) {const item: HorizontalMenuEntry = {label: $localize`Mutes`,routerLink: '',children: []}- if (this.hasRight(UserRight.MANAGE_ACCOUNTS_BLOCKLIST)) {+ if (this.hasRight(UserRight.MANAGE_SERVER_ACCOUNTS_BLOCKLIST)) {item.children.push({label: $localize`Muted accounts`,routerLink: '/admin/moderation/blocklist/accounts'})}- if (this.hasRight(UserRight.MANAGE_SERVERS_BLOCKLIST)) {+ if (this.hasRight(UserRight.MANAGE_SERVER_SERVERS_BLOCKLIST)) {item.children.push({label: $localize`Muted servers`,routerLink: '/admin/moderation/blocklist/servers'})}+ if (this.hasRight(UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS)) {+ item.children.push({+ label: $localize`Blocklist subscriptions`,+ routerLink: '/admin/moderation/blocklist/subscriptions'+ })+ }+item.routerLink = item.children[0].routerLinkthis.menuEntries.push(item)diff --git a/client/src/app/+admin/config/pages/admin-config-general.component.html b/client/src/app/+admin/config/pages/admin-config-general.component.htmlindex 711e85d77d..31185bef42 100644--- a/client/src/app/+admin/config/pages/admin-config-general.component.html+++ b/client/src/app/+admin/config/pages/admin-config-general.component.html@@ -1,4 +1,11 @@-<my-admin-save-bar i18n-title title="General configuration" (save)="save()" [form]="form" [formErrors]="formErrors" [validationMessages]="validationMessages"></my-admin-save-bar>+<my-admin-save-bar+ i18n-title+ title="General configuration"+ (save)="save()"+ [form]="form"+ [formErrors]="formErrors"+ [validationMessages]="validationMessages"+></my-admin-save-bar><form [formGroup]="form" id="admin-config-form"><div class="pt-two-cols">@@ -33,7 +40,7 @@formControlName="redirectOnSingleExternalAuth"i18n-labelTextlabelText="Redirect users on single external auth when users click on the login button in menu"- >+ ><ng-container ngProjectAs="description">@if (countExternalAuth() === 0) {<span i18n>⚠️ You don't have any external auth plugin enabled</span>@@ -77,7 +84,6 @@}</div></ng-container>-</div><div class="form-group" formGroupName="trending">@@ -206,7 +212,8 @@<div [ngClass]="getDisabledSignupClass()"><label i18n for="signupLimit">Signup limit</label>- <span i18n class="small muted ms-1">When the total number of users in your platform reaches this limit, registrations are disabled. -1 = unlimited</span>+ <span i18n class="small muted ms-1"+ >When the total number of users in your platform reaches this limit, registrations are disabled. -1 = unlimited</span><div class="number-with-unit"><input@@ -216,7 +223,7 @@class="form-control"formControlName="limit"[ngClass]="{ 'input-error': formErrors.signup.limit }"- >+ ><span i18n>{form.value.signup.limit, plural, =1 {user} other {users}}</span></div>@@ -240,7 +247,7 @@class="form-control"formControlName="minimumAge"[ngClass]="{ 'input-error': formErrors.signup.minimumAge }"- >+ ><span i18n>{form.value.signup.minimumAge, plural, =1 {year old} other {years old}}</span></div>@@ -301,7 +308,7 @@formControlName="enabled"i18n-labelTextlabelText="Automatically enable video history for a new user"- >+ ></my-peertube-checkbox></ng-container></ng-container>@@ -338,10 +345,10 @@formControlName="enabled"i18n-labelTextlabelText="Allow import with HTTP URL (e.g. YouTube)"- >+ ><ng-container ngProjectAs="description"><span i18n- >⚠️ If enabled, we recommend to use <a class="link-primary" href="https://docs.joinpeertube.org/maintain/configuration#security"+ >⚠️ If enabled, we recommend to use <a class="link-primary" href="https://docs.joinpeertube.org/maintain/configuration#security">a HTTP proxy</a> to prevent private URL access from your PeerTube server</span></ng-container></my-peertube-checkbox>@@ -353,7 +360,7 @@formControlName="enabled"i18n-labelTextlabelText="Allow import with a torrent file or a magnet URI"- >+ ><ng-container ngProjectAs="description"><span i18n>⚠️ We don't recommend to enable this feature if you don't trust your users</span></ng-container>@@ -368,7 +375,7 @@formControlName="enabled"i18n-labelTextlabelText="Allow channel synchronization with channel of other platforms like YouTube"- >+ ><ng-container ngProjectAs="description"><span i18n [hidden]="isImportVideosHttpEnabled()">⛔ You need to allow import with HTTP URL to be able to activate this feature.@@ -388,7 +395,7 @@class="form-control"formControlName="maxPerUser"[ngClass]="{ 'input-error': formErrors['import']['videoChannelSynchronization']['maxPerUser'] }"- >+ ><span i18n>{form.value.import.videoChannelSynchronization.maxPerUser, plural, =1 {sync} other {syncs}}</span></div>@@ -418,7 +425,7 @@formControlName="enabled"i18n-labelTextlabelText="Block new videos automatically"- >+ ><ng-container ngProjectAs="description"><span i18n>Unless a user is marked as trusted, their videos will stay private until a moderator reviews them.</span></ng-container>@@ -436,7 +443,7 @@formControlName="enabled"i18n-labelTextlabelText="Allow users to upload a new version of their video"- >+ ></my-peertube-checkbox></div></ng-container>@@ -452,9 +459,11 @@<ng-container ngProjectAs="extra"><div class="form-group" formGroupName="remoteRunners" [ngClass]="getStoryboardRunnerDisabledClass()"><my-peertube-checkbox- inputName="storyboardsRemoteRunnersEnabled" formControlName="enabled"- i18n-labelText labelText="Enable remote runners to generate storyboards"- >+ inputName="storyboardsRemoteRunnersEnabled"+ formControlName="enabled"+ i18n-labelText+ labelText="Enable remote runners to generate storyboards"+ ><ng-container ngProjectAs="description"><div i18n>Use <a routerLink="/admin/settings/system/runners/runners-list">remote runners</a> to generate storyboards.</div><div i18n>Remote runners have to register on your instance first.</div>@@ -472,196 +481,195 @@<ng-container ngProjectAs="description"><span i18n><a href="https://docs.joinpeertube.org/admin/configuration#automatic-transcription" target="_blank">Automatically create subtitles</a>for uploaded/imported VOD videos</span>- </ng-container>+ </ng-container>- <ng-container ngProjectAs="extra">- <div class="form-group" formGroupName="remoteRunners" [ngClass]="getTranscriptionRunnerDisabledClass()">- <my-peertube-checkbox- inputName="videoTranscriptionRemoteRunnersEnabled"- formControlName="enabled"- i18n-labelText- labelText="Enable remote runners for transcription"+ <ng-container ngProjectAs="extra">+ <div class="form-group" formGroupName="remoteRunners" [ngClass]="getTranscriptionRunnerDisabledClass()">+ <my-peertube-checkbox+ inputName="videoTranscriptionRemoteRunnersEnabled"+ formControlName="enabled"+ i18n-labelText+ labelText="Enable remote runners for transcription">- <ng-container ngProjectAs="description">- <div i18n>Use <a routerLink="/admin/settings/system/runners/runners-list">remote runners</a> to process transcription tasks.</div>- <div i18n>Remote runners have to register on your instance first.</div>- </ng-container>- </my-peertube-checkbox>- </div>- </ng-container>- </my-peertube-checkbox>- </div>- </ng-container>-- <ng-container formGroupName="defaults">- <ng-container formGroupName="publish">- <div class="form-group">- <label i18n for="defaultsPublishPrivacy">Default video privacy</label>+ <ng-container ngProjectAs="description">+ <div i18n>Use <a routerLink="/admin/settings/system/runners/runners-list">remote runners</a> to process transcription tasks.</div>+ <div i18n>Remote runners have to register on your instance first.</div>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container>- <my-select-options inputId="defaultsPublishPrivacy" [items]="privacyOptions" formControlName="privacy"></my-select-options>+ <ng-container formGroupName="defaults">+ <ng-container formGroupName="publish">+ <div class="form-group">+ <label i18n for="defaultsPublishPrivacy">Default video privacy</label>- @if (formErrors.defaults.publish.privacy) {- <div class="form-error" role="alert">{{ formErrors.defaults.publish.privacy }}</div>- }- </div>+ <my-select-options inputId="defaultsPublishPrivacy" [items]="privacyOptions" formControlName="privacy"></my-select-options>- <div class="form-group">- <label i18n for="defaultsPublishLicence">Default video licence</label>+ @if (formErrors.defaults.publish.privacy) {+ <div class="form-error" role="alert">{{ formErrors.defaults.publish.privacy }}</div>+ }+ </div>- <my-select-options inputId="defaultsPublishLicence" [items]="licenceOptions" formControlName="licence" clearable="true"></my-select-options>+ <div class="form-group">+ <label i18n for="defaultsPublishLicence">Default video licence</label>- @if (formErrors.defaults.publish.licence) {- <div class="form-error" role="alert">{{ formErrors.defaults.publish.licence }}</div>- }- </div>+ <my-select-options inputId="defaultsPublishLicence" [items]="licenceOptions" formControlName="licence" clearable="true"></my-select-options>- <div class="form-group">- <label i18n for="defaultsPublishCommentsPolicy">Default comment policy</label>+ @if (formErrors.defaults.publish.licence) {+ <div class="form-error" role="alert">{{ formErrors.defaults.publish.licence }}</div>+ }+ </div>- <my-select-options inputId="defaultsPublishCommentsPolicy" [items]="commentPoliciesOptions" formControlName="commentsPolicy"></my-select-options>+ <div class="form-group">+ <label i18n for="defaultsPublishCommentsPolicy">Default comment policy</label>- @if (formErrors.defaults.publish.commentsPolicy) {- <div class="form-error" role="alert">{{ formErrors.defaults.publish.commentsPolicy }}</div>- }- </div>+ <my-select-options inputId="defaultsPublishCommentsPolicy" [items]="commentPoliciesOptions" formControlName="commentsPolicy"></my-select-options>+ @if (formErrors.defaults.publish.commentsPolicy) {+ <div class="form-error" role="alert">{{ formErrors.defaults.publish.commentsPolicy }}</div>+ }+ </div>- <div class="form-group">- <label i18n for="defaultsDownloadPolicy">Default download policy</label>+ <div class="form-group">+ <label i18n for="defaultsDownloadPolicy">Default download policy</label>- <my-select-options inputId="defaultsDownloadPolicy" [items]="downloadPoliciesOptions" formControlName="downloadPolicy"></my-select-options>+ <my-select-options inputId="defaultsDownloadPolicy" [items]="downloadPoliciesOptions" formControlName="downloadPolicy"></my-select-options>- @if (formErrors.defaults.publish.downloadPolicy) {- <div class="form-error" role="alert">{{ formErrors.defaults.publish.downloadPolicy }}</div>- }- </div>+ @if (formErrors.defaults.publish.downloadPolicy) {+ <div class="form-error" role="alert">{{ formErrors.defaults.publish.downloadPolicy }}</div>+ }+ </div>+ </ng-container></ng-container>- </ng-container>+ </div></div>-</div>-<div class="pt-two-cols mt-4">- <div class="title-col">- <h2 i18n>VIDEO CHANNELS</h2>- </div>+ <div class="pt-two-cols mt-4">+ <div class="title-col">+ <h2 i18n>VIDEO CHANNELS</h2>+ </div>- <div class="content-col">- <div class="form-group" formGroupName="videoChannels">- <label i18n for="videoChannelsMaxPerUser">Max video channels per user</label>-- <div class="number-with-unit">- <input- type="number"- min="1"- id="videoChannelsMaxPerUser"- class="form-control"- formControlName="maxPerUser"- [ngClass]="{ 'input-error': formErrors.videoChannels.maxPerUser }"+ <div class="content-col">+ <div class="form-group" formGroupName="videoChannels">+ <label i18n for="videoChannelsMaxPerUser">Max video channels per user</label>++ <div class="number-with-unit">+ <input+ type="number"+ min="1"+ id="videoChannelsMaxPerUser"+ class="form-control"+ formControlName="maxPerUser"+ [ngClass]="{ 'input-error': formErrors.videoChannels.maxPerUser }">- <span i18n>{form.value.videoChannels.maxPerUser, plural, =1 {channel} other {channels}}</span>- </div>+ <span i18n>{form.value.videoChannels.maxPerUser, plural, =1 {channel} other {channels}}</span>+ </div>- @if (formErrors.videoChannels.maxPerUser) {- <div class="form-error" role="alert">{{ formErrors.videoChannels.maxPerUser }}</div>- }+ @if (formErrors.videoChannels.maxPerUser) {+ <div class="form-error" role="alert">{{ formErrors.videoChannels.maxPerUser }}</div>+ }+ </div></div></div>-</div>-<div class="pt-two-cols mt-4">- <div class="title-col">- <h2 i18n>FEDERATION</h2>- <div i18n class="inner-form-description">+ <div class="pt-two-cols mt-4">+ <div class="title-col">+ <h2 i18n>FEDERATION</h2>+ <div i18n class="inner-form-description">Manage <a class="link-primary" routerLink="/admin/settings/follows">relations</a> with other platforms.</div>- </div>-- <div class="content-col">- <ng-container formGroupName="videoComments">- <div class="form-group">- <my-peertube-checkbox- inputName="videoCommentsAcceptRemoteComments"- formControlName="acceptRemoteComments"- i18n-labelText- labelText="Accept comments made on remote platforms"- >- <ng-container ngProjectAs="description">- <span i18n>This setting is not retroactive: current comments from remote platforms will not be deleted</span>- </ng-container>- </my-peertube-checkbox>- </div>- </ng-container>-- <ng-container formGroupName="followers">- <ng-container formGroupName="channels">- <div class="form-group">- <my-peertube-checkbox- inputName="followersChannelsEnabled"- formControlName="enabled"- i18n-labelText- labelText="Remote actors can follow channels of your platform"- >- <ng-container ngProjectAs="description">- <span i18n>This setting is not retroactive: current followers of channels of your platform will not be affected</span>- </ng-container>- </my-peertube-checkbox>- </div>- </ng-container>+ </div>- <ng-container formGroupName="instance">+ <div class="content-col">+ <ng-container formGroupName="videoComments"><div class="form-group"><my-peertube-checkbox- inputName="followersInstanceEnabled"- formControlName="enabled"+ inputName="videoCommentsAcceptRemoteComments"+ formControlName="acceptRemoteComments"i18n-labelText- labelText="Remote actors can follow your platform"- >+ labelText="Accept comments made on remote platforms"+ ><ng-container ngProjectAs="description">- <span i18n>This setting is not retroactive: current followers of your platform will not be affected</span>+ <span i18n>This setting is not retroactive: current comments from remote platforms will not be deleted</span></ng-container></my-peertube-checkbox></div>-- <div class="form-group">- <my-peertube-checkbox- inputName="followersInstanceManualApproval"- formControlName="manualApproval"- i18n-labelText- labelText="Manually approve new followers that follow your platform"- ></my-peertube-checkbox>- </div></ng-container>- </ng-container>- <ng-container formGroupName="followings">- <ng-container formGroupName="instance">- <ng-container formGroupName="autoFollowBack">+ <ng-container formGroupName="followers">+ <ng-container formGroupName="channels"><div class="form-group"><my-peertube-checkbox- inputName="followingsInstanceAutoFollowBackEnabled"+ inputName="followersChannelsEnabled"formControlName="enabled"i18n-labelText- labelText="Automatically follow back followers that follow your platform"- >+ labelText="Remote actors can follow channels of your platform"+ ><ng-container ngProjectAs="description">- <span i18n>⚠️ This functionality requires a lot of attention and extra moderation</span>+ <span i18n>This setting is not retroactive: current followers of channels of your platform will not be affected</span></ng-container></my-peertube-checkbox></div></ng-container>- <ng-container formGroupName="autoFollowIndex">+ <ng-container formGroupName="instance"><div class="form-group"><my-peertube-checkbox- inputName="followingsInstanceAutoFollowIndexEnabled"+ inputName="followersInstanceEnabled"formControlName="enabled"i18n-labelText- labelText="Automatically follow platforms of a public index"- >+ labelText="Remote actors can follow your platform"+ ><ng-container ngProjectAs="description">- <div i18n>⚠️ This functionality requires a lot of attention and extra moderation.</div>+ <span i18n>This setting is not retroactive: current followers of your platform will not be affected</span>+ </ng-container>+ </my-peertube-checkbox>+ </div>++ <div class="form-group">+ <my-peertube-checkbox+ inputName="followersInstanceManualApproval"+ formControlName="manualApproval"+ i18n-labelText+ labelText="Manually approve new followers that follow your platform"+ ></my-peertube-checkbox>+ </div>+ </ng-container>+ </ng-container>++ <ng-container formGroupName="followings">+ <ng-container formGroupName="instance">+ <ng-container formGroupName="autoFollowBack">+ <div class="form-group">+ <my-peertube-checkbox+ inputName="followingsInstanceAutoFollowBackEnabled"+ formControlName="enabled"+ i18n-labelText+ labelText="Automatically follow back followers that follow your platform"+ >+ <ng-container ngProjectAs="description">+ <span i18n>⚠️ This functionality requires a lot of attention and extra moderation</span>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container>- <span i18n>+ <ng-container formGroupName="autoFollowIndex">+ <div class="form-group">+ <my-peertube-checkbox+ inputName="followingsInstanceAutoFollowIndexEnabled"+ formControlName="enabled"+ i18n-labelText+ labelText="Automatically follow platforms of a public index"+ >+ <ng-container ngProjectAs="description">+ <div i18n>⚠️ This functionality requires a lot of attention and extra moderation.</div>++ <span i18n>See <aclass="link-primary"href="https://docs.joinpeertube.org/admin/following-instances#automatically-follow-other-instances"@@ -669,238 +677,255 @@target="_blank">the documentation</a> for more information about the expected URL</span>- </ng-container>+ </ng-container>- <ng-container ngProjectAs="extra">- <div [ngClass]="{ 'disabled-checkbox-extra': !isAutoFollowIndexEnabled() }">- <label i18n for="followingsInstanceAutoFollowIndexUrl">Index URL</label>- <input- type="text"- id="followingsInstanceAutoFollowIndexUrl"- class="form-control"- formControlName="indexUrl"- [ngClass]="{ 'input-error': formErrors.followings.instance.autoFollowIndex.indexUrl }"- >- @if (formErrors.followings.instance.autoFollowIndex.indexUrl) {- <div class="form-error" role="alert">- {{ formErrors.followings.instance.autoFollowIndex.indexUrl }}+ <ng-container ngProjectAs="extra">+ <div [ngClass]="{ 'disabled-checkbox-extra': !isAutoFollowIndexEnabled() }">+ <label i18n for="followingsInstanceAutoFollowIndexUrl">Index URL</label>+ <input+ type="text"+ id="followingsInstanceAutoFollowIndexUrl"+ class="form-control"+ formControlName="indexUrl"+ [ngClass]="{ 'input-error': formErrors.followings.instance.autoFollowIndex.indexUrl }"+ >+ @if (formErrors.followings.instance.autoFollowIndex.indexUrl) {+ <div class="form-error" role="alert">+ {{ formErrors.followings.instance.autoFollowIndex.indexUrl }}+ </div>+ }</div>- }- </div>- </ng-container>- </my-peertube-checkbox>- </div>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container>+ </ng-container>+ </ng-container>++ <ng-container formGroupName="blocklist">+ <ng-container formGroupName="publicLog">+ <div class="form-group">+ <my-peertube-checkbox+ inputName="blocklistPublicLogEnabled"+ formControlName="enabled"+ i18n-labelText+ labelText="Publicly share your instance blocklist"+ >+ <ng-container ngProjectAs="description">+ <span i18n>Allow other instances to subscribe to your blocklist to automatically mute the same accounts and servers</span>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container></ng-container>- </ng-container>- </ng-container>-</div>-</div>--<div class="pt-two-cols mt-4">- <div class="title-col">- <h2 i18n>PLAYER</h2>+ </div></div>- <div class="content-col">- <ng-container formGroupName="defaults">- <ng-container formGroupName="player">+ <div class="pt-two-cols mt-4">+ <div class="title-col">+ <h2 i18n>PLAYER</h2>+ </div>- <div class="form-group">- <my-peertube-checkbox- inputName="defaultsPlayerAutoplay"- formControlName="autoPlay"- i18n-labelText- labelText="Automatically play videos in the player"- ></my-peertube-checkbox>- </div>- </ng-container>+ <div class="content-col">+ <ng-container formGroupName="defaults">+ <ng-container formGroupName="player">+ <div class="form-group">+ <my-peertube-checkbox+ inputName="defaultsPlayerAutoplay"+ formControlName="autoPlay"+ i18n-labelText+ labelText="Automatically play videos in the player"+ ></my-peertube-checkbox>+ </div>+ </ng-container>- <ng-container formGroupName="p2p">- <div class="form-group" formGroupName="webapp">- <my-peertube-checkbox- inputName="defaultsP2PWebappEnabled"- formControlName="enabled"- i18n-labelText- labelText="Enable P2P streaming by default on your platform"- ></my-peertube-checkbox>- </div>+ <ng-container formGroupName="p2p">+ <div class="form-group" formGroupName="webapp">+ <my-peertube-checkbox+ inputName="defaultsP2PWebappEnabled"+ formControlName="enabled"+ i18n-labelText+ labelText="Enable P2P streaming by default on your platform"+ ></my-peertube-checkbox>+ </div>- <div class="form-group" formGroupName="embed">- <my-peertube-checkbox- inputName="defaultsP2PEmbedEnabled"- formControlName="enabled"- i18n-labelText- labelText="Enable P2P streaming by default for videos embedded on external websites"- ></my-peertube-checkbox>- </div>+ <div class="form-group" formGroupName="embed">+ <my-peertube-checkbox+ inputName="defaultsP2PEmbedEnabled"+ formControlName="enabled"+ i18n-labelText+ labelText="Enable P2P streaming by default for videos embedded on external websites"+ ></my-peertube-checkbox>+ </div>+ </ng-container></ng-container>- </ng-container>+ </div></div>-</div>-<div class="pt-two-cols mt-4">- <div class="title-col">- <h2 i18n>SEARCH</h2>- </div>+ <div class="pt-two-cols mt-4">+ <div class="title-col">+ <h2 i18n>SEARCH</h2>+ </div>- <div class="content-col">- <ng-container formGroupName="search">- <ng-container formGroupName="remoteUri">- <div class="form-group">- <my-peertube-checkbox- inputName="searchRemoteUriUsers"- formControlName="users"- i18n-labelText- labelText="Allow users to do remote URI/handle search"+ <div class="content-col">+ <ng-container formGroupName="search">+ <ng-container formGroupName="remoteUri">+ <div class="form-group">+ <my-peertube-checkbox+ inputName="searchRemoteUriUsers"+ formControlName="users"+ i18n-labelText+ labelText="Allow users to do remote URI/handle search">- <ng-container ngProjectAs="description">- <span i18n>Allow <strong>your users</strong> to look up remote videos/actors that may not be federated with your platform</span>- </ng-container>- </my-peertube-checkbox>- </div>+ <ng-container ngProjectAs="description">+ <span i18n>Allow <strong>your users</strong> to look up remote videos/actors that may not be federated with your platform</span>+ </ng-container>+ </my-peertube-checkbox>+ </div>- <div class="form-group">- <my-peertube-checkbox- inputName="searchRemoteUriAnonymous"- formControlName="anonymous"- i18n-labelText- labelText="Allow anonymous to do remote URI/handle search"+ <div class="form-group">+ <my-peertube-checkbox+ inputName="searchRemoteUriAnonymous"+ formControlName="anonymous"+ i18n-labelText+ labelText="Allow anonymous to do remote URI/handle search">- <ng-container ngProjectAs="description">- <span i18n>Allow <strong>anonymous users</strong> to look up remote videos/actors that may not be federated with your platform</span>- </ng-container>- </my-peertube-checkbox>- </div>- </ng-container>+ <ng-container ngProjectAs="description">+ <span i18n>Allow <strong>anonymous users</strong> to look up remote videos/actors that may not be federated with your platform</span>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container>- <ng-container formGroupName="searchIndex">- <div class="form-group">- <my-peertube-checkbox inputName="searchIndexEnabled" formControlName="enabled" i18n-labelText labelText="Enable global search">- <ng-container ngProjectAs="description">- <div i18n>⚠️ This functionality depends heavily on the moderation of platforms followed by the search index you select</div>- </ng-container>+ <ng-container formGroupName="searchIndex">+ <div class="form-group">+ <my-peertube-checkbox inputName="searchIndexEnabled" formControlName="enabled" i18n-labelText labelText="Enable global search">+ <ng-container ngProjectAs="description">+ <div i18n>⚠️ This functionality depends heavily on the moderation of platforms followed by the search index you select</div>+ </ng-container>- <ng-container ngProjectAs="extra">- <div [ngClass]="getDisabledSearchIndexClass()">- <label i18n for="searchIndexUrl">Search index URL</label>+ <ng-container ngProjectAs="extra">+ <div [ngClass]="getDisabledSearchIndexClass()">+ <label i18n for="searchIndexUrl">Search index URL</label>- <div i18n class="form-group-description">- Use <a class="link-primary" target="_blank" href="https://framagit.org/framasoft/peertube/search-index">your own search index</a> or choose the official one, <a class="link-primary" target="_blank" href="https://sepiasearch.org">https://sepiasearch.org</a>, that is not moderated.+ <div i18n class="form-group-description">+ Use <a class="link-primary" target="_blank" href="https://framagit.org/framasoft/peertube/search-index">your own search index</a> or choose+ the official one, <a class="link-primary" target="_blank" href="https://sepiasearch.org">https://sepiasearch.org</a>, that is not moderated.</div>- <input- type="text"- id="searchIndexUrl"- class="form-control"- formControlName="url"- [ngClass]="{ 'input-error': formErrors.search.searchIndex.url }"+ <input+ type="text"+ id="searchIndexUrl"+ class="form-control"+ formControlName="url"+ [ngClass]="{ 'input-error': formErrors.search.searchIndex.url }">- @if (formErrors.search.searchIndex.url) {- <div class="form-error" role="alert">{{ formErrors.search.searchIndex.url }}</div>- }- </div>+ @if (formErrors.search.searchIndex.url) {+ <div class="form-error" role="alert">{{ formErrors.search.searchIndex.url }}</div>+ }+ </div>- <div class="mt-3">- <my-peertube-checkbox- [ngClass]="getDisabledSearchIndexClass()"- inputName="searchIndexDisableLocalSearch"- formControlName="disableLocalSearch"- i18n-labelText- labelText="Disable local search in search bar"- ></my-peertube-checkbox>- </div>+ <div class="mt-3">+ <my-peertube-checkbox+ [ngClass]="getDisabledSearchIndexClass()"+ inputName="searchIndexDisableLocalSearch"+ formControlName="disableLocalSearch"+ i18n-labelText+ labelText="Disable local search in search bar"+ ></my-peertube-checkbox>+ </div>- <div class="mt-3">- <my-peertube-checkbox- [ngClass]="getDisabledSearchIndexClass()"- inputName="searchIndexIsDefaultSearch"- formControlName="isDefaultSearch"- i18n-labelText- labelText="Search bar uses the global search index by default"+ <div class="mt-3">+ <my-peertube-checkbox+ [ngClass]="getDisabledSearchIndexClass()"+ inputName="searchIndexIsDefaultSearch"+ formControlName="isDefaultSearch"+ i18n-labelText+ labelText="Search bar uses the global search index by default">- <ng-container ngProjectAs="description">- <span i18n>Otherwise, the local search will be used by default</span>- </ng-container>- </my-peertube-checkbox>- </div>- </ng-container>- </my-peertube-checkbox>- </div>+ <ng-container ngProjectAs="description">+ <span i18n>Otherwise, the local search will be used by default</span>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container></ng-container>- </ng-container>+ </div></div>-</div>-<div class="pt-two-cols mt-4">- <div class="title-col">- <h2 i18n>USER IMPORT/EXPORT</h2>- </div>+ <div class="pt-two-cols mt-4">+ <div class="title-col">+ <h2 i18n>USER IMPORT/EXPORT</h2>+ </div>- <div class="content-col">- <ng-container formGroupName="import">- <ng-container formGroupName="users">- <div class="form-group">- <my-peertube-checkbox inputName="importUsersEnabled" formControlName="enabled" i18n-labelText labelText="Allow your users to import a data archive">- <ng-container ngProjectAs="description">- <div i18n>Video quota is checked on import so the user doesn't upload a too big archive file</div>- <div i18n>Video quota (daily quota is not taken into account) is also checked for each video when PeerTube is processing the import</div>- </ng-container>- </my-peertube-checkbox>- </div>+ <div class="content-col">+ <ng-container formGroupName="import">+ <ng-container formGroupName="users">+ <div class="form-group">+ <my-peertube-checkbox inputName="importUsersEnabled" formControlName="enabled" i18n-labelText labelText="Allow your users to import a data archive">+ <ng-container ngProjectAs="description">+ <div i18n>Video quota is checked on import so the user doesn't upload a too big archive file</div>+ <div i18n>Video quota (daily quota is not taken into account) is also checked for each video when PeerTube is processing the import</div>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container></ng-container>- </ng-container>- <ng-container formGroupName="export">- <ng-container formGroupName="users">- <div class="form-group">- <my-peertube-checkbox inputName="exportUsersEnabled" formControlName="enabled" i18n-labelText labelText="Allow your users to export their data">- <ng-container ngProjectAs="description">- <span i18n>Users can export their PeerTube data in a .zip for backup or re-import. Only one export at a time is allowed per user</span>- </ng-container>+ <ng-container formGroupName="export">+ <ng-container formGroupName="users">+ <div class="form-group">+ <my-peertube-checkbox inputName="exportUsersEnabled" formControlName="enabled" i18n-labelText labelText="Allow your users to export their data">+ <ng-container ngProjectAs="description">+ <span i18n>Users can export their PeerTube data in a .zip for backup or re-import. Only one export at a time is allowed per user</span>+ </ng-container>- <ng-container ngProjectAs="extra">- <div class="form-group" [ngClass]="getDisabledExportUsersClass()">- <label i18n id="exportUsersMaxUserVideoQuota" for="exportUsersMaxUserVideoQuota">Max user video quota allowed to generate the export</label>-- <span i18n class="ms-2 small muted">If the user decides to include the video files in the archive</span>-- <my-select-custom-value- labelId="exportUsersMaxUserVideoQuota"- inputId="exportUsersMaxUserVideoQuota"- [items]="exportMaxUserVideoQuotaOptions"- formControlName="maxUserVideoQuota"- i18n-inputSuffix- inputSuffix="bytes"- inputType="number"- [clearable]="false"- ></my-select-custom-value>-- @if (formErrors.export.users.maxUserVideoQuota) {- <div class="form-error" role="alert">{{ formErrors.export.users.maxUserVideoQuota }}</div>- }- </div>+ <ng-container ngProjectAs="extra">+ <div class="form-group" [ngClass]="getDisabledExportUsersClass()">+ <label i18n id="exportUsersMaxUserVideoQuota" for="exportUsersMaxUserVideoQuota">Max user video quota allowed to generate the export</label>++ <span i18n class="ms-2 small muted">If the user decides to include the video files in the archive</span>++ <my-select-custom-value+ labelId="exportUsersMaxUserVideoQuota"+ inputId="exportUsersMaxUserVideoQuota"+ [items]="exportMaxUserVideoQuotaOptions"+ formControlName="maxUserVideoQuota"+ i18n-inputSuffix+ inputSuffix="bytes"+ inputType="number"+ [clearable]="false"+ ></my-select-custom-value>++ @if (formErrors.export.users.maxUserVideoQuota) {+ <div class="form-error" role="alert">{{ formErrors.export.users.maxUserVideoQuota }}</div>+ }+ </div>- <div class="form-group" [ngClass]="getDisabledExportUsersClass()">- <label i18n for="exportUsersExportExpiration">User export expiration</label>+ <div class="form-group" [ngClass]="getDisabledExportUsersClass()">+ <label i18n for="exportUsersExportExpiration">User export expiration</label>- <my-select-options- inputId="exportUsersExportExpiration"- [items]="exportExpirationOptions"- formControlName="exportExpiration"- ></my-select-options>+ <my-select-options+ inputId="exportUsersExportExpiration"+ [items]="exportExpirationOptions"+ formControlName="exportExpiration"+ ></my-select-options>- <div i18n class="mt-1 small muted">The archive file is deleted after this period</div>+ <div i18n class="mt-1 small muted">The archive file is deleted after this period</div>- @if (formErrors.export.users.exportExpiration) {- <div class="form-error" role="alert">{{ formErrors.export.users.exportExpiration }}</div>- }- </div>- </ng-container>- </my-peertube-checkbox>- </div>+ @if (formErrors.export.users.exportExpiration) {+ <div class="form-error" role="alert">{{ formErrors.export.users.exportExpiration }}</div>+ }+ </div>+ </ng-container>+ </my-peertube-checkbox>+ </div>+ </ng-container></ng-container>- </ng-container>+ </div></div>-</div></form>diff --git a/client/src/app/+admin/config/pages/admin-config-general.component.ts b/client/src/app/+admin/config/pages/admin-config-general.component.tsindex 23ed5718d6..3da7722c40 100644--- a/client/src/app/+admin/config/pages/admin-config-general.component.ts+++ b/client/src/app/+admin/config/pages/admin-config-general.component.ts@@ -152,6 +152,12 @@ type Form = {}>}>+ blocklist: FormGroup<{+ publicLog: FormGroup<{+ enabled: FormControl<boolean>+ }>+ }>+followings: FormGroup<{instance: FormGroup<{autoFollowBack: FormGroup<{@@ -406,6 +412,11 @@ export class AdminConfigGeneralComponent implements OnInit, OnDestroy, CanComponenabled: null}},+ blocklist: {+ publicLog: {+ enabled: null+ }+ },followings: {instance: {autoFollowBack: {diff --git a/client/src/app/+admin/moderation/instance-blocklist/index.ts b/client/src/app/+admin/moderation/instance-blocklist/index.tsindex 3e7a344bb6..44f85d2c05 100644--- a/client/src/app/+admin/moderation/instance-blocklist/index.ts+++ b/client/src/app/+admin/moderation/instance-blocklist/index.ts@@ -1,2 +1,3 @@export * from './instance-account-blocklist.component'+export * from './instance-blocklist-subscriptions.component'export * from './instance-server-blocklist.component'diff --git a/client/src/app/+admin/moderation/instance-blocklist/instance-blocklist-subscriptions.component.html b/client/src/app/+admin/moderation/instance-blocklist/instance-blocklist-subscriptions.component.htmlnew file mode 100644index 0000000000..7611a678de--- /dev/null+++ b/client/src/app/+admin/moderation/instance-blocklist/instance-blocklist-subscriptions.component.html@@ -0,0 +1,115 @@+<my-table+ #table+ key="InstanceBlocklistSubscriptionsComponent"+ i18n-paginatorText+ paginatorText="subscriptions per page"+ [defaultColumns]="columns"+ [dataLoader]="dataLoader"+ columnConfig="false"+ searchInput="true"+>+ <ng-template #totalTitle let-totalRecords>+ <ng-container i18n+ >{ totalRecords, plural, =0 {No subscription} =1 {1 subscription} other {{{ totalRecords | myNumberFormatter }} subscriptions}}</ng-container>+ </ng-template>++ <ng-template #captionRight>+ <button class="peertube-create-button" (click)="openAddModal()" (keyup.enter)="openAddModal()">+ <my-global-icon iconName="add" aria-hidden="true"></my-global-icon>+ <ng-container i18n>Add a subscription</ng-container>+ </button>+ </ng-template>++ <ng-template #tableCells let-subscription>+ <td>{{ subscription.name }}</td>++ <td>+ <a [href]="subscription.url" target="_blank" rel="noopener noreferrer">+ {{ subscription.url }}+ <my-global-icon iconName="external-link"></my-global-icon>+ </a>+ </td>++ <td>+ <span [ngClass]="getStateClass(subscription.state.id)">+ {{ subscription.state.label }}+ </span>+ </td>++ <td>{{ subscription.lastSyncAt ? (subscription.lastSyncAt | ptDate: 'short') : '-' }}</td>++ <td>+ <a+ [routerLink]="getServerBlocklistUrl()"+ [queryParams]="{ subscriptionName: subscription.name }"+ i18n-title+ title="Open muted servers filtered by this subscription"+ >{{ subscription.mutedServersCount }}</a>+ </td>++ <td>+ <a+ [routerLink]="getAccountBlocklistUrl()"+ [queryParams]="{ subscriptionName: subscription.name }"+ i18n-title+ title="Open muted accounts filtered by this subscription"+ >{{ subscription.mutedAccountsCount }}</a>+ </td>++ <td>{{ subscription.createdAt | ptDate: 'short' }}</td>+ </ng-template>++ <ng-template #actionCell let-subscription>+ <button class="peertube-button secondary-button" (click)="removeSubscription(subscription)" i18n>Delete</button>+ </ng-template>++ <ng-template #noResults let-search="search" let-hasFilters="hasFilters">+ @if (search || hasFilters) {+ <ng-container i18n>No subscription found matching current filters.</ng-container>+ } @else {+ <ng-container i18n>No subscription found.</ng-container>+ }+ </ng-template>+</my-table>++<ng-template #addModal let-hide="close">+ <div class="modal-container">+ <div class="modal-header">+ <h4 class="modal-title" i18n>Add a blocklist subscription</h4>++ <button class="border-0 p-0" (click)="hide()" i18n-title title="Close">+ <my-global-icon iconName="cross"></my-global-icon>+ </button>+ </div>++ <div class="modal-body">+ <p i18n>Enter the URL of the blocklist to subscribe to. The list will be fetched periodically and accounts/servers will be automatically muted.</p>++ <div class="form-group">+ <label i18n for="subscriptionUrl">Blocklist URL</label>+ <input+ type="url"+ id="subscriptionUrl"+ class="form-control"+ [formField]="addSubscriptionForm['url']"+ i18n-placeholder+ placeholder="https://example.com/blocklist.json"+ >++ <my-form-error [field]="addSubscriptionForm.url()"></my-form-error>+ </div>+ </div>++ <div class="modal-footer">+ <button class="peertube-button secondary-button" (click)="hide()" i18n>Cancel</button>++ <my-button+ theme="primary"+ [loading]="addingSubscription"+ [disabled]="!addSubscriptionForm().valid() || addingSubscription"+ (click)="submitAddModal()"+ i18n+ >Subscribe</my-button>+ </div>+ </div>+</ng-template>diff --git a/client/src/app/+admin/moderation/instance-blocklist/instance-blocklist-subscriptions.component.ts b/client/src/app/+admin/moderation/instance-blocklist/instance-blocklist-subscriptions.component.tsnew file mode 100644index 0000000000..f85bb08cd0--- /dev/null+++ b/client/src/app/+admin/moderation/instance-blocklist/instance-blocklist-subscriptions.component.ts@@ -0,0 +1,135 @@+import { CommonModule } from '@angular/common'+import { Component, ElementRef, inject, signal, viewChild } from '@angular/core'+import { form, FormField, pattern, required } from '@angular/forms/signals'+import { RouterLink } from '@angular/router'+import { ConfirmService, Notifier } from '@app/core'+import { urlPattern } from '@app/shared/form-validators/common-validators'+import { GlobalIconComponent } from '@app/shared/shared-icons/global-icon.component'+import { ButtonComponent } from '@app/shared/shared-main/buttons/button.component'+import { PTDatePipe } from '@app/shared/shared-main/common/date.pipe'+import { NumberFormatterPipe } from '@app/shared/shared-main/common/number-formatter.pipe'+import { BlocklistService } from '@app/shared/shared-moderation/blocklist.service'+import { getStateBadgeClasses } from '@app/shared/shared-tables/state-badge'+import { DataLoaderOptionsBase, TableComponent } from '@app/shared/shared-tables/table.component'+import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'+import { BlocklistSubscription, StreamSyncStateType } from '@peertube/peertube-models'+import { FormErrorComponent } from '../../../shared/shared-forms/form-error.component'++type AddSubscriptionFormModel = {+ url: string+}++@Component({+ selector: 'my-instance-blocklist-subscriptions',+ templateUrl: './instance-blocklist-subscriptions.component.html',+ imports: [+ CommonModule,+ FormErrorComponent,+ TableComponent,+ NumberFormatterPipe,+ PTDatePipe,+ GlobalIconComponent,+ FormField,+ ButtonComponent,+ RouterLink+ ]+})+export class InstanceBlocklistSubscriptionsComponent {+ private blocklistService = inject(BlocklistService)+ private notifier = inject(Notifier)+ private confirmService = inject(ConfirmService)+ private modalService = inject(NgbModal)++ readonly table = viewChild<TableComponent<BlocklistSubscription>>('table')+ readonly addModal = viewChild<ElementRef>('addModal')++ readonly addSubscriptionModel = signal<AddSubscriptionFormModel>({ url: '' })+ readonly addSubscriptionForm = form(this.addSubscriptionModel, f => {+ required(f.url, { message: $localize`Blocklist URL is required.` })+ pattern(f.url, urlPattern, { message: $localize`Please enter a valid URL.` })+ })+ addingSubscription = false++ private addModalOpened: NgbModalRef++ columns = [+ { id: 'name', label: $localize`Name`, sortable: true },+ { id: 'url', label: $localize`URL`, sortable: false },+ { id: 'syncStatus', label: $localize`Status`, sortable: false },+ { id: 'lastSyncAt', label: $localize`Last synced`, sortable: true },+ { id: 'blockedHosts', label: $localize`Blocked hosts`, sortable: false },+ { id: 'blockedAccounts', label: $localize`Blocked accounts`, sortable: false },+ { id: 'createdAt', label: $localize`Subscribed at`, sortable: true }+ ]++ dataLoader: typeof this._dataLoader++ constructor () {+ this.dataLoader = this._dataLoader.bind(this)+ }++ openAddModal () {+ this.addSubscriptionModel.set({ url: '' })+ this.addSubscriptionForm().reset()++ this.addModalOpened = this.modalService.open(this.addModal(), { centered: true })+ }++ submitAddModal () {+ const url = this.addSubscriptionModel().url.trim()++ this.addingSubscription = true++ this.blocklistService.addBlocklistSubscription(url)+ .subscribe({+ next: () => {+ this.notifier.success($localize`Subscription to ${url} added.`)++ this.addModalOpened.close()++ this.table().loadData()+ this.addingSubscription = false+ },++ error: err => {+ this.notifier.handleError(err)+ this.addingSubscription = false+ }+ })+ }++ async removeSubscription (subscription: BlocklistSubscription) {+ const res = await this.confirmService.confirm(+ // eslint-disable-next-line max-len+ $localize`Deleting this subscription will unblock all accounts and servers that were muted because of it. Are you sure you want to delete the subscription to "${subscription.name}"?`,+ $localize`Delete subscription`+ )++ if (res === false) return++ this.blocklistService.removeBlocklistSubscription(subscription.id)+ .subscribe({+ next: () => {+ this.notifier.success($localize`Subscription to "${subscription.name}" deleted.`)+ this.table().loadData()+ },+ error: err => this.notifier.handleError(err)+ })+ }++ getStateClass (stateId: StreamSyncStateType) {+ return getStateBadgeClasses(stateId)+ }++ getServerBlocklistUrl () {+ return '/admin/moderation/blocklist/servers'+ }++ getAccountBlocklistUrl () {+ return '/admin/moderation/blocklist/accounts'+ }++ private _dataLoader (options: DataLoaderOptionsBase) {+ return this.blocklistService.listBlocklistSubscriptions(options)+ }+}diff --git a/client/src/app/+admin/moderation/moderation.routes.ts b/client/src/app/+admin/moderation/moderation.routes.tsindex bc2aca225b..a1e652a6fa 100644--- a/client/src/app/+admin/moderation/moderation.routes.ts+++ b/client/src/app/+admin/moderation/moderation.routes.ts@@ -1,6 +1,10 @@import { Routes } from '@angular/router'import { AbuseListComponent } from '@app/+admin/moderation/abuse-list'-import { InstanceAccountBlocklistComponent, InstanceServerBlocklistComponent } from '@app/+admin/moderation/instance-blocklist'+import {+ InstanceAccountBlocklistComponent,+ InstanceBlocklistSubscriptionsComponent,+ InstanceServerBlocklistComponent+} from '@app/+admin/moderation/instance-blocklist'import { VideoBlockListComponent } from '@app/+admin/moderation/video-block-list'import { UserRightGuard } from '@app/core'import { UserRight } from '@peertube/peertube-models'@@ -99,7 +103,7 @@ export const moderationRoutes: Routes = [component: InstanceAccountBlocklistComponent,canActivate: [ UserRightGuard ],data: {- userRight: UserRight.MANAGE_ACCOUNTS_BLOCKLIST,+ userRight: UserRight.MANAGE_SERVER_ACCOUNTS_BLOCKLIST,meta: {title: $localize`Muted accounts`}@@ -110,13 +114,25 @@ export const moderationRoutes: Routes = [component: InstanceServerBlocklistComponent,canActivate: [ UserRightGuard ],data: {- userRight: UserRight.MANAGE_SERVERS_BLOCKLIST,+ userRight: UserRight.MANAGE_SERVER_SERVERS_BLOCKLIST,meta: {title: $localize`Muted platforms`}}},+ {+ path: 'blocklist/subscriptions',+ component: InstanceBlocklistSubscriptionsComponent,+ canActivate: [ UserRightGuard ],+ data: {+ userRight: UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS,+ meta: {+ title: $localize`Blocklist subscriptions`+ }+ }+ },+{path: 'watched-words/list',component: WatchedWordsListAdminComponent,diff --git a/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts b/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.tsindex 3a356bd6f1..7774e43a73 100644--- a/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts+++ b/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts@@ -59,7 +59,8 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {'abuseNewMessage','abuseAsModerator','videoAutoBlacklistAsModerator',- 'newUserRegistration'+ 'newUserRegistration',+ 'automaticBlocklist']},@@ -81,7 +82,8 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {newInstanceFollower: UserRight.MANAGE_SERVER_FOLLOW,autoInstanceFollowing: UserRight.MANAGE_CONFIGURATION,newPeerTubeVersion: UserRight.MANAGE_DEBUG,- newPluginVersion: UserRight.MANAGE_DEBUG+ newPluginVersion: UserRight.MANAGE_DEBUG,+ automaticBlocklist: UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS}}@@ -107,7 +109,8 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {newPeerTubeVersion: $localize`A new PeerTube version is available`,newPluginVersion: $localize`One of your plugin/theme has a new available version`,myVideoStudioEditionFinished: $localize`Processing of edits has finished`,- myVideoTranscriptionGenerated: $localize`The transcription of your video has been generated`+ myVideoTranscriptionGenerated: $localize`The transcription of your video has been generated`,+ automaticBlocklist: $localize`An account or server was automatically blocked/unblocked by a blocklist subscription`}this.loadNotificationSettings()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 9726e4ea25..95537b32ea 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@@ -1,12 +1,13 @@import { CommonModule } from '@angular/common'-import { Component, OnInit, inject, viewChild } from '@angular/core'+import { Component, inject, OnInit, viewChild } from '@angular/core'import { RouterLink } from '@angular/router'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 { getStateBadgeClasses } from '@app/shared/shared-tables/state-badge'+import { HTMLServerConfig, StreamSyncStateType, VideoChannelSync } from '@peertube/peertube-models'import { first, mergeMap } from 'rxjs'import { GlobalIconComponent } from '../../shared/shared-icons/global-icon.component'import { ActionDropdownComponent, DropdownAction } from '../../shared/shared-main/buttons/action-dropdown.component'@@ -37,13 +38,6 @@ export class MyVideoChannelSyncsComponent implements OnInit {videoChannelSyncActions: DropdownAction<VideoChannelSync>[][] = []- private static STATE_CLASS_BY_ID = {- [VideoChannelSyncState.FAILED]: 'badge-red',- [VideoChannelSyncState.PROCESSING]: 'badge-blue',- [VideoChannelSyncState.SYNCED]: 'badge-green',- [VideoChannelSyncState.WAITING_FIRST_RUN]: 'badge-yellow'- }-private serverConfig: HTMLServerConfigcolumns: TableColumnInfo<string>[] = [@@ -136,8 +130,8 @@ export class MyVideoChannelSyncsComponent implements OnInit {return '/my-library/video-channel-syncs/create'}- getSyncStateClass (stateId: VideoChannelSyncStateType) {- return [ 'pt-badge', MyVideoChannelSyncsComponent.STATE_CLASS_BY_ID[stateId] ]+ getSyncStateClass (stateId: StreamSyncStateType) {+ return getStateBadgeClasses(stateId)}getChannelUrl (name: string) {diff --git a/client/src/app/shared/form-validators/common-validators.ts b/client/src/app/shared/form-validators/common-validators.tsindex d9ac9b45b3..b9b04aaa36 100644--- a/client/src/app/shared/form-validators/common-validators.ts+++ b/client/src/app/shared/form-validators/common-validators.ts@@ -1,6 +1,10 @@import { Validators } from '@angular/forms'import { BuildFormValidator } from './form-validator.model'+export const urlPattern = /^https?:\/\//++// ---------------------------------------------------------------------------+export const REQUIRED_VALIDATOR: BuildFormValidator = {VALIDATORS: [ Validators.required ],MESSAGES: {@@ -9,7 +13,7 @@ export const REQUIRED_VALIDATOR: BuildFormValidator = {}export const URL_VALIDATOR: BuildFormValidator = {- VALIDATORS: [ Validators.pattern(/^https?:\/\//) ],+ VALIDATORS: [ Validators.pattern(urlPattern) ],MESSAGES: {pattern: $localize`This field must be a URL`}diff --git a/client/src/app/shared/shared-main/account/account.model.ts b/client/src/app/shared/shared-main/account/account.model.tsindex 155224404c..a79d8e5fd6 100644--- a/client/src/app/shared/shared-main/account/account.model.ts+++ b/client/src/app/shared/shared-main/account/account.model.ts@@ -12,8 +12,11 @@ export class Account extends Actor implements ServerAccount {mutedByUser: booleanmutedByInstance: boolean+ mutedByInstanceSubscription: string | null+mutedServerByUser: booleanmutedServerByInstance: boolean+ mutedServerByInstanceSubscription: string | nulluserId?: number@@ -38,8 +41,10 @@ export class Account extends Actor implements ServerAccount {this.mutedByUser = falsethis.mutedByInstance = false+ this.mutedByInstanceSubscription = nullthis.mutedServerByUser = falsethis.mutedServerByInstance = false+ this.mutedServerByInstanceSubscription = null}updateAvatar (newAvatars: ActorImage[]) {@@ -52,8 +57,10 @@ export class Account extends Actor implements ServerAccount {updateBlockStatus (blockStatus: BlockStatus) {this.mutedByInstance = blockStatus.accounts[this.nameWithHostForced].blockedByServer+ this.mutedByInstanceSubscription = blockStatus.accounts[this.nameWithHostForced].blockedByServerSubscriptionthis.mutedByUser = blockStatus.accounts[this.nameWithHostForced].blockedByUserthis.mutedServerByUser = blockStatus.hosts[this.host].blockedByUserthis.mutedServerByInstance = blockStatus.hosts[this.host].blockedByServer+ this.mutedServerByInstanceSubscription = blockStatus.hosts[this.host].blockedByServerSubscription}}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 2d6c7cb524..cc2972b66b 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@@ -169,6 +169,11 @@ export class UserNotification {if (payload.changeOwnership.state.id === ChangeOwnershipState.ACCEPTED) {this.url = this.buildChannelUrl(payload.changeOwnership.channel)} // Else, no URL: we have buttons instead to accept/decline the request+ break++ case UserNotificationType.AUTOMATIC_BLOCKLIST_UPDATE:+ this.url = '/admin/moderation/blocklist/subscriptions'+ break}} catch (err: any) {this.payload.type = nulldiff --git a/client/src/app/shared/shared-moderation/account-block-badges.component.html b/client/src/app/shared/shared-moderation/account-block-badges.component.htmlindex b2265c2aec..69d2dacfc5 100644--- a/client/src/app/shared/shared-moderation/account-block-badges.component.html+++ b/client/src/app/shared/shared-moderation/account-block-badges.component.html@@ -8,10 +8,18 @@@if (!platformOnly()) {@if (account().mutedByInstance) {- <span class="pt-badge badge-danger" i18n>Muted by your platform</span>+ <span+ class="pt-badge badge-danger"+ [title]="getSubscriptionTitle(account().mutedByInstanceSubscription)"+ i18n+ >Muted by your platform</span>}@if (account().mutedServerByInstance) {- <span class="pt-badge badge-danger" i18n>Platform muted by your platform</span>+ <span+ class="pt-badge badge-danger"+ [title]="getSubscriptionTitle(account().mutedServerByInstanceSubscription)"+ i18n+ >Platform muted by your platform</span>}}diff --git a/client/src/app/shared/shared-moderation/account-block-badges.component.ts b/client/src/app/shared/shared-moderation/account-block-badges.component.tsindex 5e64005be0..f5dcd0461c 100644--- a/client/src/app/shared/shared-moderation/account-block-badges.component.ts+++ b/client/src/app/shared/shared-moderation/account-block-badges.component.ts@@ -2,7 +2,15 @@ import { booleanAttribute, Component, input } from '@angular/core'import { Account } from '../shared-main/account/account.model'export type AccountBlockBadgeInput = Partial<- Pick<Account, 'mutedByUser' | 'mutedServerByUser' | 'mutedByInstance' | 'mutedServerByInstance'>+ Pick<+ Account,+ | 'mutedByUser'+ | 'mutedServerByUser'+ | 'mutedByInstance'+ | 'mutedByInstanceSubscription'+ | 'mutedServerByInstance'+ | 'mutedServerByInstanceSubscription'+ >>@Component({@@ -15,4 +23,10 @@ export class AccountBlockBadgesComponent {readonly account = input.required<AccountBlockBadgeInput>()readonly platformOnly = input(false, { transform: booleanAttribute })++ getSubscriptionTitle (subscriptionName: string | undefined) {+ if (!subscriptionName) return undefined++ return $localize`Muted by subscription "${subscriptionName}"`+ }}diff --git a/client/src/app/shared/shared-moderation/account-block.model.ts b/client/src/app/shared/shared-moderation/account-block.model.tsindex 309b6e83b6..45ad7bec6d 100644--- a/client/src/app/shared/shared-moderation/account-block.model.ts+++ b/client/src/app/shared/shared-moderation/account-block.model.ts@@ -6,9 +6,16 @@ export class AccountBlock implements AccountBlockServer {blockedAccount: AccountcreatedAt: Date | string+ blocklistSubscription?: {+ id: number+ name: string+ url: string+ }+constructor (block: AccountBlockServer) {this.byAccount = new Account(block.byAccount)this.blockedAccount = new Account(block.blockedAccount)this.createdAt = block.createdAt+ this.blocklistSubscription = block.blocklistSubscription}}diff --git a/client/src/app/shared/shared-moderation/blocklist.service.ts b/client/src/app/shared/shared-moderation/blocklist.service.tsindex 10ea22fbf7..0bff99bbab 100644--- a/client/src/app/shared/shared-moderation/blocklist.service.ts+++ b/client/src/app/shared/shared-moderation/blocklist.service.ts@@ -3,7 +3,14 @@ import { Injectable, inject } from '@angular/core'import { AuthUser, Notifier, RestExtractor, RestPagination, RestService } from '@app/core'import { formatICU } from '@app/helpers'import { arrayify } from '@peertube/peertube-core-utils'-import { AccountBlock as AccountBlockServer, BlockStatus, ResultList, ServerBlock, UserRight } from '@peertube/peertube-models'+import {+ AccountBlock as AccountBlockServer,+ BlockStatus,+ BlocklistSubscription,+ ResultList,+ ServerBlock,+ UserRight+} from '@peertube/peertube-models'import { SortMeta } from 'primeng/api'import { from } from 'rxjs'import { catchError, concatMap, map, tap, toArray } from 'rxjs/operators'@@ -37,11 +44,11 @@ export class BlocklistService {}canMuteAccountByInstance (user: AuthUser, account: Pick<Account, 'id'>) {- return user && account && user.account.id !== account.id && user.hasRight(UserRight.MANAGE_ACCOUNTS_BLOCKLIST)+ return user && account && user.account.id !== account.id && user.hasRight(UserRight.MANAGE_SERVER_ACCOUNTS_BLOCKLIST)}canMutePlatformByInstance (user: AuthUser, account: Pick<Account, 'host'>) {- return user && account && !Actor.IS_LOCAL(account.host) && user.hasRight(UserRight.MANAGE_SERVERS_BLOCKLIST)+ return user && account && !Actor.IS_LOCAL(account.host) && user.hasRight(UserRight.MANAGE_SERVER_SERVERS_BLOCKLIST)}// ---------------------------------------------------------------------------@@ -67,7 +74,7 @@ export class BlocklistService {// User -> Account blocklist// ---------------------------------------------------------------------------- getUserAccountBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string }) {+ listUserAccountBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string }) {const { pagination, sort, search } = optionslet params = new HttpParams()@@ -100,7 +107,7 @@ export class BlocklistService {// User -> Server blocklist// ---------------------------------------------------------------------------- getUserServerBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string }) {+ listUserServerBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string }) {const { pagination, sort, search } = optionslet params = new HttpParams()@@ -130,13 +137,14 @@ export class BlocklistService {// Instance -> Account blocklist// ---------------------------------------------------------------------------- getInstanceAccountBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string }) {- const { pagination, sort, search } = options+ listInstanceAccountBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string, subscriptionName?: string }) {+ const { pagination, sort, search, subscriptionName } = optionslet params = new HttpParams()params = this.restService.addRestGetParams(params, pagination, sort)if (search) params = params.append('search', search)+ if (subscriptionName) params = params.append('subscriptionName', subscriptionName)return this.authHttp.get<ResultList<AccountBlock>>(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/accounts', { params }).pipe(@@ -207,13 +215,14 @@ export class BlocklistService {// Instance -> Server blocklist// ---------------------------------------------------------------------------- getInstanceServerBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string }) {- const { pagination, sort, search } = options+ listInstanceServerBlocklist (options: { pagination: RestPagination, sort: SortMeta, search?: string, subscriptionName?: string }) {+ const { pagination, sort, search, subscriptionName } = optionslet params = new HttpParams()params = this.restService.addRestGetParams(params, pagination, sort)if (search) params = params.append('search', search)+ if (subscriptionName) params = params.append('subscriptionName', subscriptionName)return this.authHttp.get<ResultList<ServerBlock>>(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/servers', { params }).pipe(catchError(err => this.restExtractor.handleError(err)))@@ -277,6 +286,32 @@ export class BlocklistService {)}+ // ---------------------------------------------------------------------------+ // Blocklist subscriptions+ // ---------------------------------------------------------------------------++ listBlocklistSubscriptions (options: { pagination: RestPagination, sort: SortMeta, search?: string }) {+ const { pagination, sort, search } = options++ let params = new HttpParams()+ params = this.restService.addRestGetParams(params, pagination, sort)++ if (search) params = params.append('search', search)++ return this.authHttp.get<ResultList<BlocklistSubscription>>(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/subscriptions', { params })+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }++ addBlocklistSubscription (url: string) {+ return this.authHttp.post<BlocklistSubscription>(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/subscriptions', { url })+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }++ removeBlocklistSubscription (id: number) {+ return this.authHttp.delete(BlocklistService.BASE_SERVER_BLOCKLIST_URL + '/subscriptions/' + id)+ .pipe(catchError(err => this.restExtractor.handleError(err)))+ }+// ---------------------------------------------------------------------------private formatAccountBlock (accountBlock: AccountBlockServer) {diff --git a/client/src/app/shared/shared-moderation/generic-account-blocklist.component.html b/client/src/app/shared/shared-moderation/generic-account-blocklist.component.htmlindex 98d221e8d1..f2b4856fd9 100644--- a/client/src/app/shared/shared-moderation/generic-account-blocklist.component.html+++ b/client/src/app/shared/shared-moderation/generic-account-blocklist.component.html@@ -7,6 +7,7 @@[dataLoader]="dataLoader"columnConfig="false"searchInput="true"+ [inputFilters]="isInstanceMode() ? inputFilters : undefined"><ng-template #totalTitle let-totalRecords><ng-container i18n>{ totalRecords, plural, =0 {No account} =1 {1 account} other {{{ totalRecords | myNumberFormatter }} accounts}}</ng-container>@@ -27,6 +28,21 @@</td><td>{{ account.createdAt | ptDate: 'short' }}</td>++ @if (table.isColumnDisplayed('subscriptionName')) {+ <td>+ @if (account.blocklistSubscription) {+ <a+ [routerLink]="getBlocklistUrl()"+ [queryParams]="{ subscriptionName: account.blocklistSubscription.name }"+ i18n-title+ title="Filter muted accounts by this subscription"+ >+ <span class="pt-badge" [class]="getSubscriptionBadge(account.blocklistSubscription.name)">{{ account.blocklistSubscription.name }}</span>+ </a>+ }+ </td>+ }</ng-template><ng-template #actionCell let-account>diff --git a/client/src/app/shared/shared-moderation/generic-account-blocklist.component.ts b/client/src/app/shared/shared-moderation/generic-account-blocklist.component.tsindex d58ec71af5..b5e77c3565 100644--- a/client/src/app/shared/shared-moderation/generic-account-blocklist.component.ts+++ b/client/src/app/shared/shared-moderation/generic-account-blocklist.component.ts@@ -1,12 +1,19 @@import { Component, inject, input, viewChild } from '@angular/core'+import { AdvancedFilterDef } from '@app/shared/shared-forms/advanced-input-filter.component'import { Notifier } from '@app/core'+import { RouterLink } from '@angular/router'import { ActorAvatarComponent } from '../shared-actor-image/actor-avatar.component'import { PTDatePipe } from '../shared-main/common/date.pipe'import { NumberFormatterPipe } from '../shared-main/common/number-formatter.pipe'+import { PeerTubeBadgeService } from '../shared-main/common/peertube-badge.service'import { DataLoaderOptionsBase, TableColumnInfo, TableComponent } from '../shared-tables/table.component'import { AccountBlock } from './account-block.model'import { BlocklistComponentType, BlocklistService } from './blocklist.service'+type DataLoaderParameter = DataLoaderOptionsBase & {+ subscriptionName?: string+}+@Component({selector: 'my-generic-account-blocklist',templateUrl: './generic-account-blocklist.component.html',@@ -14,21 +21,38 @@ import { BlocklistComponentType, BlocklistService } from './blocklist.service'TableComponent,NumberFormatterPipe,ActorAvatarComponent,- PTDatePipe+ PTDatePipe,+ RouterLink]})export class GenericAccountBlocklistComponent {private notifier = inject(Notifier)+ private badgeService = inject(PeerTubeBadgeService)private blocklistService = inject(BlocklistService)readonly mode = input.required<BlocklistComponentType>()readonly key = input.required<string>()- readonly table = viewChild<TableComponent<AccountBlock>>('table')+ readonly table = viewChild<TableComponent<AccountBlock, DataLoaderParameter>>('table')++ readonly inputFilters: AdvancedFilterDef<DataLoaderParameter>[] = [+ {+ key: 'subscriptionName',+ type: 'text',+ title: $localize`Subscription list name`,+ placeholder: $localize`Filter by subscription name`+ }+ ]columns: TableColumnInfo<string>[] = [{ id: 'account', label: $localize`Account`, sortable: false },- { id: 'createdAt', label: $localize`Muted at`, sortable: true }+ { id: 'createdAt', label: $localize`Muted at`, sortable: true },+ {+ id: 'subscriptionName',+ label: $localize`Subscription list name`,+ sortable: false,+ isDisplayed: () => this.mode() === BlocklistComponentType.Instance+ }]dataLoader: typeof this._dataLoader@@ -57,11 +81,23 @@ export class GenericAccountBlocklistComponent {)}- private _dataLoader (options: DataLoaderOptionsBase) {+ getSubscriptionBadge (name: string) {+ return this.badgeService.getRandomBadge('subscription', name)+ }++ isInstanceMode () {+ return this.mode() === BlocklistComponentType.Instance+ }++ getBlocklistUrl () {+ return '/admin/moderation/blocklist/accounts'+ }++ private _dataLoader (options: DataLoaderParameter) {if (this.mode() === BlocklistComponentType.Account) {- return this.blocklistService.getUserAccountBlocklist(options)+ return this.blocklistService.listUserAccountBlocklist(options)}- return this.blocklistService.getInstanceAccountBlocklist(options)+ return this.blocklistService.listInstanceAccountBlocklist(options)}}diff --git a/client/src/app/shared/shared-moderation/generic-server-blocklist.component.html b/client/src/app/shared/shared-moderation/generic-server-blocklist.component.htmlindex c439a2de22..38052776ba 100644--- a/client/src/app/shared/shared-moderation/generic-server-blocklist.component.html+++ b/client/src/app/shared/shared-moderation/generic-server-blocklist.component.html@@ -7,6 +7,7 @@[dataLoader]="dataLoader"columnConfig="false"searchInput="true"+ [inputFilters]="isInstanceMode() ? inputFilters : undefined"><ng-template #totalTitle let-totalRecords><ng-container i18n>{ totalRecords, plural, =0 {No server} =1 {1 server} other {{{ totalRecords | myNumberFormatter }} servers}}</ng-container>@@ -28,6 +29,21 @@</td><td>{{ serverBlock.createdAt | ptDate: 'short' }}</td>++ @if (table.isColumnDisplayed('subscriptionName')) {+ <td>+ @if (serverBlock.blocklistSubscription) {+ <a+ [routerLink]="getBlocklistUrl()"+ [queryParams]="{ subscriptionName: serverBlock.blocklistSubscription.name }"+ i18n-title+ title="Filter muted servers by this subscription"+ >+ <span class="pt-badge" [class]="getSubscriptionBadge(serverBlock.blocklistSubscription.name)">{{ serverBlock.blocklistSubscription.name }}</span>+ </a>+ }+ </td>+ }</ng-template><ng-template #actionCell let-serverBlock>diff --git a/client/src/app/shared/shared-moderation/generic-server-blocklist.component.ts b/client/src/app/shared/shared-moderation/generic-server-blocklist.component.tsindex 8382407c58..ad08458632 100644--- a/client/src/app/shared/shared-moderation/generic-server-blocklist.component.ts+++ b/client/src/app/shared/shared-moderation/generic-server-blocklist.component.ts@@ -1,13 +1,20 @@import { Component, inject, input, viewChild } from '@angular/core'import { Notifier } from '@app/core'+import { RouterLink } from '@angular/router'+import { AdvancedFilterDef } from '@app/shared/shared-forms/advanced-input-filter.component'import { BatchDomainsModalComponent } from '@app/shared/shared-moderation/batch-domains-modal.component'import { ServerBlock } from '@peertube/peertube-models'import { GlobalIconComponent } from '../shared-icons/global-icon.component'import { PTDatePipe } from '../shared-main/common/date.pipe'import { NumberFormatterPipe } from '../shared-main/common/number-formatter.pipe'+import { PeerTubeBadgeService } from '../shared-main/common/peertube-badge.service'import { DataLoaderOptionsBase, TableColumnInfo, TableComponent } from '../shared-tables/table.component'import { BlocklistComponentType, BlocklistService } from './blocklist.service'+type DataLoaderParameter = DataLoaderOptionsBase & {+ subscriptionName?: string+}+@Component({selector: 'my-generic-server-blocklist',templateUrl: './generic-server-blocklist.component.html',@@ -16,22 +23,39 @@ import { BlocklistComponentType, BlocklistService } from './blocklist.service'NumberFormatterPipe,PTDatePipe,GlobalIconComponent,- BatchDomainsModalComponent+ BatchDomainsModalComponent,+ RouterLink]})export class GenericServerBlocklistComponent {private notifier = inject(Notifier)+ private badgeService = inject(PeerTubeBadgeService)private blocklistService = inject(BlocklistService)readonly mode = input.required<BlocklistComponentType>()readonly key = input.required<string>()readonly batchDomainsModal = viewChild<BatchDomainsModalComponent>('batchDomainsModal')- readonly table = viewChild<TableComponent<ServerBlock>>('table')+ readonly table = viewChild<TableComponent<ServerBlock, DataLoaderParameter>>('table')++ readonly inputFilters: AdvancedFilterDef<DataLoaderParameter>[] = [+ {+ key: 'subscriptionName',+ type: 'text',+ title: $localize`Subscription list name`,+ placeholder: $localize`Filter by subscription name`+ }+ ]columns: TableColumnInfo<string>[] = [{ id: 'server', label: $localize`Server`, sortable: false },- { id: 'createdAt', label: $localize`Muted at`, sortable: true }+ { id: 'createdAt', label: $localize`Muted at`, sortable: true },+ {+ id: 'subscriptionName',+ label: $localize`Subscription list name`,+ sortable: false,+ isDisplayed: () => this.mode() === BlocklistComponentType.Instance+ }]dataLoader: typeof this._dataLoader@@ -85,11 +109,23 @@ export class GenericServerBlocklistComponent {})}- private _dataLoader (options: DataLoaderOptionsBase) {+ getSubscriptionBadge (name: string) {+ return this.badgeService.getRandomBadge('subscription', name)+ }++ getBlocklistUrl () {+ return '/admin/moderation/blocklist/servers'+ }++ isInstanceMode () {+ return this.mode() === BlocklistComponentType.Instance+ }++ private _dataLoader (options: DataLoaderParameter) {if (this.mode() === BlocklistComponentType.Account) {- return this.blocklistService.getUserServerBlocklist(options)+ return this.blocklistService.listUserServerBlocklist(options)}- return this.blocklistService.getInstanceServerBlocklist(options)+ return this.blocklistService.listInstanceServerBlocklist(options)}}diff --git a/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.ts b/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.tsindex d6eee39322..a1b616ac5a 100644--- a/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.ts+++ b/client/src/app/shared/shared-moderation/user-moderation-dropdown.component.ts@@ -360,9 +360,9 @@ export class UserModerationDropdownComponent implements OnInit, OnChanges {authUser.canManageUser(this.user())const hasAccountBlocklistRight = this.account() && displayOptions.instanceAccount &&- authUser.hasRight(UserRight.MANAGE_ACCOUNTS_BLOCKLIST)+ authUser.hasRight(UserRight.MANAGE_SERVER_ACCOUNTS_BLOCKLIST)const hasServerBlocklistRight = this.account() && displayOptions.instanceAccount &&- authUser.hasRight(UserRight.MANAGE_SERVERS_BLOCKLIST)+ authUser.hasRight(UserRight.MANAGE_SERVER_SERVERS_BLOCKLIST)const hasBulkRemoveCommentsRight = this.account() && displayOptions.instanceAccount &&authUser.hasRight(UserRight.MANAGE_ANY_VIDEO_COMMENT)diff --git a/client/src/app/shared/shared-notifications/user-notification-content.component.html b/client/src/app/shared/shared-notifications/user-notification-content.component.htmlindex 92e4824f55..2d8907ef45 100644--- a/client/src/app/shared/shared-notifications/user-notification-content.component.html+++ b/client/src/app/shared/shared-notifications/user-notification-content.component.html@@ -337,6 +337,25 @@</div>}+ @case (32) { <!-- UserNotificationType.AUTOMATIC_BLOCKLIST_UPDATE -->+ <my-global-icon iconName="no"></my-global-icon>++ <div class="message">+ <span i18n>Automatic blocklist update: </span>+ @if (n.payload.data?.blockedAccountsCount || n.payload.data?.blockedHostsCount) {+ <span i18n>+ <strong>{{ n.payload.data?.blockedAccountsCount || 0 }}</strong> accounts and <strong>{{ n.payload.data?.blockedHostsCount || 0 }}</strong> servers were blocked. + </span>+ }++ @if (n.payload.data?.unblockedAccountsCount || n.payload.data?.unblockedHostsCount) {+ <span i18n>+ <strong>{{ n.payload.data?.unblockedAccountsCount || 0 }}</strong> accounts and <strong>{{ n.payload.data?.unblockedHostsCount || 0 }}</strong> servers were unblocked.+ </span>+ }+ </div>+ }+@default {<my-global-icon iconName="alert"></my-global-icon>diff --git a/client/src/app/shared/shared-tables/state-badge.ts b/client/src/app/shared/shared-tables/state-badge.tsnew file mode 100644index 0000000000..ecc059b811--- /dev/null+++ b/client/src/app/shared/shared-tables/state-badge.ts@@ -0,0 +1,12 @@+import { StreamSyncState, StreamSyncStateType } from '@peertube/peertube-models'++const STATE_CLASS_BY_ID = {+ [StreamSyncState.FAILED]: 'badge-red',+ [StreamSyncState.PROCESSING]: 'badge-blue',+ [StreamSyncState.SYNCED]: 'badge-green',+ [StreamSyncState.WAITING_FIRST_RUN]: 'badge-yellow'+}++export function getStateBadgeClasses (stateId: StreamSyncStateType) {+ return [ 'pt-badge', STATE_CLASS_BY_ID[stateId] ]+}diff --git a/client/src/sass/z-index.scss b/client/src/sass/z-index.scssindex 4aeee71bed..f1c360f517 100644--- a/client/src/sass/z-index.scss+++ b/client/src/sass/z-index.scss@@ -39,7 +39,7 @@ body > .p-overlay {z-index: z(dropdown) + 1 !important;}-p-toast .p-toast {+p-toast {z-index: z(notification) !important;}diff --git a/config/default.yaml b/config/default.yamlindex f42e942f9d..bc369cdccd 100644--- a/config/default.yaml+++ b/config/default.yaml@@ -1096,6 +1096,11 @@ followings:# Host your own using https://framagit.org/framasoft/peertube/instances-peertube#peertube-auto-followindex_url: ''+blocklist:+ # Enable /api/v1/server/blocklist/public-log endpoint on your instance to share your blocklist with other instances+ public_log:+ enabled: false+theme:default: 'default'diff --git a/config/production.yaml.example b/config/production.yaml.exampleindex 5e362451a4..bd144ce3e9 100644--- a/config/production.yaml.example+++ b/config/production.yaml.example@@ -1106,6 +1106,11 @@ followings:# Host your own using https://framagit.org/framasoft/peertube/instances-peertube#peertube-auto-followindex_url: ''+blocklist:+ # Enable /api/v1/server/blocklist/public-log endpoint on your instance to share your blocklist with other instances+ public_log:+ enabled: false+theme:default: 'default'diff --git a/packages/core-utils/src/users/user-role.ts b/packages/core-utils/src/users/user-role.tsindex 04af3af7ce..cd9f931c9b 100644--- a/packages/core-utils/src/users/user-role.ts+++ b/packages/core-utils/src/users/user-role.ts@@ -22,6 +22,7 @@ const userRoleRights: { [id in UserRoleType]: UserRightType[] } = {UserRight.SEE_ALL_VIDEOS,UserRight.MANAGE_SERVER_ACCOUNTS_BLOCKLIST,UserRight.MANAGE_SERVER_SERVERS_BLOCKLIST,+ UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS,UserRight.MANAGE_USERS,UserRight.SEE_ALL_COMMENTS,UserRight.MANAGE_REGISTRATIONS,diff --git a/packages/models/src/common/index.ts b/packages/models/src/common/index.tsindex 87fe5d8b41..c9417beef1 100644--- a/packages/models/src/common/index.ts+++ b/packages/models/src/common/index.ts@@ -3,3 +3,4 @@ export * from './constant-label.model.js'export * from './peertube-error.model.js'export * from './result-list.model.js'export * from './simple-logger.model.js'+export * from './stream-sync-state.enum.js'diff --git a/packages/models/src/common/stream-sync-state.enum.ts b/packages/models/src/common/stream-sync-state.enum.tsnew file mode 100644index 0000000000..74b312e635--- /dev/null+++ b/packages/models/src/common/stream-sync-state.enum.ts@@ -0,0 +1,8 @@+export const StreamSyncState = {+ WAITING_FIRST_RUN: 1,+ PROCESSING: 2,+ SYNCED: 3,+ FAILED: 4+} as const++export type StreamSyncStateType = typeof StreamSyncState[keyof typeof StreamSyncState]diff --git a/packages/models/src/moderation/account-block.model.ts b/packages/models/src/moderation/account-block.model.tsindex 2d070da62f..913057471f 100644--- a/packages/models/src/moderation/account-block.model.ts+++ b/packages/models/src/moderation/account-block.model.ts@@ -4,4 +4,10 @@ export interface AccountBlock {byAccount: AccountblockedAccount: AccountcreatedAt: Date | string++ blocklistSubscription?: {+ id: number+ name: string+ url: string+ }}diff --git a/packages/models/src/moderation/auto-mute-list.model.ts b/packages/models/src/moderation/auto-mute-list.model.tsnew file mode 100644index 0000000000..4ddf58171b--- /dev/null+++ b/packages/models/src/moderation/auto-mute-list.model.ts@@ -0,0 +1,12 @@+export type AutoMuteActionType = 'block' | 'unblock'++export interface AutoMuteAction {+ type: AutoMuteActionType+ target: string+ createdAt: string+}++export interface AutoMuteList {+ name: string+ actions: AutoMuteAction[]+}diff --git a/packages/models/src/moderation/block-status.model.ts b/packages/models/src/moderation/block-status.model.tsindex 597312757b..132333ebaf 100644--- a/packages/models/src/moderation/block-status.model.ts+++ b/packages/models/src/moderation/block-status.model.ts@@ -1,15 +1,19 @@export interface BlockStatus {accounts: {- [ handle: string ]: {+ [handle: string]: {blockedByServer: boolean- blockedByUser?: boolean+ blockedByServerSubscription: string | null++ blockedByUser: boolean}}hosts: {- [ host: string ]: {+ [host: string]: {blockedByServer: boolean- blockedByUser?: boolean+ blockedByServerSubscription: string | null++ blockedByUser: boolean}}}diff --git a/packages/models/src/moderation/blocklist-log.model.ts b/packages/models/src/moderation/blocklist-log.model.tsnew file mode 100644index 0000000000..07e61d640b--- /dev/null+++ b/packages/models/src/moderation/blocklist-log.model.ts@@ -0,0 +1,8 @@+export type BlocklistLogAction = 'add' | 'delete'++export interface BlocklistLog {+ id: number+ action: BlocklistLogAction+ target: string+ createdAt: Date | string+}diff --git a/packages/models/src/moderation/blocklist-subscription.model.ts b/packages/models/src/moderation/blocklist-subscription.model.tsnew file mode 100644index 0000000000..63dcdd2fc3--- /dev/null+++ b/packages/models/src/moderation/blocklist-subscription.model.ts@@ -0,0 +1,18 @@+import { ConstantLabel } from '../common/constant-label.model.js'+import { StreamSyncStateType } from '../common/stream-sync-state.enum.js'++export interface BlocklistSubscription {+ id: number+ name: string+ url: string++ lastSyncAt: Date | string++ state: ConstantLabel<StreamSyncStateType>++ createdAt: Date | string+ updatedAt: Date | string++ mutedAccountsCount: number+ mutedServersCount: number+}diff --git a/packages/models/src/moderation/index.ts b/packages/models/src/moderation/index.tsindex fb27da7e02..671119611c 100644--- a/packages/models/src/moderation/index.ts+++ b/packages/models/src/moderation/index.ts@@ -4,6 +4,9 @@ export * from './account-block.model.js'export * from './comment-automatic-tag-policies-update.model.js'export * from './comment-automatic-tag-policies.model.js'export * from './automatic-tag-policy.enum.js'+export * from './auto-mute-list.model.js'export * from './block-status.model.js'+export * from './blocklist-log.model.js'+export * from './blocklist-subscription.model.js'export * from './server-block.model.js'export * from './watched-words-list.model.js'diff --git a/packages/models/src/moderation/server-block.model.ts b/packages/models/src/moderation/server-block.model.tsindex b85646fc62..5c6d9378bf 100644--- a/packages/models/src/moderation/server-block.model.ts+++ b/packages/models/src/moderation/server-block.model.ts@@ -2,8 +2,16 @@ import { Account } from '../actors/index.js'export interface ServerBlock {byAccount: Account+blockedServer: {host: string}++ blocklistSubscription?: {+ id: number+ name: string+ url: string+ }+createdAt: Date | string}diff --git a/packages/models/src/server/custom-config.model.ts b/packages/models/src/server/custom-config.model.tsindex aa23d2947b..f9034b1650 100644--- a/packages/models/src/server/custom-config.model.ts+++ b/packages/models/src/server/custom-config.model.ts@@ -289,6 +289,12 @@ export interface CustomConfig {}}+ blocklist: {+ publicLog: {+ enabled: boolean+ }+ }+followers: {instance: {enabled: booleandiff --git a/packages/models/src/server/server-config.model.ts b/packages/models/src/server/server-config.model.tsindex f3a4f92f63..e18493b018 100644--- a/packages/models/src/server/server-config.model.ts+++ b/packages/models/src/server/server-config.model.ts@@ -330,6 +330,12 @@ export interface ServerConfig {}}+ blocklist: {+ publicLog: {+ enabled: boolean+ }+ }+avatar: {file: FileConstraints}diff --git a/packages/models/src/users/user-notification-data.model.ts b/packages/models/src/users/user-notification-data.model.tsindex e458daa661..babf3d750d 100644--- a/packages/models/src/users/user-notification-data.model.ts+++ b/packages/models/src/users/user-notification-data.model.ts@@ -1 +1,6 @@-export type UserNotificationData = {}+export type UserNotificationData = {+ blockedAccountsCount: number+ blockedHostsCount: number+ unblockedAccountsCount: number+ unblockedHostsCount: number+}diff --git a/packages/models/src/users/user-notification-setting.model.ts b/packages/models/src/users/user-notification-setting.model.tsindex 64d8cfb2da..b7f58b5067 100644--- a/packages/models/src/users/user-notification-setting.model.ts+++ b/packages/models/src/users/user-notification-setting.model.ts@@ -33,4 +33,6 @@ export interface UserNotificationSetting {myVideoStudioEditionFinished: UserNotificationSettingValueTypemyVideoTranscriptionGenerated: UserNotificationSettingValueType++ automaticBlocklist: UserNotificationSettingValueType}diff --git a/packages/models/src/users/user-notification.model.ts b/packages/models/src/users/user-notification.model.tsindex eb841d8cfd..bbed0476a1 100644--- a/packages/models/src/users/user-notification.model.ts+++ b/packages/models/src/users/user-notification.model.ts@@ -54,7 +54,9 @@ export const UserNotificationType = {CHANNEL_OWNERSHIP_CHANGED_REQUEST: 29,CHANNEL_OWNERSHIP_CHANGED_ACCEPTED: 30,- CHANNEL_OWNERSHIP_CHANGED_REJECTED: 31+ CHANNEL_OWNERSHIP_CHANGED_REJECTED: 31,++ AUTOMATIC_BLOCKLIST_UPDATE: 32} as constexport type UserNotificationType_Type = typeof UserNotificationType[keyof typeof UserNotificationType]diff --git a/packages/models/src/users/user-right.enum.ts b/packages/models/src/users/user-right.enum.tsindex 9f5e52db29..b10d69f9f8 100644--- a/packages/models/src/users/user-right.enum.ts+++ b/packages/models/src/users/user-right.enum.ts@@ -53,7 +53,9 @@ export const UserRight = {MANAGE_USER_IMPORTS: 31,MANAGE_INSTANCE_WATCHED_WORDS: 32,- MANAGE_INSTANCE_AUTO_TAGS: 33+ MANAGE_INSTANCE_AUTO_TAGS: 33,++ MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS: 34} as constexport type UserRightType = typeof UserRight[keyof typeof UserRight]diff --git a/packages/models/src/videos/channel-sync/index.ts b/packages/models/src/videos/channel-sync/index.tsindex 206cbe1b63..3cc981ac90 100644--- a/packages/models/src/videos/channel-sync/index.ts+++ b/packages/models/src/videos/channel-sync/index.ts@@ -1,3 +1,2 @@-export * from './video-channel-sync-state.enum.js'export * from './video-channel-sync.model.js'export * from './video-channel-sync-create.model.js'diff --git a/packages/models/src/videos/channel-sync/video-channel-sync-state.enum.ts b/packages/models/src/videos/channel-sync/video-channel-sync-state.enum.tsdeleted file mode 100644index 047444bbc3..0000000000--- a/packages/models/src/videos/channel-sync/video-channel-sync-state.enum.ts+++ /dev/null@@ -1,8 +0,0 @@-export const VideoChannelSyncState = {- WAITING_FIRST_RUN: 1,- PROCESSING: 2,- SYNCED: 3,- FAILED: 4-} as const--export type VideoChannelSyncStateType = typeof VideoChannelSyncState[keyof typeof VideoChannelSyncState]diff --git a/packages/models/src/videos/channel-sync/video-channel-sync.model.ts b/packages/models/src/videos/channel-sync/video-channel-sync.model.tsindex a4e6a7590d..d1a89dd2a5 100644--- a/packages/models/src/videos/channel-sync/video-channel-sync.model.ts+++ b/packages/models/src/videos/channel-sync/video-channel-sync.model.ts@@ -1,6 +1,6 @@import { VideoChannelSummary } from '../channel/video-channel.model.js'import { ConstantLabel } from '../../common/constant-label.model.js'-import { VideoChannelSyncStateType } from './video-channel-sync-state.enum.js'+import { StreamSyncStateType } from '../../common/stream-sync-state.enum.js'export interface VideoChannelSync {id: number@@ -9,6 +9,6 @@ export interface VideoChannelSync {createdAt: stringchannel: VideoChannelSummary- state: ConstantLabel<VideoChannelSyncStateType>+ state: ConstantLabel<StreamSyncStateType>lastSyncAt: string}diff --git a/packages/server-commands/src/users/blocklist-command.ts b/packages/server-commands/src/users/blocklist-command.tsindex e8f66a9a45..b4ba1d1ff3 100644--- a/packages/server-commands/src/users/blocklist-command.ts+++ b/packages/server-commands/src/users/blocklist-command.ts@@ -1,6 +1,15 @@/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { AccountBlock, BlockStatus, HttpStatusCode, ResultList, ServerBlock } from '@peertube/peertube-models'+import {+ AccountBlock,+ AutoMuteList,+ BlockStatus,+ BlocklistSubscription,+ HttpStatusCode,+ ResultList,+ ServerBlock+} from '@peertube/peertube-models'+import { unwrapBody } from '../requests/requests.js'import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'type ListBlocklistOptions = OverrideCommandOptions & {@@ -10,6 +19,7 @@ type ListBlocklistOptions = OverrideCommandOptions & {sort?: string // default -createdAtsearch?: string+ subscriptionName?: string}export class BlocklistCommand extends AbstractCommand {@@ -159,15 +169,89 @@ export class BlocklistCommand extends AbstractCommand {}private listBlocklist<T> (options: ListBlocklistOptions, path: string) {- const { start, count, search, sort = '-createdAt' } = options+ const { start, count, search, subscriptionName, sort = '-createdAt' } = optionsreturn this.getRequestBody<ResultList<T>>({...options,+ path,+ query: { start, count, sort, search, subscriptionName },+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.OK_200+ })+ }++ // ---------------------------------------------------------------------------++ listServerBlocklistSubscriptions (options: OverrideCommandOptions & {+ start?: number+ count?: number++ sort?: string // default -createdAt++ search?: string+ } = {}) {+ const { start, count, search, sort = '-createdAt' } = options++ const path = '/api/v1/server/blocklist/subscriptions'++ return this.getRequestBody<ResultList<BlocklistSubscription>>({+ ...options,+path,query: { start, count, sort, search },implicitToken: true,defaultExpectedStatus: HttpStatusCode.OK_200})}++ addServerBlocklistSubscription (+ options: OverrideCommandOptions & {+ subscriptionUrl: string+ }+ ) {+ const path = '/api/v1/server/blocklist/subscriptions'++ return unwrapBody<BlocklistSubscription>(this.postBodyRequest({+ ...options,++ path,+ fields: {+ url: options.subscriptionUrl+ },+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.OK_200+ }))+ }++ removeServerBlocklistSubscription (+ options: OverrideCommandOptions & {+ id: number | string+ }+ ) {+ const path = '/api/v1/server/blocklist/subscriptions/' + options.id++ return this.deleteRequest({+ ...options,++ path,+ implicitToken: true,+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204+ })+ }++ listServerPublicBlocklistLog (+ options: OverrideCommandOptions & {+ startDate?: string+ } = {}+ ) {+ return this.getRequestBody<AutoMuteList>({+ ...options,++ path: '/api/v1/server/blocklist/public-log',+ query: options.startDate ? { startDate: options.startDate } : undefined,+ implicitToken: false,+ defaultExpectedStatus: HttpStatusCode.OK_200+ })+ }}diff --git a/packages/tests/src/api/check-params/blocklist-subscriptions.ts b/packages/tests/src/api/check-params/blocklist-subscriptions.tsnew file mode 100644index 0000000000..5565444f11--- /dev/null+++ b/packages/tests/src/api/check-params/blocklist-subscriptions.ts@@ -0,0 +1,205 @@+/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { HttpStatusCode } from '@peertube/peertube-models'+import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@peertube/peertube-server-commands'+import { checkBadCountPagination, checkBadSort, checkBadStartPagination } from '@tests/shared/checks.js'+import { MockCoreBlocklist } from '@tests/shared/mock-servers/mock-core-blocklist.js'++describe('Test blocklist subscriptions API validators', function () {+ let server: PeerTubeServer+ let mockServer: MockCoreBlocklist+ let mockPort: number+ let userAccessToken: string++ before(async function () {+ server = await createSingleServer(1)++ await setAccessTokensToServers([ server ])++ mockServer = new MockCoreBlocklist()+ mockPort = await mockServer.initialize()++ userAccessToken = await server.users.generateUserAndToken('user1')+ })++ describe('When managing blocklist subscriptions', function () {+ const path = '/api/v1/server/blocklist/subscriptions'++ describe('When listing subscriptions', function () {+ it('Should fail with an unauthenticated user', async function () {+ await server.blocklist.listServerBlocklistSubscriptions({+ token: null,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a user without the appropriate rights', async function () {+ await server.blocklist.listServerBlocklistSubscriptions({+ token: userAccessToken,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with a bad start pagination', async function () {+ await checkBadStartPagination(server.url, path, server.accessToken)+ })++ it('Should fail with a bad count pagination', async function () {+ await checkBadCountPagination(server.url, path, server.accessToken)+ })++ it('Should fail with an incorrect sort', async function () {+ await checkBadSort(server.url, path, server.accessToken)+ })++ it('Should succeed with valid params', async function () {+ await server.blocklist.listServerBlocklistSubscriptions()+ })+ })++ describe('When adding subscriptions', function () {+ it('Should fail with an unauthenticated user', async function () {+ await server.blocklist.addServerBlocklistSubscription({+ token: null,+ subscriptionUrl: `http://127.0.0.1:${mockPort}/list.json`,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a user without the appropriate rights', async function () {+ await server.blocklist.addServerBlocklistSubscription({+ token: userAccessToken,+ subscriptionUrl: `http://127.0.0.1:${mockPort}/list.json`,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with an invalid URL', async function () {+ await server.blocklist.addServerBlocklistSubscription({+ subscriptionUrl: 'invalid',+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail with an URL that does not have the right format', async function () {+ await server.blocklist.addServerBlocklistSubscription({+ subscriptionUrl: `http://127.0.0.1:${mockPort}/invalid-blocklist-1`,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })++ await server.blocklist.addServerBlocklistSubscription({+ subscriptionUrl: `http://127.0.0.1:${mockPort}/invalid-blocklist-2`,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should succeed with valid params', async function () {+ await server.blocklist.addServerBlocklistSubscription({ subscriptionUrl: `http://127.0.0.1:${mockPort}/list.json` })+ })++ it('Should fail with an already existing URL', async function () {+ await server.blocklist.addServerBlocklistSubscription({+ subscriptionUrl: `http://127.0.0.1:${mockPort}/list.json`,+ expectedStatus: HttpStatusCode.CONFLICT_409+ })+ })+ })++ describe('When deleting subscriptions', function () {+ let subscriptionId: number++ before(async function () {+ const { data } = await server.blocklist.listServerBlocklistSubscriptions()+ subscriptionId = data[0].id+ })++ it('Should fail with an unauthenticated user', async function () {+ await server.blocklist.removeServerBlocklistSubscription({+ token: null,+ id: subscriptionId,+ expectedStatus: HttpStatusCode.UNAUTHORIZED_401+ })+ })++ it('Should fail with a user without the appropriate rights', async function () {+ await server.blocklist.removeServerBlocklistSubscription({+ token: userAccessToken,+ id: subscriptionId,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with an invalid id', async function () {+ await server.blocklist.removeServerBlocklistSubscription({+ id: 'invalid',+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should fail with an unknown id', async function () {+ await server.blocklist.removeServerBlocklistSubscription({+ id: 999999,+ expectedStatus: HttpStatusCode.NOT_FOUND_404+ })+ })++ it('Should succeed with valid params', async function () {+ await server.blocklist.removeServerBlocklistSubscription({ id: subscriptionId })+ })+ })+ })++ describe('When listing public blocklist log', function () {+ it('Should fail if not enabled by the config', async function () {+ await server.blocklist.listServerPublicBlocklistLog({+ startDate: new Date().toISOString(),+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should fail with an invalid start date', async function () {+ await server.config.updateExistingConfig({+ newConfig: {+ blocklist: {+ publicLog: {+ enabled: true+ }+ }+ }+ })++ await server.blocklist.listServerPublicBlocklistLog({+ startDate: 'invalid-date',+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })+ })++ it('Should succeed with valid params', async function () {+ await server.blocklist.listServerPublicBlocklistLog({ startDate: new Date().toISOString() })+ await server.blocklist.listServerPublicBlocklistLog()+ })++ it('Should fail again when disabled in config', async function () {+ await server.config.updateExistingConfig({+ newConfig: {+ blocklist: {+ publicLog: {+ enabled: false+ }+ }+ }+ })++ await server.blocklist.listServerPublicBlocklistLog({+ startDate: new Date().toISOString(),+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })+ })++ after(async function () {+ await cleanupTests([ server ])++ await mockServer.terminate()+ })+})diff --git a/packages/tests/src/api/check-params/user-notifications.ts b/packages/tests/src/api/check-params/user-notifications.tsindex b1c032b650..4075ea910f 100644--- a/packages/tests/src/api/check-params/user-notifications.ts+++ b/packages/tests/src/api/check-params/user-notifications.ts@@ -175,7 +175,8 @@ describe('Test user notifications API validators', function () {newPeerTubeVersion: UserNotificationSettingValue.WEB,myVideoStudioEditionFinished: UserNotificationSettingValue.WEB,myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB,- newPluginVersion: UserNotificationSettingValue.WEB+ newPluginVersion: UserNotificationSettingValue.WEB,+ automaticBlocklist: UserNotificationSettingValue.WEB}it('Should fail with missing fields', async function () {diff --git a/packages/tests/src/api/moderation/blocklist-subscriptions.ts b/packages/tests/src/api/moderation/blocklist-subscriptions.tsnew file mode 100644index 0000000000..51f6d8211a--- /dev/null+++ b/packages/tests/src/api/moderation/blocklist-subscriptions.ts@@ -0,0 +1,359 @@+/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { wait } from '@peertube/peertube-core-utils'+import {+ cleanupTests,+ createSingleServer,+ doubleFollow,+ PeerTubeServer,+ setAccessTokensToServers+} from '@peertube/peertube-server-commands'+import { MockCoreBlocklist } from '@tests/shared/mock-servers/mock-core-blocklist.js'+import { expect } from 'chai'++describe('Test blocklist subscriptions', function () {+ let server: PeerTubeServer+ let mockServer: MockCoreBlocklist+ let mockPort: number+ let subscriptionId: number++ before(async function () {+ server = await createSingleServer(1)+ await setAccessTokensToServers([ server ])++ mockServer = new MockCoreBlocklist()+ mockPort = await mockServer.initialize()+ })++ describe('When managing subscription endpoints', function () {+ it('Should add subscriptions', async function () {+ {+ const body = await server.blocklist.addServerBlocklistSubscription({ subscriptionUrl: `http://127.0.0.1:${mockPort}/list.json` })++ expect(body.name).to.equal('Test subscription')+ expect(body.url).to.equal(`http://127.0.0.1:${mockPort}/list.json`)++ subscriptionId = body.id+ }++ {+ const body = await server.blocklist.addServerBlocklistSubscription({ subscriptionUrl: `http://127.0.0.1:${mockPort}/list-2` })++ expect(body.name).to.equal('another subscription list')+ expect(body.url).to.equal(`http://127.0.0.1:${mockPort}/list-2`)+ }+ })++ it('Should list subscriptions', async function () {+ const body = await server.blocklist.listServerBlocklistSubscriptions({ sort: 'createdAt' })++ expect(body.total).to.equal(2)+ expect(body.data).to.have.lengthOf(2)++ {+ const subscription = body.data[0]+ expect(subscription.name).to.equal('Test subscription')+ expect(subscription.url).to.equal(`http://127.0.0.1:${mockPort}/list.json`)+ expect(subscription.mutedAccountsCount).to.equal(0)+ expect(subscription.mutedServersCount).to.equal(0)+ expect(subscription.createdAt).to.exist+ expect(subscription.updatedAt).to.exist+ expect(subscription.lastSyncAt).to.be.null+ }++ {+ const subscription = body.data[1]+ expect(subscription.name).to.equal('another subscription list')+ expect(subscription.url).to.equal(`http://127.0.0.1:${mockPort}/list-2`)+ expect(subscription.mutedAccountsCount).to.equal(0)+ expect(subscription.mutedServersCount).to.equal(0)+ }+ })++ it('Should search subscriptions', async function () {+ const body = await server.blocklist.listServerBlocklistSubscriptions({ search: 'another' })++ expect(body.total).to.equal(1)+ expect(body.data).to.have.lengthOf(1)++ const subscription = body.data[0]+ expect(subscription.name).to.equal('another subscription list')+ })++ it('Should sort and paginate subscriptions', async function () {+ {+ const body = await server.blocklist.listServerBlocklistSubscriptions({ sort: 'name' })++ expect(body.total).to.equal(2)+ expect(body.data).to.have.lengthOf(2)++ expect(body.data.map(d => d.name)).to.deep.equal([ 'another subscription list', 'Test subscription' ])+ }++ {+ const body = await server.blocklist.listServerBlocklistSubscriptions({ sort: '-name' })++ expect(body.total).to.equal(2)+ expect(body.data).to.have.lengthOf(2)++ expect(body.data.map(d => d.name)).to.deep.equal([ 'Test subscription', 'another subscription list' ])+ }++ {+ const body = await server.blocklist.listServerBlocklistSubscriptions({ start: 1, count: 1, sort: '-name' })++ expect(body.total).to.equal(2)+ expect(body.data).to.have.lengthOf(1)++ expect(body.data[0].name).to.equal('another subscription list')+ }+ })+ })++ describe('When synchronizing a subscription', function () {+ let server2: PeerTubeServer+ let mutedHandle1: string+ let mutedHandle2: string+ const mutedHost = 'example.com'++ before(async function () {+ server2 = await createSingleServer(2)+ await setAccessTokensToServers([ server2 ])++ const tokenMuted1 = await server.users.generateUserAndToken('muted1')+ const tokenMuted2 = await server.users.generateUserAndToken('muted2')++ mutedHandle1 = `muted1@${server.host}`+ mutedHandle2 = `muted2@${server.host}`++ await server.videos.quickUpload({ name: 'muted video', token: tokenMuted1 })+ await server.videos.quickUpload({ name: 'muted video', token: tokenMuted2 })++ await doubleFollow(server, server2)+ })++ it('Should automatically block and unblock from subscription actions', async function () {+ this.timeout(120_000)++ const now = Date.now()++ mockServer.setActions([+ { type: 'block', target: mutedHost, createdAt: new Date(now - 1000).toISOString() },+ { type: 'block', target: mutedHandle1, createdAt: new Date(now - 1000).toISOString() },+ { type: 'block', target: mutedHandle2, createdAt: new Date(now - 1000).toISOString() }+ ])++ await wait(8000)++ {+ const body = await server.blocklist.getStatus({+ accounts: [ mutedHandle1, mutedHandle2 ],+ hosts: [ mutedHost ]+ })++ expect(body.accounts[mutedHandle1].blockedByServer).to.be.true+ expect(body.accounts[mutedHandle1].blockedByServerSubscription).to.equal('Test subscription')+ expect(body.accounts[mutedHandle1].blockedByUser).to.be.false++ expect(body.accounts[mutedHandle2].blockedByServer).to.be.true+ expect(body.accounts[mutedHandle1].blockedByUser).to.be.false+ expect(body.accounts[mutedHandle2].blockedByServerSubscription).to.equal('Test subscription')++ expect(body.hosts[mutedHost].blockedByServer).to.be.true+ expect(body.hosts[mutedHost].blockedByUser).to.be.false+ expect(body.hosts[mutedHost].blockedByServerSubscription).to.equal('Test subscription')+ }++ mockServer.setActions([+ { type: 'block', target: mutedHandle1, createdAt: new Date(now - 1000).toISOString() },+ { type: 'unblock', target: mutedHandle1, createdAt: new Date(now + 2000).toISOString() }+ ])++ await wait(8000)++ {+ const body = await server.blocklist.getStatus({+ accounts: [ mutedHandle1 ]+ })++ expect(body.accounts[mutedHandle1].blockedByServer).to.be.false+ expect(body.accounts[mutedHandle1].blockedByServerSubscription).to.be.null+ }+ })++ it('Should only check new block status on next run', async function () {+ mockServer.setActions([+ { type: 'block', target: mutedHandle1, createdAt: new Date(new Date().getTime() - 100_000).toISOString() }+ ])++ await wait(8000)++ {+ const body = await server.blocklist.getStatus({+ accounts: [ mutedHandle1 ]+ })++ expect(body.accounts[mutedHandle1].blockedByServer).to.be.false+ expect(body.accounts[mutedHandle1].blockedByServerSubscription).to.be.null+ }+ })++ it('Should not remove manual blocks', async function () {+ await server.blocklist.addToServerBlocklist({ account: mutedHandle1 })++ mockServer.setActions([+ { type: 'block', target: mutedHandle1, createdAt: new Date(new Date().getTime() - 100_000).toISOString() },+ { type: 'unblock', target: mutedHandle1, createdAt: new Date(new Date().getTime() - 50_000).toISOString() }+ ])++ await wait(8000)++ {+ const body = await server.blocklist.getStatus({+ accounts: [ mutedHandle1, mutedHandle2 ]+ })++ expect(body.accounts[mutedHandle1].blockedByServer).to.be.true+ expect(body.accounts[mutedHandle1].blockedByServerSubscription).to.be.null+ expect(body.accounts[mutedHandle2].blockedByServer).to.be.true+ expect(body.accounts[mutedHandle2].blockedByServerSubscription).to.equal('Test subscription')+ }+ })++ it('Should list blocked accounts/servers', async function () {+ {+ const { total, data } = await server.blocklist.listServerServerBlocklist({ start: 0, count: 5 })++ expect(total).to.equal(1)+ expect(data[0].blockedServer.host).to.equal(mutedHost)+ expect(data[0].blocklistSubscription.name).to.equal('Test subscription')+ expect(data[0].blocklistSubscription.url).to.exist+ }++ {+ const { total, data } = await server.blocklist.listServerAccountBlocklist({ start: 0, count: 5, sort: 'createdAt' })++ expect(total).to.equal(2)+ expect(data[0].blockedAccount.name + '@' + data[0].blockedAccount.host).to.equal(mutedHandle2)+ expect(data[0].blocklistSubscription.name).to.equal('Test subscription')+ expect(data[0].blocklistSubscription.url).to.exist++ expect(data[1].blockedAccount.name + '@' + data[1].blockedAccount.host).to.equal(mutedHandle1)+ expect(data[1].blocklistSubscription).to.not.exist+ }++ {+ const { total, data } = await server.blocklist.listServerAccountBlocklist({+ start: 0,+ count: 5,+ subscriptionName: 'Test subscription'+ })++ expect(total).to.equal(1)+ expect(data).to.have.lengthOf(1)+ expect(data[0].blockedAccount.name + '@' + data[0].blockedAccount.host).to.equal(mutedHandle2)+ }++ {+ const { total, data } = await server.blocklist.listServerServerBlocklist({+ start: 0,+ count: 5,+ subscriptionName: 'Test subscription'+ })++ expect(total).to.equal(1)+ expect(data).to.have.lengthOf(1)+ expect(data[0].blockedServer.host).to.equal(mutedHost)+ }++ {+ const { total, data } = await server.blocklist.listServerAccountBlocklist({+ start: 0,+ count: 5,+ subscriptionName: 'unknown subscription name'+ })++ expect(total).to.equal(0)+ expect(data).to.have.lengthOf(0)+ }++ {+ const body = await server.blocklist.listServerBlocklistSubscriptions({ sort: 'name' })++ expect(body.total).to.equal(2)++ const testSubscription = body.data.find(s => s.name === 'Test subscription')+ expect(testSubscription).to.exist+ expect(testSubscription.mutedAccountsCount).to.equal(1)+ expect(testSubscription.mutedServersCount).to.equal(1)++ const anotherSubscription = body.data.find(s => s.name === 'another subscription list')+ expect(anotherSubscription).to.exist+ expect(anotherSubscription.mutedAccountsCount).to.equal(0)+ expect(anotherSubscription.mutedServersCount).to.equal(0)+ }+ })++ it('Should subscribe to another instance blocklist and synchronize', async function () {+ await server.config.updateExistingConfig({+ newConfig: {+ blocklist: {+ publicLog: {+ enabled: true+ }+ }+ }+ })++ await server2.blocklist.addServerBlocklistSubscription({ subscriptionUrl: `${server.url}/api/v1/server/blocklist/public-log` })+ await wait(8000)++ {+ const { data } = await server2.blocklist.listServerBlocklistSubscriptions({ search: 'public-log' })++ expect(data).to.have.lengthOf(1)+ expect(data[0].name).to.equal('PeerTube')+ expect(data[0].url).to.equal(`${server.url}/api/v1/server/blocklist/public-log`)+ expect(data[0].state.label).to.be.oneOf([ 'Synchronized', 'Processing' ])+ }++ {+ const body = await server2.blocklist.getStatus({+ accounts: [ mutedHandle1, mutedHandle2 ],+ hosts: [ mutedHost ]+ })++ expect(body.accounts[mutedHandle1].blockedByServer).to.be.true+ expect(body.accounts[mutedHandle1].blockedByServerSubscription).to.equal('PeerTube')++ expect(body.accounts[mutedHandle2].blockedByServer).to.be.false+ expect(body.accounts[mutedHandle2].blockedByServerSubscription).to.be.null++ expect(body.hosts[mutedHost].blockedByServer).to.be.false+ expect(body.hosts[mutedHost].blockedByServerSubscription).to.be.null+ }+ })++ it('Should delete a subscription', async function () {+ await server.blocklist.removeServerBlocklistSubscription({ id: subscriptionId })++ const body = await server.blocklist.getStatus({+ accounts: [ mutedHandle1, mutedHandle2 ]+ })++ expect(body.accounts[mutedHandle1].blockedByServer).to.be.true+ expect(body.accounts[mutedHandle1].blockedByServerSubscription).to.be.null+ expect(body.accounts[mutedHandle2].blockedByServer).to.be.false+ expect(body.accounts[mutedHandle2].blockedByServerSubscription).to.be.null+ })++ after(async function () {+ await cleanupTests([ server2 ])+ })+ })++ after(async function () {+ await cleanupTests([ server ])+ await mockServer.terminate()+ })+})diff --git a/packages/tests/src/api/notifications/moderation-notifications.ts b/packages/tests/src/api/notifications/moderation-notifications.tsindex f1873e25fd..a449dc035a 100644--- a/packages/tests/src/api/notifications/moderation-notifications.ts+++ b/packages/tests/src/api/notifications/moderation-notifications.ts@@ -1,14 +1,16 @@/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */import { wait } from '@peertube/peertube-core-utils'-import { AbuseState, UserNotification, UserRole, VideoPrivacy } from '@peertube/peertube-models'+import { AbuseState, UserNotification, UserNotificationType, UserRole, VideoPrivacy } from '@peertube/peertube-models'import { buildUUID } from '@peertube/peertube-node-utils'import { cleanupTests, PeerTubeServer, waitJobs } from '@peertube/peertube-server-commands'+import { MockCoreBlocklist } from '@tests/shared/mock-servers/mock-core-blocklist.js'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 {checkAbuseStateChange,+ checkAutomaticBlocklistForModerators,checkNewAbuseMessage,checkNewAccountAbuseForModerators,checkNewBlacklistOnMyVideo,@@ -17,7 +19,7 @@ import {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 { prepareNotificationsTest, waitUntilNotification } from '@tests/shared/notifications/notifications-common.js'import { CheckerBaseParams } from '@tests/shared/notifications/shared/notification-checker.js'describe('Test moderation notifications', function () {@@ -579,6 +581,86 @@ describe('Test moderation notifications', function () {})})+ describe('Subscription auto blocklist notifications', function () {+ let mockServer: MockCoreBlocklist+ let mockPort: number++ before(async function () {+ mockServer = new MockCoreBlocklist()+ mockPort = await mockServer.initialize()+ })++ it('Should notify moderators when subscriptions auto block/unblock targets', async function () {+ this.timeout(120000)++ const targetHandle = `user2@${servers[1].host}`+ const targetHost = servers[1].host+ const targetHost2 = 'example.com'++ await servers[0].accounts.get({ accountName: targetHandle })++ const { id: subscriptionId } = await servers[0].blocklist.addServerBlocklistSubscription({+ subscriptionUrl: `http://127.0.0.1:${mockPort}/list.json`+ })++ const baseParams: CheckerBaseParams = {+ server: servers[0],+ emails,+ socketNotifications: adminNotifications,+ token: servers[0].accessToken+ }++ const now = Date.now()++ mockServer.setActions([+ { type: 'block', target: targetHandle, createdAt: new Date(now - 1000).toISOString() },+ { type: 'block', target: targetHost2, createdAt: new Date(now - 1000).toISOString() }+ ])++ await waitUntilNotification({+ server: servers[0],+ token: servers[0].accessToken,+ notificationType: UserNotificationType.AUTOMATIC_BLOCKLIST_UPDATE,+ fromDate: new Date(now)+ })++ await checkAutomaticBlocklistForModerators({+ ...baseParams,++ expectedBlockedAccountsCount: 1,+ expectedBlockedHostsCount: 1,+ expectedUnblockedAccountsCount: 0,+ expectedUnblockedHostsCount: 0,+ checkType: 'presence'+ })++ mockServer.setActions([+ { type: 'block', target: targetHandle, createdAt: new Date(now - 1000).toISOString() },+ { type: 'block', target: targetHost, createdAt: new Date(now + 1000).toISOString() },+ { type: 'unblock', target: targetHost, createdAt: new Date(now + 2000).toISOString() },+ { type: 'unblock', target: targetHost2, createdAt: new Date(now + 2000).toISOString() }+ ])++ await wait(8000)++ await checkAutomaticBlocklistForModerators({+ ...baseParams,++ expectedBlockedAccountsCount: 0,+ expectedBlockedHostsCount: 0,+ expectedUnblockedAccountsCount: 0,+ expectedUnblockedHostsCount: 1,+ checkType: 'presence'+ })++ await servers[0].blocklist.removeServerBlocklistSubscription({ id: subscriptionId })+ })++ after(async function () {+ await mockServer.terminate()+ })+ })+after(async function () {await MockSmtpServer.Instance.kill()diff --git a/packages/tests/src/api/server/config.ts b/packages/tests/src/api/server/config.tsindex 700716456b..a73998d0a7 100644--- a/packages/tests/src/api/server/config.ts+++ b/packages/tests/src/api/server/config.ts@@ -130,6 +130,7 @@ function checkInitialConfig (server: PeerTubeServer, data: CustomConfig) {expect(data.import.videoChannelSynchronization.enabled).to.be.falseexpect(data.import.users.enabled).to.be.trueexpect(data.autoBlacklist.videos.ofUsers.enabled).to.be.false+ expect(data.blocklist.publicLog.enabled).to.be.falseexpect(data.followers.instance.enabled).to.be.trueexpect(data.followers.instance.manualApproval).to.be.false@@ -416,6 +417,11 @@ function buildNewCustomConfig (server: PeerTubeServer): CustomConfig {}}},+ blocklist: {+ publicLog: {+ enabled: true+ }+ },broadcastMessage: {enabled: true,level: 'error',@@ -530,6 +536,7 @@ describe('Test config', function () {expect(data.views.videos.watchingInterval.users).to.equal(5000)expect(data.webrtc.stunServers).to.include('stun:stun.framasoft.org')+ expect(data.blocklist.publicLog.enabled).to.be.false})it('Should have a correct config on a server with registration enabled', async function () {diff --git a/packages/tests/src/api/videos/video-channel-syncs.ts b/packages/tests/src/api/videos/video-channel-syncs.tsindex 2ccfcc0bee..bd811a7620 100644--- a/packages/tests/src/api/videos/video-channel-syncs.ts+++ b/packages/tests/src/api/videos/video-channel-syncs.ts@@ -1,6 +1,6 @@/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */-import { VideoChannelSyncState, VideoImportState, VideoInclude, VideoPrivacy } from '@peertube/peertube-models'+import { StreamSyncState, VideoImportState, VideoInclude, VideoPrivacy } from '@peertube/peertube-models'import { areHttpImportTestsDisabled, areYoutubeImportTestsDisabled } from '@peertube/peertube-node-utils'import {cleanupTests,@@ -140,7 +140,7 @@ describe('Test channel synchronizations', function () {expect(videoChannelSync.externalChannelUrl).to.equal(externalChannelUrl)expect(videoChannelSync.channel.id).to.equal(servers[0].store.channel.id)expect(videoChannelSync.channel.name).to.equal('root_channel')- expect(videoChannelSync.state.id).to.equal(VideoChannelSyncState.WAITING_FIRST_RUN)+ expect(videoChannelSync.state.id).to.equal(StreamSyncState.WAITING_FIRST_RUN)expect(new Date(videoChannelSync.createdAt)).to.be.above(startTestDate).and.to.be.at.most(new Date())})@@ -161,7 +161,7 @@ describe('Test channel synchronizations', function () {const { data } = await servers[0].channelSyncs.listByAccount({ accountName: userInfo.username })expect(data[0].state).to.contain({- id: VideoChannelSyncState.WAITING_FIRST_RUN,+ id: StreamSyncState.WAITING_FIRST_RUN,label: 'Waiting first run'})})@@ -186,7 +186,7 @@ describe('Test channel synchronizations', function () {expect(data[0]).to.deep.contain({externalChannelUrl: FIXTURE_URLS.youtubeChannel,state: {- id: VideoChannelSyncState.SYNCED,+ id: StreamSyncState.SYNCED,label: 'Synchronized'}})@@ -204,7 +204,7 @@ describe('Test channel synchronizations', function () {expect(data[0]).to.deep.contain({externalChannelUrl: FIXTURE_URLS.youtubeChannel + '?baz=qux',state: {- id: VideoChannelSyncState.SYNCED,+ id: StreamSyncState.SYNCED,label: 'Synchronized'}})@@ -256,7 +256,7 @@ describe('Test channel synchronizations', function () {{const { data } = await servers[0].channelSyncs.listByAccount({ accountName: 'root' })const sync = data.find(s => s.id === rootChannelSyncId)- expect(sync.state.id).to.equal(VideoChannelSyncState.FAILED)+ expect(sync.state.id).to.equal(StreamSyncState.FAILED)}}@@ -272,7 +272,7 @@ describe('Test channel synchronizations', function () {{const { data } = await servers[0].channelSyncs.listByAccount({ accountName: 'root' })const sync = data.find(s => s.id === rootChannelSyncId)- expect(sync.state.id).to.equal(VideoChannelSyncState.SYNCED)+ expect(sync.state.id).to.equal(StreamSyncState.SYNCED)}})diff --git a/packages/tests/src/external-plugins/auto-block-videos.ts b/packages/tests/src/external-plugins/auto-block-videos.tsindex 9bd56ea99f..2ca3002927 100644--- a/packages/tests/src/external-plugins/auto-block-videos.ts+++ b/packages/tests/src/external-plugins/auto-block-videos.ts@@ -11,7 +11,7 @@ import {PeerTubeServer,setAccessTokensToServers} from '@peertube/peertube-server-commands'-import { MockBlocklist } from '../shared/mock-servers/mock-plugin-blocklist.js'+import { MockPluginBlocklist } from '../shared/mock-servers/mock-plugin-blocklist.js'async function check (server: PeerTubeServer, videoUUID: string, exists = true) {const { data } = await server.videos.list()@@ -24,7 +24,7 @@ async function check (server: PeerTubeServer, videoUUID: string, exists = true)describe('Official plugin auto-block videos', function () {let servers: PeerTubeServer[]- let blocklistServer: MockBlocklist+ let blocklistServer: MockPluginBlocklistlet server1Videos: Video[] = []let server2Videos: Video[] = []let port: number@@ -39,7 +39,7 @@ describe('Official plugin auto-block videos', function () {await server.plugins.install({ npmName: 'peertube-plugin-auto-block-videos' })}- blocklistServer = new MockBlocklist()+ blocklistServer = new MockPluginBlocklist()port = await blocklistServer.initialize()await servers[0].videos.quickUpload({ name: 'video server 1' })diff --git a/packages/tests/src/external-plugins/auto-mute.ts b/packages/tests/src/external-plugins/auto-mute.tsindex 158ccb1535..1be9bf68ec 100644--- a/packages/tests/src/external-plugins/auto-mute.ts+++ b/packages/tests/src/external-plugins/auto-mute.ts@@ -12,12 +12,12 @@ import {PeerTubeServer,setAccessTokensToServers} from '@peertube/peertube-server-commands'-import { MockBlocklist } from '../shared/mock-servers/mock-plugin-blocklist.js'+import { MockPluginBlocklist } from '../shared/mock-servers/mock-plugin-blocklist.js'describe('Official plugin auto-mute', function () {const autoMuteListPath = '/plugins/auto-mute/router/api/v1/mute-list'let servers: PeerTubeServer[]- let blocklistServer: MockBlocklist+ let blocklistServer: MockPluginBlocklistlet port: numberbefore(async function () {@@ -30,7 +30,7 @@ describe('Official plugin auto-mute', function () {await server.plugins.install({ npmName: 'peertube-plugin-auto-mute' })}- blocklistServer = new MockBlocklist()+ blocklistServer = new MockPluginBlocklist()port = await blocklistServer.initialize()await servers[0].videos.quickUpload({ name: 'video server 1' })diff --git a/packages/tests/src/shared/mock-servers/mock-core-blocklist.ts b/packages/tests/src/shared/mock-servers/mock-core-blocklist.tsnew file mode 100644index 0000000000..bf907581b9--- /dev/null+++ b/packages/tests/src/shared/mock-servers/mock-core-blocklist.ts@@ -0,0 +1,47 @@+import express from 'express'+import { Server } from 'http'+import { getPort, randomListen, terminateServer } from './shared.js'++export class MockCoreBlocklist {+ private server: Server++ private actions: { type: 'block' | 'unblock', target: string, createdAt: string }[] = []++ async initialize () {+ const app = express()++ app.get('/list.json', (req: express.Request, res: express.Response) => {+ return res.json({+ name: 'Test subscription',+ actions: this.actions+ })+ })++ app.get('/list-2', (req: express.Request, res: express.Response) => {+ return res.json({+ name: 'another subscription list',+ actions: []+ })+ })++ app.get('/invalid-blocklist-1', (req: express.Request, res: express.Response) => {+ return res.json({ actions: [], name: '' })+ })++ app.get('/invalid-blocklist-2', (req: express.Request, res: express.Response) => {+ return res.send('')+ })++ this.server = await randomListen(app)++ return getPort(this.server)+ }++ setActions (actions: { type: 'block' | 'unblock', target: string, createdAt: string }[]) {+ this.actions = actions+ }++ terminate () {+ return terminateServer(this.server)+ }+}diff --git a/packages/tests/src/shared/mock-servers/mock-plugin-blocklist.ts b/packages/tests/src/shared/mock-servers/mock-plugin-blocklist.tsindex c0b6518ba3..0df1e7451c 100644--- a/packages/tests/src/shared/mock-servers/mock-plugin-blocklist.ts+++ b/packages/tests/src/shared/mock-servers/mock-plugin-blocklist.ts@@ -10,7 +10,7 @@ type BlocklistResponse = {}[]}-export class MockBlocklist {+export class MockPluginBlocklist {private body: BlocklistResponseprivate server: Serverdiff --git a/packages/tests/src/shared/notifications/check-moderation-notifications.ts b/packages/tests/src/shared/notifications/check-moderation-notifications.tsindex 8352d8f42a..c7fc782635 100644--- a/packages/tests/src/shared/notifications/check-moderation-notifications.ts+++ b/packages/tests/src/shared/notifications/check-moderation-notifications.ts@@ -202,6 +202,58 @@ export async function checkVideoAutoBlacklistForModerators (await checkNotification({ ...options, notificationChecker, emailNotificationFinder })}+export async function checkAutomaticBlocklistForModerators (+ options: CheckerBaseParams & {+ expectedBlockedAccountsCount: number+ expectedBlockedHostsCount: number+ expectedUnblockedAccountsCount: number+ expectedUnblockedHostsCount: number+ checkType: CheckerType+ }+) {+ const {+ expectedBlockedAccountsCount,+ expectedBlockedHostsCount,+ expectedUnblockedAccountsCount,+ expectedUnblockedHostsCount+ } = options++ const notificationType = UserNotificationType.AUTOMATIC_BLOCKLIST_UPDATE++ function notificationChecker (notification: UserNotification, checkType: CheckerType) {+ if (checkType === 'presence') {+ expect(notification).to.not.be.undefined+ expect(notification.type).to.equal(notificationType)++ expect(notification.data.blockedAccountsCount).to.equal(expectedBlockedAccountsCount)+ expect(notification.data.blockedHostsCount).to.equal(expectedBlockedHostsCount)+ expect(notification.data.unblockedAccountsCount).to.equal(expectedUnblockedAccountsCount)+ expect(notification.data.unblockedHostsCount).to.equal(expectedUnblockedHostsCount)+ } else {+ expect(notification).to.satisfy((n: UserNotification) => {+ if (n?.type !== notificationType) return true+ if (!n?.data) return true++ const data = n.data++ return data.blockedAccountsCount !== expectedBlockedAccountsCount ||+ data.blockedHostsCount !== expectedBlockedHostsCount ||+ data.unblockedAccountsCount !== expectedUnblockedAccountsCount ||+ data.unblockedHostsCount !== expectedUnblockedHostsCount+ })+ }+ }++ function emailNotificationFinder (email: object) {+ const text: string = email['text']++ return text.includes(`${expectedBlockedAccountsCount} account(s) and ${expectedBlockedHostsCount} server(s) were blocked`) &&+ text.includes(`${expectedUnblockedAccountsCount} account(s) and ${expectedUnblockedHostsCount} server(s) were unblocked`)+ }++ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })+}+export async function checkNewBlacklistOnMyVideo (options: CheckerBaseParams & {shortUUID: stringdiff --git a/packages/tests/src/shared/notifications/notifications-common.ts b/packages/tests/src/shared/notifications/notifications-common.tsindex a8bfa408b6..fc04e52eb5 100644--- a/packages/tests/src/shared/notifications/notifications-common.ts+++ b/packages/tests/src/shared/notifications/notifications-common.ts@@ -39,7 +39,8 @@ export function getAllNotificationsSettings (): UserNotificationSetting {newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,myVideoStudioEditionFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,- newPluginVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL+ newPluginVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,+ automaticBlocklist: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL}}diff --git a/server/core/controllers/api/blocklist.ts b/server/core/controllers/api/blocklist.tsindex f045935b09..3b34d96df6 100644--- a/server/core/controllers/api/blocklist.ts+++ b/server/core/controllers/api/blocklist.ts@@ -1,9 +1,9 @@import express from 'express'import { handleToNameAndHost } from '@server/helpers/actors.js'import { logger } from '@server/helpers/logger.js'-import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'import { getServerActor } from '@server/models/application/application.js'-import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'import { MActorAccountId, MUserAccountId } from '@server/types/models/index.js'import { BlockStatus } from '@peertube/peertube-models'import { apiRateLimiter, asyncMiddleware, blocklistStatusValidator, optionalAuthenticate } from '../../middlewares/index.js'@@ -98,9 +98,16 @@ async function populateAccountBlocklistStatus (options: {}}-function getStatus (blocks: { accountId: number }[], serverActor: MActorAccountId, user?: MUserAccountId) {+function getStatus (+ blocks: { accountId: number, blocklistSubscriptionName: string }[],+ serverActor: MActorAccountId,+ user?: MUserAccountId+) {+ const serverBlock = blocks.find(block => block.accountId === serverActor.Account.id)+return {- blockedByServer: blocks.some(block => block.accountId === serverActor.Account.id),+ blockedByServer: !!serverBlock,+ blockedByServerSubscription: serverBlock?.blocklistSubscriptionName ?? null,blockedByUser: blocks.some(block => block.accountId === user?.Account.id)}}diff --git a/server/core/controllers/api/config.ts b/server/core/controllers/api/config.tsindex fdc1c8a4a3..69b2b04b4d 100644--- a/server/core/controllers/api/config.ts+++ b/server/core/controllers/api/config.ts@@ -534,6 +534,11 @@ function customConfig (): CustomConfig {}}},+ blocklist: {+ publicLog: {+ enabled: CONFIG.BLOCKLIST.PUBLIC_LOG.ENABLED+ }+ },followers: {instance: {enabled: CONFIG.FOLLOWERS.INSTANCE.ENABLED,diff --git a/server/core/controllers/api/server/server-blocklist.ts b/server/core/controllers/api/server/server-blocklist.tsindex e17761959f..c4b467824b 100644--- a/server/core/controllers/api/server/server-blocklist.ts+++ b/server/core/controllers/api/server/server-blocklist.ts@@ -1,7 +1,10 @@-import 'multer'-import express from 'express'-import { HttpStatusCode, UserRight } from '@peertube/peertube-models'+import { AutoMuteList, BlocklistLogAction, HttpStatusCode, UserRight } from '@peertube/peertube-models'+import { logger } from '@server/helpers/logger.js'+import { CONFIG } from '@server/initializers/config.js'+import { fetchAndValidateAutoMuteList } from '@server/lib/blocklist-subscriptions.js'import { getServerActor } from '@server/models/application/application.js'+import express from 'express'+import 'multer'import { getFormattedObjects } from '../../../helpers/utils.js'import {addAccountInBlocklist,@@ -20,14 +23,20 @@ import {} from '../../../middlewares/index.js'import {accountsBlocklistSortValidator,+ addBlocklistSubscriptionValidator,blockAccountValidator,+ blocklistSubscriptionsSortValidator,blockServerValidator,+ deleteBlocklistSubscriptionValidator,+ publicBlocklistLogValidator,serversBlocklistSortValidator,unblockAccountByServerValidator,unblockServerByServerValidator} from '../../../middlewares/validators/index.js'-import { AccountBlocklistModel } from '../../../models/account/account-blocklist.js'-import { ServerBlocklistModel } from '../../../models/server/server-blocklist.js'+import { AccountBlocklistModel } from '../../../models/blocklist/account-blocklist.js'+import { BlocklistLogModel } from '../../../models/blocklist/blocklist-log.js'+import { BlocklistSubscriptionModel } from '../../../models/blocklist/blocklist-subscription.js'+import { ServerBlocklistModel } from '../../../models/blocklist/server-blocklist.js'const serverBlocklistRouter = express.Router()@@ -85,6 +94,47 @@ serverBlocklistRouter.delete(asyncRetryTransactionMiddleware(unblockServer))+// ---------------------------------------------------------------------------+// Blocklist subscriptions+// ---------------------------------------------------------------------------++serverBlocklistRouter.get(+ '/blocklist/subscriptions',+ authenticate,+ ensureUserHasRight(UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS),+ paginationValidator,+ blocklistSubscriptionsSortValidator,+ setDefaultSort,+ setDefaultPagination,+ asyncMiddleware(listBlocklistSubscriptions)+)++serverBlocklistRouter.post(+ '/blocklist/subscriptions',+ authenticate,+ ensureUserHasRight(UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS),+ asyncMiddleware(addBlocklistSubscriptionValidator),+ asyncRetryTransactionMiddleware(addBlocklistSubscription)+)++serverBlocklistRouter.delete(+ '/blocklist/subscriptions/:id',+ authenticate,+ ensureUserHasRight(UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS),+ asyncMiddleware(deleteBlocklistSubscriptionValidator),+ asyncRetryTransactionMiddleware(deleteBlocklistSubscription)+)++// ---------------------------------------------------------------------------+// Public blocklist log+// ---------------------------------------------------------------------------++serverBlocklistRouter.get(+ '/blocklist/public-log',+ publicBlocklistLogValidator,+ asyncMiddleware(listPublicBlocklistLog)+)+export {serverBlocklistRouter}@@ -99,6 +149,7 @@ async function listBlockedAccounts (req: express.Request, res: express.Response)count: req.query.count,sort: req.query.sort,search: req.query.search,+ subscriptionName: req.query.subscriptionName,accountId: serverActor.Account.id})@@ -109,7 +160,11 @@ async function blockAccount (req: express.Request, res: express.Response) {const serverActor = await getServerActor()const accountToBlock = res.locals.account- await addAccountInBlocklist({ byAccountId: serverActor.Account.id, targetAccountId: accountToBlock.id, removeNotificationOfUserId: null })+ await addAccountInBlocklist({+ byAccountId: serverActor.Account.id,+ targetAccount: accountToBlock,+ removeNotificationOfUserId: null+ })return res.sendStatus(HttpStatusCode.NO_CONTENT_204)}@@ -130,6 +185,7 @@ async function listBlockedServers (req: express.Request, res: express.Response)count: req.query.count,sort: req.query.sort,search: req.query.search,+ subscriptionName: req.query.subscriptionName,accountId: serverActor.Account.id})@@ -142,7 +198,7 @@ async function blockServer (req: express.Request, res: express.Response) {await addServerInBlocklist({byAccountId: serverActor.Account.id,- targetServerId: serverToBlock.id,+ targetServer: serverToBlock,removeNotificationOfUserId: null})@@ -156,3 +212,80 @@ async function unblockServer (req: express.Request, res: express.Response) {return res.sendStatus(HttpStatusCode.NO_CONTENT_204)}++async function listBlocklistSubscriptions (req: express.Request, res: express.Response) {+ const serverActor = await getServerActor()++ const resultList = await BlocklistSubscriptionModel.listForApi({+ accountId: serverActor.Account.id,+ start: req.query.start,+ count: req.query.count,+ sort: req.query.sort,+ search: req.query.search+ })++ return res.json(getFormattedObjects(resultList.data, resultList.total))+}++async function addBlocklistSubscription (req: express.Request, res: express.Response) {+ const serverActor = await getServerActor()++ try {+ const { name: listName } = await fetchAndValidateAutoMuteList(req.body.url)++ const subscription = await BlocklistSubscriptionModel.create({+ accountId: serverActor.Account.id,+ name: listName,+ url: req.body.url,+ lastSyncAt: null+ })++ return res.json(subscription.toFormattedJSON())+ } catch (err) {+ logger.warn('Failed to fetch or parse auto mute list URL when adding blocklist subscription.', { url: req.body.url, err })++ res.fail({+ status: HttpStatusCode.BAD_REQUEST_400,+ message: req.t('Cannot fetch or parse auto mute list URL')+ })+ }+}++async function deleteBlocklistSubscription (req: express.Request, res: express.Response) {+ const subscription = res.locals.blocklistSubscription++ await subscription.destroy()++ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)+}++async function listPublicBlocklistLog (req: express.Request, res: express.Response) {+ const serverActor = await getServerActor()++ const resultList = await BlocklistLogModel.listPublicForApi({+ accountId: serverActor.Account.id,+ startDate: req.query.startDate,+ start: 0,+ count: 500,+ sort: 'createdAt'+ })++ const payload: AutoMuteList = {+ name: CONFIG.INSTANCE.NAME,+ actions: resultList.data.map(log => {+ return {+ type: mapBlocklistLogAction(log.action),+ target: log.target,+ createdAt: new Date(log.createdAt).toISOString()+ }+ })+ }++ return res.json(payload)+}++function mapBlocklistLogAction (action: BlocklistLogAction): 'block' | 'unblock' {+ if (action === 'add') return 'block'++ return 'unblock'+}diff --git a/server/core/controllers/api/users/my-blocklist.ts b/server/core/controllers/api/users/my-blocklist.tsindex ba10fb29d8..528aaac243 100644--- a/server/core/controllers/api/users/my-blocklist.ts+++ b/server/core/controllers/api/users/my-blocklist.ts@@ -1,6 +1,6 @@-import 'multer'-import express from 'express'import { HttpStatusCode } from '@peertube/peertube-models'+import express from 'express'+import 'multer'import { getFormattedObjects } from '../../../helpers/utils.js'import {addAccountInBlocklist,@@ -24,12 +24,13 @@ import {serversBlocklistSortValidator,unblockServerByAccountValidator} from '../../../middlewares/validators/index.js'-import { AccountBlocklistModel } from '../../../models/account/account-blocklist.js'-import { ServerBlocklistModel } from '../../../models/server/server-blocklist.js'+import { AccountBlocklistModel } from '../../../models/blocklist/account-blocklist.js'+import { ServerBlocklistModel } from '../../../models/blocklist/server-blocklist.js'const myBlocklistRouter = express.Router()-myBlocklistRouter.get('/me/blocklist/accounts',+myBlocklistRouter.get(+ '/me/blocklist/accounts',authenticate,paginationValidator,accountsBlocklistSortValidator,@@ -38,19 +39,22 @@ myBlocklistRouter.get('/me/blocklist/accounts',asyncMiddleware(listBlockedAccounts))-myBlocklistRouter.post('/me/blocklist/accounts',+myBlocklistRouter.post(+ '/me/blocklist/accounts',authenticate,asyncMiddleware(blockAccountValidator),asyncRetryTransactionMiddleware(blockAccount))-myBlocklistRouter.delete('/me/blocklist/accounts/:accountName',+myBlocklistRouter.delete(+ '/me/blocklist/accounts/:accountName',authenticate,asyncMiddleware(unblockAccountByAccountValidator),asyncRetryTransactionMiddleware(unblockAccount))-myBlocklistRouter.get('/me/blocklist/servers',+myBlocklistRouter.get(+ '/me/blocklist/servers',authenticate,paginationValidator,serversBlocklistSortValidator,@@ -59,13 +63,15 @@ myBlocklistRouter.get('/me/blocklist/servers',asyncMiddleware(listBlockedServers))-myBlocklistRouter.post('/me/blocklist/servers',+myBlocklistRouter.post(+ '/me/blocklist/servers',authenticate,asyncMiddleware(blockServerValidator),asyncRetryTransactionMiddleware(blockServer))-myBlocklistRouter.delete('/me/blocklist/servers/:host',+myBlocklistRouter.delete(+ '/me/blocklist/servers/:host',authenticate,asyncMiddleware(unblockServerByAccountValidator),asyncRetryTransactionMiddleware(unblockServer)@@ -95,7 +101,11 @@ async function blockAccount (req: express.Request, res: express.Response) {const user = res.locals.oauth.token.Userconst accountToBlock = res.locals.account- await addAccountInBlocklist({ byAccountId: user.Account.id, targetAccountId: accountToBlock.id, removeNotificationOfUserId: user.id })+ await addAccountInBlocklist({+ byAccountId: user.Account.id,+ targetAccount: accountToBlock,+ removeNotificationOfUserId: user.id+ })return res.sendStatus(HttpStatusCode.NO_CONTENT_204)}@@ -128,7 +138,7 @@ async function blockServer (req: express.Request, res: express.Response) {await addServerInBlocklist({byAccountId: user.Account.id,- targetServerId: serverToBlock.id,+ targetServer: serverToBlock,removeNotificationOfUserId: user.id})diff --git a/server/core/controllers/api/users/my-notifications.ts b/server/core/controllers/api/users/my-notifications.tsindex 63049d3efd..0d3622f3d2 100644--- a/server/core/controllers/api/users/my-notifications.ts+++ b/server/core/controllers/api/users/my-notifications.ts@@ -77,7 +77,8 @@ async function updateNotificationSettings (req: express.Request, res: express.RenewPeerTubeVersion: body.newPeerTubeVersion,newPluginVersion: body.newPluginVersion,myVideoTranscriptionGenerated: body.myVideoTranscriptionGenerated,- myVideoStudioEditionFinished: body.myVideoStudioEditionFinished+ myVideoStudioEditionFinished: body.myVideoStudioEditionFinished,+ automaticBlocklist: body.automaticBlocklist}await UserNotificationSettingModel.updateUserSettings(values, user.id)diff --git a/server/core/controllers/api/video-channel-sync.ts b/server/core/controllers/api/video-channel-sync.tsindex 0b4aad98d3..8db887d212 100644--- a/server/core/controllers/api/video-channel-sync.ts+++ b/server/core/controllers/api/video-channel-sync.ts@@ -1,4 +1,4 @@-import { HttpStatusCode, VideoChannelActivityAction, VideoChannelSyncState } from '@peertube/peertube-models'+import { HttpStatusCode, VideoChannelActivityAction, StreamSyncState } from '@peertube/peertube-models'import { auditLoggerFactory, getAuditIdFromRes, VideoChannelSyncAuditView } from '@server/helpers/audit-logger.js'import { logger } from '@server/helpers/logger.js'import { sequelizeTypescript } from '@server/initializers/database.js'@@ -44,7 +44,7 @@ async function createVideoChannelSync (req: express.Request, res: express.Responconst syncCreated: MChannelSyncFormattable = new VideoChannelSyncModel({externalChannelUrl: req.body.externalChannelUrl,videoChannelId: req.body.videoChannelId,- state: VideoChannelSyncState.WAITING_FIRST_RUN+ state: StreamSyncState.WAITING_FIRST_RUN})await sequelizeTypescript.transaction(async transaction => {diff --git a/server/core/helpers/custom-validators/video-channel-syncs.ts b/server/core/helpers/custom-validators/video-channel-syncs.tsindex a07d8ed529..5e51408645 100644--- a/server/core/helpers/custom-validators/video-channel-syncs.ts+++ b/server/core/helpers/custom-validators/video-channel-syncs.ts@@ -1,6 +1,6 @@-import { VIDEO_CHANNEL_SYNC_STATE } from '@server/initializers/constants.js'+import { STREAM_SYNC_STATE } from '@server/initializers/constants.js'import { exists } from './misc.js'export function isVideoChannelSyncStateValid (value: any) {- return exists(value) && VIDEO_CHANNEL_SYNC_STATE[value] !== undefined+ return exists(value) && STREAM_SYNC_STATE[value] !== undefined}diff --git a/server/core/initializers/config.ts b/server/core/initializers/config.tsindex ad23b0daff..9780467d25 100644--- a/server/core/initializers/config.ts+++ b/server/core/initializers/config.ts@@ -124,6 +124,14 @@ const CONFIG = {ENABLED: config.get<boolean>('nsfw_flags_settings.enabled')},+ BLOCKLIST: {+ PUBLIC_LOG: {+ get ENABLED () {+ return config.get<boolean>('blocklist.public_log.enabled')+ }+ }+ },+DOWNLOAD: {MAX_TOTAL_BYTES_PER_SECOND: config.get<string | number | null>('download.max_total_bytes_per_second') === null? nulldiff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.tsindex 22a8396913..02403107bf 100644--- a/server/core/initializers/constants.ts+++ b/server/core/initializers/constants.ts@@ -28,8 +28,8 @@ import {VideoChannelActivityTargetType,VideoChannelCollaboratorState,VideoChannelCollaboratorStateType,- VideoChannelSyncState,- VideoChannelSyncStateType,+ StreamSyncState,+ StreamSyncStateType,VideoCommentPolicy,VideoCommentPolicyType,VideoEmbedPrivacyPolicy,@@ -155,6 +155,7 @@ export const SORTABLE_COLUMNS = {ACCOUNTS_BLOCKLIST: [ 'createdAt' ],SERVERS_BLOCKLIST: [ 'createdAt' ],+ BLOCKLIST_SUBSCRIPTIONS: [ 'name', 'createdAt', 'lastSyncAt' ],WATCHED_WORDS_LISTS: [ 'createdAt', 'updatedAt', 'listName' ],@@ -374,7 +375,8 @@ export const SCHEDULER_INTERVALS_MS = {REMOVE_EXPIRED_USER_EXPORTS: 1000 * 3600, // 1 hourUPDATE_INBOX_STATS: 1000 * 60, // 1 minuteREMOVE_DANGLING_RESUMABLE_UPLOADS: 60000 * 60, // 1 hour- CHANNEL_SYNC_CHECK_INTERVAL: CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.CHECK_INTERVAL+ CHANNEL_SYNC_CHECK_INTERVAL: CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.CHECK_INTERVAL,+ BLOCKLIST_SUBSCRIPTIONS_SYNC: 60000 * 60 // 1 hour}// ---------------------------------------------------------------------------@@ -662,11 +664,11 @@ export const VIDEO_IMPORT_STATES: { [id in VideoImportStateType]: string } = {[VideoImportState.PROCESSING]: 'Processing'}-export const VIDEO_CHANNEL_SYNC_STATE: { [id in VideoChannelSyncStateType]: string } = {- [VideoChannelSyncState.FAILED]: 'Failed',- [VideoChannelSyncState.SYNCED]: 'Synchronized',- [VideoChannelSyncState.PROCESSING]: 'Processing',- [VideoChannelSyncState.WAITING_FIRST_RUN]: 'Waiting first run'+export const STREAM_SYNC_STATE: { [id in StreamSyncStateType]: string } = {+ [StreamSyncState.FAILED]: 'Failed',+ [StreamSyncState.SYNCED]: 'Synchronized',+ [StreamSyncState.PROCESSING]: 'Processing',+ [StreamSyncState.WAITING_FIRST_RUN]: 'Waiting first run'}export const ABUSE_STATES: { [id in AbuseStateType]: string } = {@@ -1290,6 +1292,7 @@ if (process.env.PRODUCTION_CONSTANTS !== 'true') {SCHEDULER_INTERVALS_MS.REMOVE_OLD_HISTORY = 5000SCHEDULER_INTERVALS_MS.UPDATE_VIDEOS = 5000SCHEDULER_INTERVALS_MS.AUTO_FOLLOW_INDEX_INSTANCES = 5000+ SCHEDULER_INTERVALS_MS.BLOCKLIST_SUBSCRIPTIONS_SYNC = 5000SCHEDULER_INTERVALS_MS.UPDATE_INBOX_STATS = 5000SCHEDULER_INTERVALS_MS.CHECK_PEERTUBE_VERSION = 2000SCHEDULER_INTERVALS_MS.UPDATE_TOKEN_SESSION = 2000diff --git a/server/core/initializers/database.ts b/server/core/initializers/database.tsindex 7ee27a41d1..09a320ee92 100644--- a/server/core/initializers/database.ts+++ b/server/core/initializers/database.ts@@ -42,7 +42,7 @@ import { AbuseMessageModel } from '../models/abuse/abuse-message.js'import { AbuseModel } from '../models/abuse/abuse.js'import { VideoAbuseModel } from '../models/abuse/video-abuse.js'import { VideoCommentAbuseModel } from '../models/abuse/video-comment-abuse.js'-import { AccountBlocklistModel } from '../models/account/account-blocklist.js'+import { AccountBlocklistModel } from '../models/blocklist/account-blocklist.js'import { AccountVideoRateModel } from '../models/account/account-video-rate.js'import { AccountModel } from '../models/account/account.js'import { ActorFollowModel } from '../models/actor/actor-follow.js'@@ -53,7 +53,9 @@ import { OAuthClientModel } from '../models/oauth/oauth-client.js'import { OAuthTokenModel } from '../models/oauth/oauth-token.js'import { VideoRedundancyModel } from '../models/redundancy/video-redundancy.js'import { PluginModel } from '../models/server/plugin.js'-import { ServerBlocklistModel } from '../models/server/server-blocklist.js'+import { BlocklistLogModel } from '../models/blocklist/blocklist-log.js'+import { BlocklistSubscriptionModel } from '../models/blocklist/blocklist-subscription.js'+import { ServerBlocklistModel } from '../models/blocklist/server-blocklist.js'import { ServerModel } from '../models/server/server.js'import { VideoStatModel } from '../models/stat/video-stat.js'import { UserNotificationSettingModel } from '../models/user/user-notification-setting.js'@@ -181,6 +183,8 @@ export async function initDatabaseModels (silent: boolean) {VideoLiveReplaySettingModel,AccountBlocklistModel,ServerBlocklistModel,+ BlocklistSubscriptionModel,+ BlocklistLogModel,UserNotificationModel,UserNotificationSettingModel,VideoStreamingPlaylistModel,diff --git a/server/core/initializers/migrations/1035-blocklist-subscriptions.ts b/server/core/initializers/migrations/1035-blocklist-subscriptions.tsnew file mode 100644index 0000000000..6233b81fd1--- /dev/null+++ b/server/core/initializers/migrations/1035-blocklist-subscriptions.ts@@ -0,0 +1,71 @@+import * as Sequelize from 'sequelize'++async function up (utils: {+ transaction: Sequelize.Transaction+ queryInterface: Sequelize.QueryInterface+ sequelize: Sequelize.Sequelize+}): Promise<void> {+ const { transaction } = utils++ {+ const query = `+CREATE TABLE IF NOT EXISTS "blocklistSubscription" (+ "id" SERIAL,+ "name" VARCHAR(255) NOT NULL,+ "url" VARCHAR(255) NOT NULL,+ "lastSyncAt" TIMESTAMP WITH TIME ZONE,+ "lastActionCreatedAt" TIMESTAMP WITH TIME ZONE,+ "state" INTEGER NOT NULL DEFAULT 1,+ "accountId" INTEGER NOT NULL REFERENCES "account" ("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 })+ }++ {+ await utils.sequelize.query(+ `ALTER TABLE "accountBlocklist" ` ++ `ADD COLUMN IF NOT EXISTS "blocklistSubscriptionId" INTEGER REFERENCES "blocklistSubscription" ("id") ON DELETE CASCADE ON UPDATE CASCADE`,+ { transaction }+ )+ }++ {+ await utils.sequelize.query(+ `ALTER TABLE "serverBlocklist" ` ++ `ADD COLUMN IF NOT EXISTS "blocklistSubscriptionId" INTEGER REFERENCES "blocklistSubscription" ("id") ON DELETE CASCADE ON UPDATE CASCADE`,+ { transaction }+ )+ }++ {+ await utils.sequelize.query(`CREATE TYPE "enum_blocklistLog_action" AS ENUM ('add', 'delete');`, { transaction })++ const query = `+CREATE TABLE IF NOT EXISTS "blocklistLog" (+ "id" SERIAL,+ "action" "public"."enum_blocklistLog_action",+ "automaticallyCreated" BOOLEAN,+ "accountId" INTEGER REFERENCES "account" ("id") ON DELETE SET NULL ON UPDATE CASCADE,+ "blocklistSubscriptionId" INTEGER REFERENCES "blocklistSubscription" ("id") ON DELETE SET NULL ON UPDATE CASCADE,+ "target" VARCHAR(255),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,+ PRIMARY KEY ("id")+);`++ await utils.sequelize.query(query, { transaction })+ }+}++function down () {+ throw new Error('Not implemented.')+}++export {+ up,+ down+}diff --git a/server/core/initializers/migrations/1040-automatic-blocklist-notification-setting.ts b/server/core/initializers/migrations/1040-automatic-blocklist-notification-setting.tsnew file mode 100644index 0000000000..22bfa81503--- /dev/null+++ b/server/core/initializers/migrations/1040-automatic-blocklist-notification-setting.ts@@ -0,0 +1,33 @@+import * as Sequelize from 'sequelize'++async function up (utils: {+ transaction: Sequelize.Transaction+ queryInterface: Sequelize.QueryInterface+ sequelize: Sequelize.Sequelize+}): Promise<void> {+ const { transaction } = utils++ await utils.sequelize.query(+ `ALTER TABLE "userNotificationSetting" ADD COLUMN IF NOT EXISTS "automaticBlocklist" INTEGER`,+ { transaction }+ )++ await utils.sequelize.query(+ `UPDATE "userNotificationSetting" SET "automaticBlocklist" = 1 WHERE "automaticBlocklist" IS NULL`,+ { transaction }+ )++ await utils.sequelize.query(+ `ALTER TABLE "userNotificationSetting" ALTER COLUMN "automaticBlocklist" SET NOT NULL`,+ { transaction }+ )+}++function down () {+ throw new Error('Not implemented.')+}++export {+ up,+ down+}diff --git a/server/core/lib/blocklist-subscriptions.ts b/server/core/lib/blocklist-subscriptions.tsnew file mode 100644index 0000000000..4309e8019f--- /dev/null+++ b/server/core/lib/blocklist-subscriptions.ts@@ -0,0 +1,64 @@+import { AutoMuteAction, AutoMuteList } from '@peertube/peertube-models'+import { doJSONRequest } from '@server/helpers/requests.js'++export async function fetchAndValidateAutoMuteList (url: string, startDate?: Date): Promise<AutoMuteList> {+ const searchParams = startDate+ ? { startDate: startDate.toISOString() }+ : undefined++ const { body } = await doJSONRequest<AutoMuteList>(url, { searchParams, preventSSRF: false })++ if (!body || typeof body !== 'object' || Array.isArray(body)) {+ throw new Error('Invalid auto mute list payload: expected an object')+ }++ const name = body.name+ const rawActions = body.actions++ if (typeof name !== 'string' || name.trim().length === 0) {+ throw new Error('Invalid auto mute list payload: name must be a non-empty string')+ }++ if (!Array.isArray(rawActions)) {+ throw new Error('Invalid auto mute list payload: actions must be an array')+ }++ const actions: AutoMuteAction[] = rawActions.map((action, index) => validateAutoMuteAction(action, index))++ return {+ name,+ actions+ }+}++// ---------------------------------------------------------------------------+// Private+// ---------------------------------------------------------------------------++function validateAutoMuteAction (action: AutoMuteList['actions'][number], index: number): AutoMuteAction {+ if (!action || typeof action !== 'object' || Array.isArray(action)) {+ throw new Error(`Invalid auto mute list action at index ${index}: expected object`)+ }++ const type = action.type+ const target = action.target+ const createdAt = action.createdAt++ if (type !== 'block' && type !== 'unblock') {+ throw new Error(`Invalid auto mute list action at index ${index}: type must be block/unblock`)+ }++ if (typeof target !== 'string' || target.trim().length === 0) {+ throw new Error(`Invalid auto mute list action at index ${index}: target must be a non-empty string`)+ }++ if (typeof createdAt !== 'string' || Number.isNaN(Date.parse(createdAt))) {+ throw new Error(`Invalid auto mute list action at index ${index}: createdAt must be a valid ISO date`)+ }++ return {+ type,+ target,+ createdAt+ }+}diff --git a/server/core/lib/blocklist.ts b/server/core/lib/blocklist.tsindex fd0e9f6fcb..4d597a3ea5 100644--- a/server/core/lib/blocklist.ts+++ b/server/core/lib/blocklist.ts@@ -1,68 +1,126 @@+import { logger } from '@server/helpers/logger.js'import { sequelizeTypescript } from '@server/initializers/database.js'+import { AccountModel } from '@server/models/account/account.js'import { getServerActor } from '@server/models/application/application.js'-import { MAccountBlocklist, MAccountId, MAccountHost, MServerBlocklist } from '@server/types/models/index.js'-import { AccountBlocklistModel } from '../models/account/account-blocklist.js'-import { ServerBlocklistModel } from '../models/server/server-blocklist.js'+import { ServerModel } from '@server/models/server/server.js'import { UserNotificationModel } from '@server/models/user/user-notification.js'-import { logger } from '@server/helpers/logger.js'--async function addAccountInBlocklist (options: {+import {+ MAccountBlocklist,+ MAccountDefault,+ MAccountHost,+ MAccountId,+ MBlocklistSubscription,+ MServer,+ MServerBlocklist+} from '@server/types/models/index.js'+import { AccountBlocklistModel } from '../models/blocklist/account-blocklist.js'+import { BlocklistLogModel } from '../models/blocklist/blocklist-log.js'+import { ServerBlocklistModel } from '../models/blocklist/server-blocklist.js'++export async function addAccountInBlocklist (options: {byAccountId: number- targetAccountId: number+ targetAccount: MAccountDefault+ blocklistSubscription?: MBlocklistSubscriptionremoveNotificationOfUserId: number | null // If blocked by a user}) {- const { byAccountId, targetAccountId, removeNotificationOfUserId } = options+ const { byAccountId, targetAccount, blocklistSubscription, removeNotificationOfUserId } = optionsawait sequelizeTypescript.transaction(async t => {- return AccountBlocklistModel.upsert({- accountId: byAccountId,- targetAccountId- }, { transaction: t })+ const existing = await AccountBlocklistModel.loadByAccountAndTarget(byAccountId, targetAccount.id, t)++ if (!existing) {+ await AccountBlocklistModel.create({+ accountId: byAccountId,+ targetAccountId: targetAccount.id,+ blocklistSubscriptionId: blocklistSubscription?.id+ }, { transaction: t })++ await BlocklistLogModel.create({+ action: 'add',+ accountId: byAccountId,+ blocklistSubscriptionId: blocklistSubscription?.id,+ automaticallyCreated: !!blocklistSubscription,+ target: targetAccount.Actor.getFullIdentifier()+ }, { transaction: t })+ }})UserNotificationModel.removeNotificationsOf({- id: targetAccountId,+ id: targetAccount.id,type: 'account',forUserId: removeNotificationOfUserId}).catch(err => logger.error('Cannot remove notifications after an account mute.', { err }))}-async function addServerInBlocklist (options: {+export async function addServerInBlocklist (options: {byAccountId: number- targetServerId: number-+ targetServer: MServer+ blocklistSubscription?: MBlocklistSubscriptionremoveNotificationOfUserId: number | null}) {- const { byAccountId, targetServerId, removeNotificationOfUserId } = options+ const { byAccountId, targetServer, blocklistSubscription, removeNotificationOfUserId } = optionsawait sequelizeTypescript.transaction(async t => {- return ServerBlocklistModel.upsert({- accountId: byAccountId,- targetServerId- }, { transaction: t })+ const existing = await ServerBlocklistModel.loadByAccountAndTarget(byAccountId, targetServer.id, t)++ if (!existing) {+ await ServerBlocklistModel.create({+ accountId: byAccountId,+ targetServerId: targetServer.id,+ blocklistSubscriptionId: blocklistSubscription?.id+ }, { transaction: t })++ await BlocklistLogModel.create({+ action: 'add',+ accountId: byAccountId,+ blocklistSubscriptionId: blocklistSubscription?.id,+ automaticallyCreated: !!blocklistSubscription,+ target: targetServer.host+ }, { transaction: t })+ }})UserNotificationModel.removeNotificationsOf({- id: targetServerId,+ id: targetServer.id,type: 'server',forUserId: removeNotificationOfUserId}).catch(err => logger.error('Cannot remove notifications after a server mute.', { err }))}-function removeAccountFromBlocklist (accountBlock: MAccountBlocklist) {+export function removeAccountFromBlocklist (accountBlock: MAccountBlocklist) {return sequelizeTypescript.transaction(async t => {+ const targetAccount = await AccountModel.load(accountBlock.targetAccountId, t)++ await BlocklistLogModel.create({+ action: 'delete',+ accountId: accountBlock.accountId,+ blocklistSubscriptionId: accountBlock.blocklistSubscriptionId,+ automaticallyCreated: !!accountBlock.blocklistSubscriptionId,+ target: targetAccount.Actor.getFullIdentifier()+ }, { transaction: t })+return accountBlock.destroy({ transaction: t })})}-function removeServerFromBlocklist (serverBlock: MServerBlocklist) {+export function removeServerFromBlocklist (serverBlock: MServerBlocklist) {return sequelizeTypescript.transaction(async t => {+ const targetServer = await ServerModel.load(serverBlock.targetServerId, t)++ await BlocklistLogModel.create({+ action: 'delete',+ accountId: serverBlock.accountId,+ blocklistSubscriptionId: serverBlock.blocklistSubscriptionId,+ automaticallyCreated: !!serverBlock.blocklistSubscriptionId,+ target: targetServer.host+ }, { transaction: t })+return serverBlock.destroy({ transaction: t })})}-async function isBlockedByServerOrAccount (targetAccount: MAccountHost, userAccount?: MAccountId) {+export async function isBlockedByServerOrAccount (targetAccount: MAccountHost, userAccount?: MAccountId) {const serverAccountId = (await getServerActor()).Account.idconst sourceAccounts = [ serverAccountId ]@@ -80,11 +138,3 @@ async function isBlockedByServerOrAccount (targetAccount: MAccountHost, userAccoreturn false}--export {- addAccountInBlocklist,- addServerInBlocklist,- removeAccountFromBlocklist,- removeServerFromBlocklist,- isBlockedByServerOrAccount-}diff --git a/server/core/lib/job-queue/handlers/after-video-channel-import.ts b/server/core/lib/job-queue/handlers/after-video-channel-import.tsindex 58b80b8273..773e57da29 100644--- a/server/core/lib/job-queue/handlers/after-video-channel-import.ts+++ b/server/core/lib/job-queue/handlers/after-video-channel-import.ts@@ -1,4 +1,4 @@-import { AfterVideoChannelImportPayload, VideoChannelSyncState, VideoImportPreventExceptionResult } from '@peertube/peertube-models'+import { AfterVideoChannelImportPayload, StreamSyncState, VideoImportPreventExceptionResult } from '@peertube/peertube-models'import { logger, loggerTagsFactory } from '@server/helpers/logger.js'import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync.js'import { Job } from 'bullmq'@@ -28,10 +28,10 @@ export async function processAfterVideoChannelImport (job: Job) {}if (errors > 0) {- sync.state = VideoChannelSyncState.FAILED+ sync.state = StreamSyncState.FAILEDlogger.error(`Finished synchronizing "${sync.VideoChannel.Actor.preferredUsername}" with failures.`, { errors, successes, ...lTags() })} else {- sync.state = VideoChannelSyncState.SYNCED+ sync.state = StreamSyncState.SYNCEDlogger.info(`Finished synchronizing "${sync.VideoChannel.Actor.preferredUsername}" successfully.`, { successes, ...lTags() })}diff --git a/server/core/lib/notifier/notifier.ts b/server/core/lib/notifier/notifier.tsindex 826ca49bf4..fd2353bbbe 100644--- a/server/core/lib/notifier/notifier.ts+++ b/server/core/lib/notifier/notifier.ts@@ -32,6 +32,7 @@ import {AbstractNotification,AbuseStateChangeForReporter,AutoFollowForInstance,+ AutomaticBlocklistForModerators,ChannelChangeOwnershipAccepted,ChannelChangeOwnershipRejected,CommentMention,@@ -95,6 +96,8 @@ class Notifier {newPeertubeVersion: [ NewPeerTubeVersionForAdmins ],newPluginVersion: [ NewPluginVersionForAdmins ],+ automaticBlocklist: [ AutomaticBlocklistForModerators ],+channelCollaboratorInvitation: [ InvitedToCollaborateToChannel ],channelCollaborationAccepted: [ AcceptedToCollaborateToChannel ],channelCollaborationRefused: [ RefusedToCollaborateToChannel ],@@ -302,6 +305,20 @@ class Notifier {.catch(err => logger.error('Cannot notify on new plugin version %s.', plugin.name, { err }))}+ notifyOfAutomaticBlocklist (options: {+ blockedAccountsCount: number+ blockedHostsCount: number+ unblockedAccountsCount: number+ unblockedHostsCount: number+ }) {+ const models = this.notificationModels.automaticBlocklist++ logger.debug(`Notify on automatic blocklist subscription update`, { ...options, ...lTags() })++ this.sendNotifications(models, options)+ .catch(err => logger.error(`Cannot notify on automatic blocklist update.`, { err, ...options }))+ }+notifyOfFinishedVideoStudioEdition (video: MVideoFull) {const models = this.notificationModels.videoStudioEditionFinisheddiff --git a/server/core/lib/notifier/shared/change-ownership/request-channel-change-ownership.ts b/server/core/lib/notifier/shared/change-ownership/request-channel-change-ownership.tsindex a08ff3beda..a07da43d2a 100644--- a/server/core/lib/notifier/shared/change-ownership/request-channel-change-ownership.ts+++ b/server/core/lib/notifier/shared/change-ownership/request-channel-change-ownership.ts@@ -2,7 +2,7 @@ import { UserNotificationSettingValue, UserNotificationType } from '@peertube/peimport { 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 { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'import { UserModel } from '@server/models/user/user.js'import { MUserDefault, MUserWithNotificationSetting } from '@server/types/models/index.js'import { MChangeOwnershipFull } from '@server/types/models/video/change-ownership.js'diff --git a/server/core/lib/notifier/shared/change-ownership/request-video-change-ownership.ts b/server/core/lib/notifier/shared/change-ownership/request-video-change-ownership.tsindex 3f65f23070..ab97117bd7 100644--- a/server/core/lib/notifier/shared/change-ownership/request-video-change-ownership.ts+++ b/server/core/lib/notifier/shared/change-ownership/request-video-change-ownership.ts@@ -7,7 +7,7 @@ import { MUserDefault, MUserWithNotificationSetting } from '@server/types/modelsimport { MChangeOwnershipFull } from '@server/types/models/video/change-ownership.js'import { AbstractNotification } from '../common/abstract-notification.js'import { buildChangeOwnershipNotification } from './change-ownership-utils.js'-import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'export class RequestVideoChangeOwnership extends AbstractNotification<MChangeOwnershipFull> {private user: MUserDefaultdiff --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.tsindex 8e4b03f32e..cf31dcf2d4 100644--- 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.ts@@ -2,7 +2,7 @@ import { UserNotificationSettingValue, UserNotificationType } from '@peertube/peimport { 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 { AccountBlocklistModel } from '@server/models/blocklist/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'diff --git a/server/core/lib/notifier/shared/comment/comment-mention.ts b/server/core/lib/notifier/shared/comment/comment-mention.tsindex 62164a4aec..dfa9e24f1c 100644--- a/server/core/lib/notifier/shared/comment/comment-mention.ts+++ b/server/core/lib/notifier/shared/comment/comment-mention.ts@@ -3,9 +3,9 @@ import { tu } from '@server/helpers/i18n.js'import { logger } from '@server/helpers/logger.js'import { toSafeHtml } from '@server/helpers/markdown.js'import { WEBSERVER } from '@server/initializers/constants.js'-import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'import { getServerActor } from '@server/models/application/application.js'-import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'import { UserNotificationModel } from '@server/models/user/user-notification.js'import { UserModel } from '@server/models/user/user.js'import {diff --git a/server/core/lib/notifier/shared/instance/automatic-blocklist-for-moderators.ts b/server/core/lib/notifier/shared/instance/automatic-blocklist-for-moderators.tsnew file mode 100644index 0000000000..00b564a52b--- /dev/null+++ b/server/core/lib/notifier/shared/instance/automatic-blocklist-for-moderators.ts@@ -0,0 +1,63 @@+import { pick } from '@peertube/peertube-core-utils'+import { UserNotificationType, UserRight } from '@peertube/peertube-models'+import { t } from '@server/helpers/i18n.js'+import { logger } from '@server/helpers/logger.js'+import { CONFIG } from '@server/initializers/config.js'+import { UserNotificationModel } from '@server/models/user/user-notification.js'+import { UserModel } from '@server/models/user/user.js'+import { MUserDefault, MUserWithNotificationSetting, UserNotificationModelForApi } from '@server/types/models/index.js'+import { AbstractNotification } from '../common/abstract-notification.js'++export class AutomaticBlocklistForModerators extends AbstractNotification<{+ blockedAccountsCount: number+ blockedHostsCount: number+ unblockedAccountsCount: number+ unblockedHostsCount: number+}> {+ private moderators: MUserDefault[]++ async prepare () {+ this.moderators = await UserModel.listWithRight(UserRight.MANAGE_SERVER_BLOCKLIST_SUBSCRIPTIONS)+ }++ log () {+ logger.info(`Notifying ${this.moderators.length} moderators of automatic blocklist update`, this.payload)+ }++ getSetting (user: MUserWithNotificationSetting) {+ return user.NotificationSetting.automaticBlocklist+ }++ getTargetUsers () {+ return this.moderators+ }++ createNotification (user: MUserWithNotificationSetting) {+ return UserNotificationModel.build<UserNotificationModelForApi>({+ type: UserNotificationType.AUTOMATIC_BLOCKLIST_UPDATE,++ userId: user.id,++ data: pick(this.payload, [ 'blockedAccountsCount', 'blockedHostsCount', 'unblockedAccountsCount', 'unblockedHostsCount' ])+ })+ }++ createEmail (user: MUserWithNotificationSetting) {+ const to = { email: user.email, language: user.getLanguage() }+ const language = user.getLanguage()++ const data = pick(this.payload, [ 'blockedAccountsCount', 'blockedHostsCount', 'unblockedAccountsCount', 'unblockedHostsCount' ])++ const text = t(+ 'Automatic blocklist update: {blockedAccountsCount} account(s) and {blockedHostsCount} server(s) were blocked. {unblockedAccountsCount} account(s) and {unblockedHostsCount} server(s) were unblocked.',+ language,+ data+ )++ return {+ to,+ subject: t('Automatic blocklist update on {instanceName}', language, { instanceName: CONFIG.INSTANCE.NAME }),+ text+ }+ }+}diff --git a/server/core/lib/notifier/shared/instance/index.ts b/server/core/lib/notifier/shared/instance/index.tsindex c922fcbe97..c56fbdd52c 100644--- a/server/core/lib/notifier/shared/instance/index.ts+++ b/server/core/lib/notifier/shared/instance/index.ts@@ -2,3 +2,4 @@ export * from './new-peertube-version-for-admins.js'export * from './new-plugin-version-for-admins.js'export * from './direct-registration-for-moderators.js'export * from './registration-request-for-moderators.js'+export * from './automatic-blocklist-for-moderators.js'diff --git a/server/core/lib/plugins/plugin-helpers-builder.ts b/server/core/lib/plugins/plugin-helpers-builder.tsindex 37d0379643..46e186a9da 100644--- a/server/core/lib/plugins/plugin-helpers-builder.ts+++ b/server/core/lib/plugins/plugin-helpers-builder.ts@@ -5,10 +5,10 @@ import { buildLogger } from '@server/helpers/logger.js'import { CONFIG } from '@server/initializers/config.js'import { WEBSERVER } from '@server/initializers/constants.js'import { sequelizeTypescript } from '@server/initializers/database.js'-import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'import { AccountModel } from '@server/models/account/account.js'import { getServerActor } from '@server/models/application/application.js'-import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'import { ServerModel } from '@server/models/server/server.js'import { UserModel } from '@server/models/user/user.js'import { VideoBlacklistModel } from '@server/models/video/video-blacklist.js'@@ -172,7 +172,7 @@ function buildModerationHelpers () {await addServerInBlocklist({byAccountId: options.byAccountId,- targetServerId: serverToBlock.id,+ targetServer: serverToBlock,removeNotificationOfUserId: user?.id})},@@ -192,7 +192,7 @@ function buildModerationHelpers () {await addAccountInBlocklist({byAccountId: options.byAccountId,- targetAccountId: accountToBlock.id,+ targetAccount: accountToBlock,removeNotificationOfUserId: user?.id})},diff --git a/server/core/lib/schedulers/blocklist-subscriptions-scheduler.ts b/server/core/lib/schedulers/blocklist-subscriptions-scheduler.tsnew file mode 100644index 0000000000..2ce6d3d9b5--- /dev/null+++ b/server/core/lib/schedulers/blocklist-subscriptions-scheduler.ts@@ -0,0 +1,251 @@+import { AutoMuteAction, AutoMuteList, StreamSyncState } from '@peertube/peertube-models'+import { handleToNameAndHost } from '@server/helpers/actors.js'+import { logger, loggerTagsFactory } from '@server/helpers/logger.js'+import { SCHEDULER_INTERVALS_MS } from '@server/initializers/constants.js'+import { fetchAndValidateAutoMuteList } from '@server/lib/blocklist-subscriptions.js'+import {+ addAccountInBlocklist,+ addServerInBlocklist,+ removeAccountFromBlocklist,+ removeServerFromBlocklist+} from '@server/lib/blocklist.js'+import { AccountModel } from '@server/models/account/account.js'+import { getServerActor } from '@server/models/application/application.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'+import { BlocklistSubscriptionModel } from '@server/models/blocklist/blocklist-subscription.js'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'+import { ServerModel } from '@server/models/server/server.js'+import { MBlocklistSubscription } from '@server/types/models/index.js'+import { Notifier } from '../notifier/notifier.js'+import { AbstractScheduler } from './abstract-scheduler.js'++const lTags = loggerTagsFactory('schedulers')++export class BlocklistSubscriptionsScheduler extends AbstractScheduler {+ private static instance: AbstractScheduler++ protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.BLOCKLIST_SUBSCRIPTIONS_SYNC++ private constructor () {+ super({ randomRunOnEnable: true })+ }++ protected async internalExecute () {+ const serverActor = await getServerActor()++ const subscriptions = await BlocklistSubscriptionModel.listByAccountId(serverActor.Account.id)+ if (subscriptions.length === 0) return++ for (const subscription of subscriptions) {+ try {+ await this.syncSubscription({ subscription, serverAccountId: serverActor.Account.id })+ } catch (err) {+ subscription.update({ state: StreamSyncState.PROCESSING })+ .catch(err =>+ logger.error('Cannot update blocklist subscription state after failed synchronization.', {+ err,+ url: subscription.url,+ ...lTags()+ })+ )++ logger.error('Cannot synchronize blocklist subscription.', { err, url: subscription.url, ...lTags() })+ }+ }+ }++ private async syncSubscription (options: {+ subscription: MBlocklistSubscription+ serverAccountId: number+ }) {+ const { subscription, serverAccountId } = options++ logger.info(`Synchronizing blocklist subscription "${subscription.name}" (${subscription.url}).`, lTags())++ await subscription.update({ state: StreamSyncState.PROCESSING })++ const newLastSyncAt = new Date()++ const body: AutoMuteList = await fetchAndValidateAutoMuteList(subscription.url, subscription.lastActionCreatedAt)++ logger.debug('Fetched blocklist subscription data.', {+ ...lTags(),+ subscriptionUrl: subscription.url,+ actionsCount: body.actions.length+ })++ const actions = body.actions+ .map(action => ({ ...action, createdAtMs: Date.parse(action.createdAt) }))+ .filter(action => {+ if (Number.isNaN(action.createdAtMs)) return false++ if (!subscription.lastActionCreatedAt) return true++ return action.createdAtMs > subscription.lastActionCreatedAt.getTime()+ })+ .sort((a, b) => a.createdAtMs - b.createdAtMs)++ const blockedAccounts = new Set<string>()+ const blockedHosts = new Set<string>()+ const unblockedAccounts = new Set<string>()+ const unblockedHosts = new Set<string>()++ for (const action of actions) {+ const actionResult = await this.handleAction({+ action,+ serverAccountId,+ subscription+ })++ if (!actionResult) continue++ const [ blocked, unblocked ] = actionResult.targetType === 'account'+ ? [ blockedAccounts, unblockedAccounts ]+ : [ blockedHosts, unblockedHosts ]++ if (actionResult.actionType === 'block') {+ if (unblocked.has(action.target)) unblocked.delete(action.target)+ else blocked.add(action.target)+ } else {+ // oxlint-disable-next-line no-lonely-if+ if (blocked.has(action.target)) blocked.delete(action.target)+ else unblocked.add(action.target)+ }+ }++ this.notifyOfAutomaticBlocklistActions({+ block: {+ accountsCount: blockedAccounts.size,+ hostsCount: blockedHosts.size+ },+ unblock: {+ accountsCount: unblockedAccounts.size,+ hostsCount: unblockedHosts.size+ }+ })++ const lastActionCreatedAt = actions.length !== 0+ ? new Date(actions[actions.length - 1].createdAt)+ : subscription.lastActionCreatedAt++ await subscription.update({ name: body.name, lastSyncAt: newLastSyncAt, lastActionCreatedAt, state: StreamSyncState.SYNCED })+ }++ private async handleAction (options: {+ action: AutoMuteAction+ serverAccountId: number+ subscription: MBlocklistSubscription+ }) {+ const { action, serverAccountId, subscription } = options++ if (action.target.includes('@')) {+ return this.handleAccountAction({+ action,+ serverAccountId,+ subscription+ })+ }++ return this.handleServerAction({+ action,+ serverAccountId,+ subscription+ })+ }++ private async handleAccountAction (options: {+ action: AutoMuteAction+ serverAccountId: number+ subscription: MBlocklistSubscription+ }) {+ const { action, serverAccountId, subscription } = options++ const { name, host } = handleToNameAndHost(action.target)++ // TODO: handle actors that are not yet federated+ const account = host+ ? await AccountModel.loadByNameAndHost(name, host)+ : await AccountModel.loadLocalByName(name)++ if (!account) return null++ if (action.type === 'block') {+ const existing = await AccountBlocklistModel.loadByAccountAndTarget(serverAccountId, account.id)+ if (existing) return null++ await addAccountInBlocklist({+ byAccountId: serverAccountId,+ targetAccount: account,+ blocklistSubscription: subscription,+ removeNotificationOfUserId: null+ })+ } else if (action.type === 'unblock') {+ const block = await AccountBlocklistModel.loadByAccountAndTarget(serverAccountId, account.id)+ if (!block || block.blocklistSubscriptionId !== subscription.id) return null++ await removeAccountFromBlocklist(block)+ }++ return {+ actionType: action.type,+ targetType: 'account' as const+ }+ }++ private async handleServerAction (options: {+ action: AutoMuteAction+ serverAccountId: number+ subscription: MBlocklistSubscription+ }) {+ const { action, serverAccountId, subscription } = options++ const server = await ServerModel.loadOrCreateByHost(action.target)++ if (action.type === 'block') {+ const existing = await ServerBlocklistModel.loadByAccountAndHost(serverAccountId, action.target)+ if (existing) return null++ await addServerInBlocklist({+ byAccountId: serverAccountId,+ targetServer: server,+ blocklistSubscription: subscription,+ removeNotificationOfUserId: null+ })+ } else if (action.type === 'unblock') {+ const block = await ServerBlocklistModel.loadByAccountAndHost(serverAccountId, action.target)+ if (!block || block.blocklistSubscriptionId !== subscription.id) return null++ await removeServerFromBlocklist(block)+ }++ return {+ actionType: action.type,+ targetType: 'host' as const+ }+ }++ private notifyOfAutomaticBlocklistActions (stats: {+ block: { accountsCount: number, hostsCount: number }+ unblock: { accountsCount: number, hostsCount: number }+ }) {+ if (+ stats.block.accountsCount === 0 &&+ stats.block.hostsCount === 0 &&+ stats.unblock.accountsCount === 0 &&+ stats.unblock.hostsCount === 0+ ) {+ return+ }++ Notifier.Instance.notifyOfAutomaticBlocklist({+ blockedAccountsCount: stats.block.accountsCount,+ blockedHostsCount: stats.block.hostsCount,+ unblockedAccountsCount: stats.unblock.accountsCount,+ unblockedHostsCount: stats.unblock.hostsCount+ })+ }++ static get Instance () {+ return this.instance || (this.instance = new this())+ }+}diff --git a/server/core/lib/search.ts b/server/core/lib/search.tsindex 567eced7cc..63ca1b7106 100644--- a/server/core/lib/search.ts+++ b/server/core/lib/search.ts@@ -1,8 +1,8 @@import express from 'express'import { CONFIG } from '@server/initializers/config.js'-import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'import { getServerActor } from '@server/models/application/application.js'-import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'import { SearchTargetQuery } from '@peertube/peertube-models'function isSearchIndexSearch (query: SearchTargetQuery) {diff --git a/server/core/lib/server-config-manager.ts b/server/core/lib/server-config-manager.tsindex b95977123a..bc8a21615b 100644--- a/server/core/lib/server-config-manager.ts+++ b/server/core/lib/server-config-manager.ts@@ -369,6 +369,12 @@ class ServerConfigManager {}},+ blocklist: {+ publicLog: {+ enabled: CONFIG.BLOCKLIST.PUBLIC_LOG.ENABLED+ }+ },+federation: {enabled: CONFIG.FEDERATION.ENABLED},diff --git a/server/core/lib/sync-channel.ts b/server/core/lib/sync-channel.tsindex f86470a86f..8f2ec5b206 100644--- a/server/core/lib/sync-channel.ts+++ b/server/core/lib/sync-channel.ts@@ -1,4 +1,4 @@-import { VideoChannelSyncState } from '@peertube/peertube-models'+import { StreamSyncState } from '@peertube/peertube-models'import { logger, loggerTagsFactory, LoggerTagsFn } from '@server/helpers/logger.js'import { YoutubeDlImportError, YoutubeDlImportErrorCode, YoutubeDLWrapper } from '@server/helpers/youtube-dl/index.js'import { CONFIG } from '@server/initializers/config.js'@@ -24,7 +24,7 @@ export async function synchronizeChannel (options: {const channelUsername = channel.Actor.preferredUsernameif (channelSync) {- channelSync.state = VideoChannelSyncState.PROCESSING+ channelSync.state = StreamSyncState.PROCESSINGchannelSync.lastSyncAt = new Date()await channelSync.save()}@@ -123,7 +123,7 @@ export async function synchronizeChannel (options: {logger.error(`Failed to import ${externalChannelUrl} in channel ${channelUsername}`, { err, ...rootLTags() })if (channelSync) {- channelSync.state = VideoChannelSyncState.FAILED+ channelSync.state = StreamSyncState.FAILEDawait channelSync.save()}}diff --git a/server/core/lib/user-import-export/exporters/blocklist-exporter.ts b/server/core/lib/user-import-export/exporters/blocklist-exporter.tsindex 74b3a5b370..ebfbacbcf5 100644--- a/server/core/lib/user-import-export/exporters/blocklist-exporter.ts+++ b/server/core/lib/user-import-export/exporters/blocklist-exporter.ts@@ -1,10 +1,9 @@import { AbstractUserExporter } from './abstract-user-exporter.js'-import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'-import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.js'import { BlocklistExportJSON } from '@peertube/peertube-models'-export class BlocklistExporter extends AbstractUserExporter <BlocklistExportJSON> {-+export class BlocklistExporter extends AbstractUserExporter<BlocklistExportJSON> {async export () {const [ instancesBlocklist, accountsBlocklist ] = await Promise.all([ServerBlocklistModel.listHostsBlockedBy([ this.user.Account.id ]),@@ -20,5 +19,4 @@ export class BlocklistExporter extends AbstractUserExporter <BlocklistExportJSONstaticFiles: []}}-}diff --git a/server/core/lib/user-import-export/importers/account-blocklist-importer.ts b/server/core/lib/user-import-export/importers/account-blocklist-importer.tsindex 99458d4091..2b084f3576 100644--- a/server/core/lib/user-import-export/importers/account-blocklist-importer.ts+++ b/server/core/lib/user-import-export/importers/account-blocklist-importer.ts@@ -1,12 +1,12 @@+import { pick } from '@peertube/peertube-core-utils'import { BlocklistExportJSON } from '@peertube/peertube-models'+import { isValidActorHandle } from '@server/helpers/custom-validators/activitypub/actor.js'+import { isHostValid } from '@server/helpers/custom-validators/servers.js'import { logger, loggerTagsFactory } from '@server/helpers/logger.js'-import { AbstractUserImporter } from './abstract-user-importer.js'import { addAccountInBlocklist, addServerInBlocklist } from '@server/lib/blocklist.js'-import { ServerModel } from '@server/models/server/server.js'import { AccountModel } from '@server/models/account/account.js'-import { isValidActorHandle } from '@server/helpers/custom-validators/activitypub/actor.js'-import { isHostValid } from '@server/helpers/custom-validators/servers.js'-import { pick } from '@peertube/peertube-core-utils'+import { ServerModel } from '@server/models/server/server.js'+import { AbstractUserImporter } from './abstract-user-importer.js'const lTags = loggerTagsFactory('user-import')@@ -45,7 +45,7 @@ export class BlocklistImporter extends AbstractUserImporter<BlocklistExportJSON,await addAccountInBlocklist({byAccountId: this.user.Account.id,- targetAccountId: accountToBlock.id,+ targetAccount: accountToBlock,removeNotificationOfUserId: this.user.id})@@ -57,7 +57,7 @@ export class BlocklistImporter extends AbstractUserImporter<BlocklistExportJSON,await addServerInBlocklist({byAccountId: this.user.Account.id,- targetServerId: serverToBlock.id,+ targetServer: serverToBlock,removeNotificationOfUserId: this.user.id})diff --git a/server/core/lib/user-import-export/importers/user-settings-importer.ts b/server/core/lib/user-import-export/importers/user-settings-importer.tsindex 8757571ed1..2226e9b97c 100644--- a/server/core/lib/user-import-export/importers/user-settings-importer.ts+++ b/server/core/lib/user-import-export/importers/user-settings-importer.ts@@ -108,7 +108,8 @@ export class UserSettingsImporter extends AbstractUserImporter<UserSettingsExpornewPeerTubeVersion: settingsImportData.newPeerTubeVersion,newPluginVersion: settingsImportData.newPluginVersion,myVideoStudioEditionFinished: settingsImportData.myVideoStudioEditionFinished,- myVideoTranscriptionGenerated: settingsImportData.myVideoTranscriptionGenerated+ myVideoTranscriptionGenerated: settingsImportData.myVideoTranscriptionGenerated,+ automaticBlocklist: settingsImportData.automaticBlocklist}await UserNotificationSettingModel.updateUserSettings(values, this.user.id)diff --git a/server/core/lib/user.ts b/server/core/lib/user.tsindex f0db8d0d2c..155bccf730 100644--- a/server/core/lib/user.ts+++ b/server/core/lib/user.ts@@ -288,7 +288,8 @@ function createDefaultUserNotificationSettings (user: MUserId, t: Transaction |newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,newPluginVersion: UserNotificationSettingValue.WEB,myVideoStudioEditionFinished: UserNotificationSettingValue.WEB,- myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB+ myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB,+ automaticBlocklist: UserNotificationSettingValue.WEB}return UserNotificationSettingModel.create(values, { transaction: t })diff --git a/server/core/middlewares/validators/blocklist.ts b/server/core/middlewares/validators/blocklist.tsindex f72d30f58e..d06323a19f 100644--- a/server/core/middlewares/validators/blocklist.ts+++ b/server/core/middlewares/validators/blocklist.ts@@ -1,17 +1,20 @@import { HttpStatusCode } from '@peertube/peertube-models'import { areValidActorHandles } from '@server/helpers/custom-validators/activitypub/actor.js'-import { toArray } from '@server/helpers/custom-validators/misc.js'+import { isUrlValid } from '@server/helpers/custom-validators/activitypub/misc.js'+import { isDateValid, isIdValid, toArray } from '@server/helpers/custom-validators/misc.js'+import { CONFIG } from '@server/initializers/config.js'import { getServerActor } from '@server/models/application/application.js'import express from 'express'import { body, param, query } from 'express-validator'import { isEachUniqueHostValid, isHostValid } from '../../helpers/custom-validators/servers.js'import { WEBSERVER } from '../../initializers/constants.js'-import { AccountBlocklistModel } from '../../models/account/account-blocklist.js'-import { ServerBlocklistModel } from '../../models/server/server-blocklist.js'+import { AccountBlocklistModel } from '../../models/blocklist/account-blocklist.js'+import { BlocklistSubscriptionModel } from '../../models/blocklist/blocklist-subscription.js'+import { ServerBlocklistModel } from '../../models/blocklist/server-blocklist.js'import { ServerModel } from '../../models/server/server.js'import { areValidationErrors, doesAccountHandleExist } from './shared/index.js'-const blockAccountValidator = [+export const blockAccountValidator = [body('accountName').exists(),@@ -34,7 +37,7 @@ const blockAccountValidator = [}]-const unblockAccountByAccountValidator = [+export const unblockAccountByAccountValidator = [param('accountName').exists(),@@ -50,7 +53,7 @@ const unblockAccountByAccountValidator = [}]-const unblockAccountByServerValidator = [+export const unblockAccountByServerValidator = [param('accountName').exists(),@@ -66,7 +69,7 @@ const unblockAccountByServerValidator = [}]-const blockServerValidator = [+export const blockServerValidator = [body('host').custom(isHostValid),@@ -90,7 +93,7 @@ const blockServerValidator = [}]-const unblockServerByAccountValidator = [+export const unblockServerByAccountValidator = [param('host').custom(isHostValid),@@ -104,7 +107,7 @@ const unblockServerByAccountValidator = [}]-const unblockServerByServerValidator = [+export const unblockServerByServerValidator = [param('host').custom(isHostValid),@@ -118,7 +121,7 @@ const unblockServerByServerValidator = [}]-const blocklistStatusValidator = [+export const blocklistStatusValidator = [query('hosts').optional().customSanitizer(toArray)@@ -136,18 +139,69 @@ const blocklistStatusValidator = [}]-// ---------------------------------------------------------------------------+export const addBlocklistSubscriptionValidator = [+ body('url')+ .custom(isUrlValid).withMessage('Should have a valid URL'),-export {- blockAccountValidator,- blocklistStatusValidator,- blockServerValidator,- unblockAccountByAccountValidator,- unblockAccountByServerValidator,- unblockServerByAccountValidator,- unblockServerByServerValidator-}+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return++ const serverActor = await getServerActor()++ const existingSubscription = await BlocklistSubscriptionModel.loadByUrl({+ accountId: serverActor.Account.id,+ url: req.body.url+ })++ if (existingSubscription) {+ return res.fail({+ status: HttpStatusCode.CONFLICT_409,+ message: req.t('Subscription with URL {{url}} already exists', { url: req.body.url })+ })+ }++ return next()+ }+]++export const deleteBlocklistSubscriptionValidator = [+ param('id')+ .custom(isIdValid),++ async (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return+ const subscription = await BlocklistSubscriptionModel.loadById(+req.params.id)+ if (!subscription) {+ return res.fail({+ status: HttpStatusCode.NOT_FOUND_404,+ message: req.t('Blocklist subscription not found')+ })+ }++ res.locals.blocklistSubscription = subscription+ return next()+ }+]++export const publicBlocklistLogValidator = [+ query('startDate')+ .optional()+ .custom(isDateValid).withMessage('Should have a start date that conforms to ISO 8601'),++ (req: express.Request, res: express.Response, next: express.NextFunction) => {+ if (areValidationErrors(req, res)) return++ if (CONFIG.BLOCKLIST.PUBLIC_LOG.ENABLED !== true) {+ return res.sendStatus(HttpStatusCode.FORBIDDEN_403)+ }++ return next()+ }+]++// ---------------------------------------------------------------------------+// Private// ---------------------------------------------------------------------------async function doesUnblockAccountExist (accountId: number, targetAccountId: number, res: express.Response) {diff --git a/server/core/middlewares/validators/config.ts b/server/core/middlewares/validators/config.tsindex fbb05530ea..aef22d9935 100644--- a/server/core/middlewares/validators/config.ts+++ b/server/core/middlewares/validators/config.ts@@ -113,7 +113,7 @@ export const customConfigUpdateValidator = [body('broadcastMessage.message').exists(),body('broadcastMessage.level').exists(),body('broadcastMessage.dismissable').isBoolean(),-+ body('blocklist.publicLog.enabled').isBoolean(),body('live.enabled').isBoolean(),body('live.allowReplay').isBoolean(),body('defaults.live.saveReplay').isBoolean(),diff --git a/server/core/middlewares/validators/sort.ts b/server/core/middlewares/validators/sort.tsindex 1a7277f819..68e7029394 100644--- a/server/core/middlewares/validators/sort.ts+++ b/server/core/middlewares/validators/sort.ts@@ -22,6 +22,7 @@ export const instanceFollowingSortValidator = checkSortFactory(SORTABLE_COLUMNS.export const userSubscriptionsSortValidator = checkSortFactory(SORTABLE_COLUMNS.USER_SUBSCRIPTIONS)export const accountsBlocklistSortValidator = checkSortFactory(SORTABLE_COLUMNS.ACCOUNTS_BLOCKLIST)export const serversBlocklistSortValidator = checkSortFactory(SORTABLE_COLUMNS.SERVERS_BLOCKLIST)+export const blocklistSubscriptionsSortValidator = checkSortFactory(SORTABLE_COLUMNS.BLOCKLIST_SUBSCRIPTIONS)export const userNotificationsSortValidator = checkSortFactory(SORTABLE_COLUMNS.USER_NOTIFICATIONS)export const videoPlaylistsSortValidator = checkSortFactory(SORTABLE_COLUMNS.VIDEO_PLAYLISTS)export const pluginsSortValidator = checkSortFactory(SORTABLE_COLUMNS.PLUGINS)diff --git a/server/core/models/account/account.ts b/server/core/models/account/account.tsindex b1f7b05cb2..1a1f33a717 100644--- a/server/core/models/account/account.ts+++ b/server/core/models/account/account.ts@@ -38,7 +38,7 @@ 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 { ServerBlocklistModel } from '../blocklist/server-blocklist.js'import { ServerModel, serverSummaryAttributes } from '../server/server.js'import { SequelizeModel, buildSQLAttributes, getSort, throwIfNotValid } from '../shared/index.js'import { UserModel } from '../user/user.js'@@ -47,7 +47,7 @@ import { VideoChannelModel } from '../video/video-channel.js'import { VideoCommentModel } from '../video/video-comment.js'import { VideoPlaylistModel } from '../video/video-playlist.js'import { VideoModel } from '../video/video.js'-import { AccountBlocklistModel } from './account-blocklist.js'+import { AccountBlocklistModel } from '../blocklist/account-blocklist.js'export enum ScopeNames {SUMMARY = 'SUMMARY'diff --git a/server/core/models/account/account-blocklist.ts b/server/core/models/blocklist/account-blocklist.tssimilarity index 75%rename from server/core/models/account/account-blocklist.tsrename to server/core/models/blocklist/account-blocklist.tsindex d268d29e21..8abeb8264a 100644--- a/server/core/models/account/account-blocklist.ts+++ b/server/core/models/blocklist/account-blocklist.ts@@ -1,13 +1,14 @@-import { FindOptions, Op, QueryTypes } from 'sequelize'-import { BelongsTo, Column, CreatedAt, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'import { AccountBlock } from '@peertube/peertube-models'import { handlesToNameAndHost } from '@server/helpers/actors.js'+import { WEBSERVER } from '@server/initializers/constants.js'import { MAccountBlocklist, MAccountBlocklistFormattable } from '@server/types/models/index.js'+import { FindOptions, Includeable, Op, QueryTypes, Transaction } from 'sequelize'+import { BelongsTo, Column, CreatedAt, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'import { ActorModel } from '../actor/actor.js'+import { BlocklistSubscriptionModel } from './blocklist-subscription.js'import { ServerModel } from '../server/server.js'import { SequelizeModel, createSafeIn, getSort, searchAttribute } from '../shared/index.js'-import { AccountModel } from './account.js'-import { WEBSERVER } from '@server/initializers/constants.js'+import { AccountModel } from '../account/account.js'@Table({tableName: 'accountBlocklist',@@ -56,6 +57,19 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>})declare BlockedAccount: Awaited<AccountModel>+ @ForeignKey(() => BlocklistSubscriptionModel)+ @Column+ declare blocklistSubscriptionId: number | null++ @BelongsTo(() => BlocklistSubscriptionModel, {+ foreignKey: {+ name: 'blocklistSubscriptionId',+ allowNull: true+ },+ onDelete: 'CASCADE'+ })+ declare BlocklistSubscription: Awaited<BlocklistSubscriptionModel>+static isAccountMutedByAccounts (accountIds: number[], targetAccountId: number) {const query = {attributes: [ 'accountId', 'id' ],@@ -81,12 +95,13 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>})}- static loadByAccountAndTarget (accountId: number, targetAccountId: number): Promise<MAccountBlocklist> {+ static loadByAccountAndTarget (accountId: number, targetAccountId: number, transaction?: Transaction): Promise<MAccountBlocklist> {const query = {where: {accountId,targetAccountId- }+ },+ transaction}return AccountBlocklistModel.findOne(query)@@ -97,9 +112,10 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>count: numbersort: stringsearch?: string+ subscriptionName?: stringaccountId: number}) {- const { start, count, sort, search, accountId } = parameters+ const { start, count, sort, search, subscriptionName, accountId } = parametersconst getQuery = (forCount: boolean) => {const query: FindOptions = {@@ -109,6 +125,8 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>where: { accountId }}+ const include: Includeable[] = []+if (search) {Object.assign(query.where, {[Op.or]: [@@ -118,8 +136,9 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>})}+ // Fetch more data for listif (forCount !== true) {- query.include = [+ include.push({model: AccountModel,required: true,@@ -130,9 +149,10 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>required: true,as: 'BlockedAccount'}- ]- } else if (search) { // We need some joins when counting with search- query.include = [+ )+ } else if (search) {+ // For the where+ include.push({model: AccountModel.unscoped(),required: true,@@ -144,9 +164,24 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>}]}- ]+ )}+ if (subscriptionName) {+ include.push({+ model: BlocklistSubscriptionModel.unscoped(),+ required: true,+ where: { name: subscriptionName }+ })+ } else if (!forCount) {+ include.push({+ model: BlocklistSubscriptionModel,+ required: false+ })+ }++ query.include = include+return query}@@ -198,7 +233,10 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>})}- static getBlockStatus (byAccountIds: number[], handles: string[]): Promise<{ name: string, host: string, accountId: number }[]> {+ static getBlockStatus (+ byAccountIds: number[],+ handles: string[]+ ): Promise<{ name: string, host: string, accountId: number, blocklistSubscriptionName: string }[]> {const sanitizedHandles = handlesToNameAndHost(handles)const localHandles = sanitizedHandles.filter(h => !h.host)@@ -217,11 +255,13 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>handlesWhere.push(`(("actor"."preferredUsername", "server"."host") IN (:remoteHandles))`)}- const rawQuery = `SELECT "accountBlocklist"."accountId", "actor"."preferredUsername" AS "name", "server"."host" ` ++ const rawQuery =+ `SELECT "accountBlocklist"."accountId", "blocklistSubscription"."name" AS "blocklistSubscriptionName", "actor"."preferredUsername" AS "name", "server"."host" ` +`FROM "accountBlocklist" ` +`INNER JOIN "account" ON "account"."id" = "accountBlocklist"."targetAccountId" ` +`INNER JOIN "actor" ON "actor"."accountId" = "account"."id" ` +`LEFT JOIN "server" ON "server"."id" = "actor"."serverId" ` ++ `LEFT JOIN "blocklistSubscription" ON "accountBlocklist"."blocklistSubscriptionId" = "blocklistSubscription"."id" ` +`WHERE "accountBlocklist"."accountId" IN (${createSafeIn(AccountBlocklistModel.sequelize, byAccountIds)}) ` +`AND (${handlesWhere.join(' OR ')})`@@ -235,6 +275,11 @@ export class AccountBlocklistModel extends SequelizeModel<AccountBlocklistModel>return {byAccount: this.ByAccount.toFormattedJSON(),blockedAccount: this.BlockedAccount.toFormattedJSON(),++ blocklistSubscription: this.BlocklistSubscription+ ? this.BlocklistSubscription.toFormattedSummaryJSON()+ : null,+createdAt: this.createdAt}}diff --git a/server/core/models/blocklist/blocklist-log.ts b/server/core/models/blocklist/blocklist-log.tsnew file mode 100644index 0000000000..cd683bbd4c--- /dev/null+++ b/server/core/models/blocklist/blocklist-log.ts@@ -0,0 +1,106 @@+import type { BlocklistLog, BlocklistLogAction } from '@peertube/peertube-models'+import { MBlocklistLog } from '@server/types/models/index.js'+import { FindOptions, Op } from 'sequelize'+import { BelongsTo, Column, CreatedAt, DataType, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'+import { AccountModel } from '../account/account.js'+import { getSort, SequelizeModel } from '../shared/index.js'+import { BlocklistSubscriptionModel } from './blocklist-subscription.js'++@Table({+ tableName: 'blocklistLog',+ indexes: [+ {+ fields: [ 'accountId' ]+ },+ {+ fields: [ 'createdAt' ]+ },+ {+ fields: [ 'blocklistSubscriptionId' ]+ }+ ]+})+export class BlocklistLogModel extends SequelizeModel<BlocklistLogModel> {+ @CreatedAt+ declare createdAt: Date++ @UpdatedAt+ declare updatedAt: Date++ @Column(DataType.ENUM('add', 'delete'))+ declare action: BlocklistLogAction++ @Column+ declare automaticallyCreated: boolean++ @ForeignKey(() => AccountModel)+ @Column+ declare accountId: number | null++ @BelongsTo(() => AccountModel, {+ foreignKey: {+ name: 'accountId',+ allowNull: true+ },+ onDelete: 'SET NULL'+ })+ declare Account: Awaited<AccountModel>++ @ForeignKey(() => BlocklistSubscriptionModel)+ @Column+ declare blocklistSubscriptionId: number | null++ @BelongsTo(() => BlocklistSubscriptionModel, {+ foreignKey: {+ name: 'blocklistSubscriptionId',+ allowNull: true+ },+ onDelete: 'SET NULL'+ })+ declare BlocklistSubscription: Awaited<BlocklistSubscriptionModel>++ @Column+ declare target: string++ static listPublicForApi (parameters: {+ accountId: number+ startDate: string+ start: number+ count: number+ sort: string+ }) {+ const { accountId, startDate, start, count, sort } = parameters++ const query: FindOptions = {+ offset: start,+ limit: count,+ order: getSort(sort),+ where: {+ accountId,+ automaticallyCreated: false,++ ...(startDate ?+ {+ createdAt: {+ [Op.gte]: new Date(startDate)+ }+ } :+ {})+ }+ }++ return Promise.all([+ BlocklistLogModel.count(query),+ BlocklistLogModel.findAll<MBlocklistLog>(query)+ ]).then(([ total, data ]) => ({ total, data }))+ }++ toFormattedJSON (this: MBlocklistLog): BlocklistLog {+ return {+ id: this.id,+ action: this.action,+ target: this.target,+ createdAt: this.createdAt+ }+ }+}diff --git a/server/core/models/blocklist/blocklist-subscription.ts b/server/core/models/blocklist/blocklist-subscription.tsnew file mode 100644index 0000000000..f3b0256063--- /dev/null+++ b/server/core/models/blocklist/blocklist-subscription.ts@@ -0,0 +1,204 @@+import { BlocklistSubscription, StreamSyncState, type StreamSyncStateType } from '@peertube/peertube-models'+import { MBlocklistSubscription } from '@server/types/models/index.js'+import { FindOptions, literal, Op } from 'sequelize'+import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, HasMany, Table, UpdatedAt } from 'sequelize-typescript'+import { AccountModel } from '../account/account.js'+import { getSort, searchAttribute, SequelizeModel } from '../shared/index.js'+import { AccountBlocklistModel } from './account-blocklist.js'+import { BlocklistLogModel } from './blocklist-log.js'+import { ServerBlocklistModel } from './server-blocklist.js'+import { STREAM_SYNC_STATE } from '@server/initializers/constants.js'++@Table({+ tableName: 'blocklistSubscription',+ indexes: [+ {+ fields: [ 'accountId', 'url' ],+ unique: true+ }+ ]+})+export class BlocklistSubscriptionModel extends SequelizeModel<BlocklistSubscriptionModel> {+ @CreatedAt+ declare createdAt: Date++ @UpdatedAt+ declare updatedAt: Date++ @AllowNull(false)+ @Column+ declare name: string++ @AllowNull(false)+ @Column+ declare url: string++ @Column+ declare lastSyncAt: Date | null++ @Column+ declare lastActionCreatedAt: Date | null++ @AllowNull(false)+ @Default(StreamSyncState.WAITING_FIRST_RUN)+ @Column+ declare state: StreamSyncStateType++ declare mutedAccountsCount: number+ declare mutedServersCount: number++ @ForeignKey(() => AccountModel)+ @Column+ declare accountId: number++ @BelongsTo(() => AccountModel, {+ foreignKey: {+ name: 'accountId',+ allowNull: false+ },+ onDelete: 'CASCADE'+ })+ declare Account: Awaited<AccountModel>++ @HasMany(() => AccountBlocklistModel, {+ foreignKey: {+ name: 'blocklistSubscriptionId',+ allowNull: true+ },+ onDelete: 'CASCADE'+ })+ declare AccountBlocklists: Awaited<AccountBlocklistModel[]>++ @HasMany(() => ServerBlocklistModel, {+ foreignKey: {+ name: 'blocklistSubscriptionId',+ allowNull: true+ },+ onDelete: 'CASCADE'+ })+ declare ServerBlocklists: Awaited<ServerBlocklistModel[]>++ @HasMany(() => BlocklistLogModel, {+ foreignKey: {+ name: 'blocklistSubscriptionId',+ allowNull: true+ },+ onDelete: 'SET NULL'+ })+ declare BlocklistLogs: Awaited<BlocklistLogModel[]>++ static loadById (id: number) {+ return BlocklistSubscriptionModel.findByPk<MBlocklistSubscription>(id)+ }++ static loadByUrl (options: {+ accountId: number+ url: string+ }) {+ return BlocklistSubscriptionModel.findOne<MBlocklistSubscription>({+ where: {+ url: options.url,+ accountId: options.accountId+ }+ })+ }++ static listByAccountId (accountId: number) {+ return BlocklistSubscriptionModel.findAll<MBlocklistSubscription>({+ where: {+ accountId+ }+ })+ }++ static listForApi (parameters: {+ accountId: number+ start: number+ count: number+ sort: string+ search?: string+ }) {+ const { start, count, sort, search, accountId } = parameters++ const where = {+ accountId,++ ...(search+ ? {+ [Op.or]: [+ searchAttribute(search, 'name'),+ searchAttribute(search, 'url')+ ]+ }+ : {})+ }++ const findQuery: FindOptions = {+ attributes: {+ include: [+ [+ literal(+ '(' ++ 'SELECT COUNT(*) ' ++ 'FROM "accountBlocklist" ' ++ 'INNER JOIN "blocklistSubscription" ON "blocklistSubscription"."id" = "accountBlocklist"."blocklistSubscriptionId" ' ++ 'WHERE "blocklistSubscription"."id" = "BlocklistSubscriptionModel"."id"' ++ ')'+ ),+ 'mutedAccountsCount'+ ],+ [+ literal(+ '(' ++ 'SELECT COUNT(*) ' ++ 'FROM "serverBlocklist" ' ++ 'INNER JOIN "blocklistSubscription" ON "blocklistSubscription"."id" = "serverBlocklist"."blocklistSubscriptionId" ' ++ 'WHERE "blocklistSubscription"."id" = "BlocklistSubscriptionModel"."id"' ++ ')'+ ),+ 'mutedServersCount'+ ]+ ]+ },+ offset: start,+ limit: count,+ order: getSort(sort),+ where+ }++ const countQuery = { where }++ return Promise.all([+ BlocklistSubscriptionModel.count(countQuery),+ BlocklistSubscriptionModel.findAll<MBlocklistSubscription>(findQuery)+ ]).then(([ total, data ]) => ({ total, data }))+ }++ toFormattedSummaryJSON (this: MBlocklistSubscription) {+ return {+ id: this.id,+ name: this.name,+ url: this.url+ }+ }++ toFormattedJSON (this: MBlocklistSubscription): BlocklistSubscription {+ const mutedAccountsCount = this.getDataValue('mutedAccountsCount') ?? 0+ const mutedServersCount = this.getDataValue('mutedServersCount') ?? 0++ return {+ id: this.id,+ name: this.name,+ url: this.url,+ mutedAccountsCount,+ mutedServersCount,+ lastSyncAt: this.lastSyncAt,+ state: {+ id: this.state,+ label: STREAM_SYNC_STATE[this.state]+ },+ createdAt: this.createdAt,+ updatedAt: this.updatedAt+ }+ }+}diff --git a/server/core/models/server/server-blocklist.ts b/server/core/models/blocklist/server-blocklist.tssimilarity index 60%rename from server/core/models/server/server-blocklist.tsrename to server/core/models/blocklist/server-blocklist.tsindex 20b131b1ff..bf56630b25 100644--- a/server/core/models/server/server-blocklist.ts+++ b/server/core/models/blocklist/server-blocklist.ts@@ -1,34 +1,12 @@-import { Op, QueryTypes } from 'sequelize'-import { BelongsTo, Column, CreatedAt, ForeignKey, Scopes, Table, UpdatedAt } from 'sequelize-typescript'-import { MServerBlocklist, MServerBlocklistAccountServer, MServerBlocklistFormattable } from '@server/types/models/index.js'import { ServerBlock } from '@peertube/peertube-models'+import { MServerBlocklist, MServerBlocklistAccountServer, MServerBlocklistFormattable } from '@server/types/models/index.js'+import { FindOptions, Op, QueryTypes, Transaction } from 'sequelize'+import { BelongsTo, Column, CreatedAt, ForeignKey, Table, UpdatedAt } from 'sequelize-typescript'import { AccountModel } from '../account/account.js'+import { ServerModel } from '../server/server.js'import { SequelizeModel, createSafeIn, getSort, searchAttribute } from '../shared/index.js'-import { ServerModel } from './server.js'+import { BlocklistSubscriptionModel } from './blocklist-subscription.js'-enum ScopeNames {- WITH_ACCOUNT = 'WITH_ACCOUNT',- WITH_SERVER = 'WITH_SERVER'-}--@Scopes(() => ({- [ScopeNames.WITH_ACCOUNT]: {- include: [- {- model: AccountModel,- required: true- }- ]- },- [ScopeNames.WITH_SERVER]: {- include: [- {- model: ServerModel,- required: true- }- ]- }-}))@Table({tableName: 'serverBlocklist',indexes: [@@ -73,6 +51,19 @@ export class ServerBlocklistModel extends SequelizeModel<ServerBlocklistModel> {})declare BlockedServer: Awaited<ServerModel>+ @ForeignKey(() => BlocklistSubscriptionModel)+ @Column+ declare blocklistSubscriptionId: number++ @BelongsTo(() => BlocklistSubscriptionModel, {+ foreignKey: {+ name: 'blocklistSubscriptionId',+ allowNull: true+ },+ onDelete: 'CASCADE'+ })+ declare BlocklistSubscription: Awaited<BlocklistSubscriptionModel>+static isServerMutedByAccounts (accountIds: number[], targetServerId: number) {const query = {attributes: [ 'accountId', 'id' ],@@ -117,6 +108,17 @@ export class ServerBlocklistModel extends SequelizeModel<ServerBlocklistModel> {return ServerBlocklistModel.findOne(query)}+ static loadByAccountAndTarget (accountId: number, targetServerId: number, transaction?: Transaction): Promise<MServerBlocklist> {+ const query = {+ where: {+ accountId,+ targetServerId+ }+ }++ return ServerBlocklistModel.findOne(query)+ }+static listHostsBlockedBy (accountIds: number[]): Promise<string[]> {const query = {attributes: [],@@ -138,10 +140,15 @@ export class ServerBlocklistModel extends SequelizeModel<ServerBlocklistModel> {.then(entries => entries.map(e => e.BlockedServer.host))}- static getBlockStatus (byAccountIds: number[], hosts: string[]): Promise<{ host: string, accountId: number }[]> {- const rawQuery = `SELECT "server"."host", "serverBlocklist"."accountId" ` ++ static getBlockStatus (+ byAccountIds: number[],+ hosts: string[]+ ): Promise<{ host: string, accountId: number, blocklistSubscriptionName: string }[]> {+ const rawQuery =+ `SELECT "server"."host", "serverBlocklist"."accountId", "blocklistSubscription"."name" as "blocklistSubscriptionName" ` +`FROM "serverBlocklist" ` +`INNER JOIN "server" ON "server"."id" = "serverBlocklist"."targetServerId" ` ++ `LEFT JOIN "blocklistSubscription" ON "serverBlocklist"."blocklistSubscriptionId" = "blocklistSubscription"."id" ` +`WHERE "server"."host" IN (:hosts) ` +`AND "serverBlocklist"."accountId" IN (${createSafeIn(ServerBlocklistModel.sequelize, byAccountIds)})`@@ -156,11 +163,12 @@ export class ServerBlocklistModel extends SequelizeModel<ServerBlocklistModel> {count: numbersort: stringsearch?: string+ subscriptionName?: stringaccountId: number}) {- const { start, count, sort, search, accountId } = parameters+ const { start, count, sort, search, subscriptionName, accountId } = parameters- const query = {+ const baseQuery: FindOptions = {offset: start,limit: count,order: getSort(sort),@@ -171,9 +179,46 @@ export class ServerBlocklistModel extends SequelizeModel<ServerBlocklistModel> {}}+ const withSubscriptionFilter = subscriptionName+ ? {+ model: BlocklistSubscriptionModel,+ required: true,+ where: { name: subscriptionName }+ }+ : {+ model: BlocklistSubscriptionModel,+ required: false+ }+return Promise.all([- ServerBlocklistModel.scope(ScopeNames.WITH_SERVER).count(query),- ServerBlocklistModel.scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_SERVER ]).findAll<MServerBlocklistAccountServer>(query)+ ServerBlocklistModel.count({+ ...baseQuery,++ include: [+ {+ model: ServerModel,+ required: true+ },+ withSubscriptionFilter+ ]+ }),++ ServerBlocklistModel.findAll<MServerBlocklistAccountServer>({+ ...baseQuery,++ include: [+ {+ model: AccountModel,+ required: true+ },+ {+ model: ServerModel,+ required: true+ },++ withSubscriptionFilter+ ]+ })]).then(([ total, data ]) => ({ total, data }))}@@ -181,6 +226,9 @@ export class ServerBlocklistModel extends SequelizeModel<ServerBlocklistModel> {return {byAccount: this.ByAccount.toFormattedJSON(),blockedServer: this.BlockedServer.toFormattedJSON(),+ blocklistSubscription: this.BlocklistSubscription+ ? this.BlocklistSubscription.toFormattedSummaryJSON()+ : null,createdAt: this.createdAt}}diff --git a/server/core/models/server/server.ts b/server/core/models/server/server.tsindex fc2acf7e0b..9079aacb1f 100644--- a/server/core/models/server/server.ts+++ b/server/core/models/server/server.ts@@ -4,7 +4,7 @@ import { MServer, MServerFormattable } from '@server/types/models/server/index.jimport { 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 { ServerBlocklistModel } from '../blocklist/server-blocklist.js'import { AttributesOnly } from '@peertube/peertube-typescript-utils'export const serverSummaryAttributes = [ 'id', 'host' ] as const satisfies (keyof AttributesOnly<ServerModel>)[]diff --git a/server/core/models/user/user-notification-setting.ts b/server/core/models/user/user-notification-setting.tsindex 82879a308c..4691042a1b 100644--- a/server/core/models/user/user-notification-setting.ts+++ b/server/core/models/user/user-notification-setting.ts@@ -190,6 +190,15 @@ export class UserNotificationSettingModel extends SequelizeModel<UserNotificatio@Columndeclare myVideoTranscriptionGenerated: UserNotificationSettingValueType+ @AllowNull(false)+ @Default(null)+ @Is(+ 'UserNotificationSettingAutomaticBlocklist',+ value => throwIfNotValid(value, isUserNotificationSettingValid, 'automaticBlocklist')+ )+ @Column+ declare automaticBlocklist: UserNotificationSettingValueType+@ForeignKey(() => UserModel)@Columndeclare userId: number@@ -255,7 +264,8 @@ export class UserNotificationSettingModel extends SequelizeModel<UserNotificationewPeerTubeVersion: this.newPeerTubeVersion,myVideoStudioEditionFinished: this.myVideoStudioEditionFinished,myVideoTranscriptionGenerated: this.myVideoTranscriptionGenerated,- newPluginVersion: this.newPluginVersion+ newPluginVersion: this.newPluginVersion,+ automaticBlocklist: this.automaticBlocklist}}}diff --git a/server/core/models/video/sql/video/shared/video-model-builder.ts b/server/core/models/video/sql/video/shared/video-model-builder.tsindex 4837ca2d00..b73c9c6873 100644--- a/server/core/models/video/sql/video/shared/video-model-builder.ts+++ b/server/core/models/video/sql/video/shared/video-model-builder.ts@@ -1,12 +1,12 @@import { VideoInclude, VideoIncludeType } from '@peertube/peertube-models'-import { AccountBlocklistModel } from '@server/models/account/account-blocklist.js'+import { AccountBlocklistModel } from '@server/models/blocklist/account-blocklist.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 { AutomaticTagModel } from '@server/models/automatic-tag/automatic-tag.js'import { VideoAutomaticTagModel } from '@server/models/automatic-tag/video-automatic-tag.js'import { VideoRedundancyModel } from '@server/models/redundancy/video-redundancy.js'-import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'import { ServerModel } from '@server/models/server/server.js'import { TrackerModel } from '@server/models/server/tracker.js'import { UserVideoHistoryModel } from '@server/models/user/user-video-history.js'diff --git a/server/core/models/video/video-channel-sync.ts b/server/core/models/video/video-channel-sync.tsindex 4a8fafe53a..59f5ee3dcf 100644--- a/server/core/models/video/video-channel-sync.ts+++ b/server/core/models/video/video-channel-sync.ts@@ -1,7 +1,7 @@-import { VideoChannelSync, VideoChannelSyncState, type VideoChannelSyncStateType } from '@peertube/peertube-models'+import { VideoChannelSync, StreamSyncState, type StreamSyncStateType } from '@peertube/peertube-models'import { isUrlValid } from '@server/helpers/custom-validators/activitypub/misc.js'import { isVideoChannelSyncStateValid } from '@server/helpers/custom-validators/video-channel-syncs.js'-import { CONSTRAINTS_FIELDS, VIDEO_CHANNEL_SYNC_STATE } from '@server/initializers/constants.js'+import { CONSTRAINTS_FIELDS, STREAM_SYNC_STATE } from '@server/initializers/constants.js'import { MChannelSync, MChannelSyncChannel, MChannelSyncFormattable } from '@server/types/models/index.js'import { Op } from 'sequelize'import {@@ -47,10 +47,10 @@ export class VideoChannelSyncModel extends SequelizeModel<VideoChannelSyncModel>declare externalChannelUrl: string@AllowNull(false)- @Default(VideoChannelSyncState.WAITING_FIRST_RUN)+ @Default(StreamSyncState.WAITING_FIRST_RUN)@Is('VideoChannelSyncState', value => throwIfNotValid(value, isVideoChannelSyncStateValid, 'state'))@Column- declare state: VideoChannelSyncStateType+ declare state: StreamSyncStateType@AllowNull(true)@Column(DataType.DATE)@@ -147,7 +147,7 @@ export class VideoChannelSyncModel extends SequelizeModel<VideoChannelSyncModel>id: this.id,state: {id: this.state,- label: VIDEO_CHANNEL_SYNC_STATE[this.state]+ label: STREAM_SYNC_STATE[this.state]},externalChannelUrl: this.externalChannelUrl,createdAt: this.createdAt.toISOString(),diff --git a/server/core/types/express.d.ts b/server/core/types/express.d.tsindex 5c1d13c67a..02a4860f55 100644--- a/server/core/types/express.d.ts+++ b/server/core/types/express.d.ts@@ -35,7 +35,8 @@ import {MVideoThumbnails,MVideoWithBlacklist,MVideoWithRights,- MWatchedWordsList+ MWatchedWordsList,+ MBlocklistSubscription} from '@server/types/models/index.js'import { MOAuthToken, MOAuthTokenUser } from '@server/types/models/oauth/oauth-token.js'import { MPlugin, MServer, MServerBlocklist } from '@server/types/models/server.js'@@ -263,6 +264,8 @@ declare module 'express' {tokenSession?: MOAuthTokenchannelCollaborator?: MChannelCollaboratorAccount++ blocklistSubscription?: MBlocklistSubscription}}}diff --git a/server/core/types/models/account/account.ts b/server/core/types/models/account/account.tsindex 51b87eb203..839146b518 100644--- a/server/core/types/models/account/account.ts+++ b/server/core/types/models/account/account.ts@@ -16,7 +16,7 @@ import {MActorUsername} from '../actor/index.js'import { MChannelDefault } from '../video/video-channel.js'-import { MAccountBlocklistId } from './account-blocklist.js'+import { MAccountBlocklistId } from '../blocklist/account-blocklist.js'import { MChannelCollaboratorChannel } from '../video/video-channel-collaborator.js'type Use<K extends keyof AccountModel, M> = PickWith<AccountModel, K, M>diff --git a/server/core/types/models/account/index.ts b/server/core/types/models/account/index.tsindex e00026a6f4..631dd4d9fe 100644--- a/server/core/types/models/account/index.ts+++ b/server/core/types/models/account/index.ts@@ -1,3 +1,2 @@export * from './account.js'export * from './actor-custom-page.js'-export * from './account-blocklist.js'diff --git a/server/core/types/models/account/account-blocklist.ts b/server/core/types/models/blocklist/account-blocklist.tssimilarity index 71%rename from server/core/types/models/account/account-blocklist.tsrename to server/core/types/models/blocklist/account-blocklist.tsindex 27abe712ea..402f00ae09 100644--- a/server/core/types/models/account/account-blocklist.ts+++ b/server/core/types/models/blocklist/account-blocklist.ts@@ -1,12 +1,13 @@-import { AccountBlocklistModel } from '../../../models/account/account-blocklist.js'import { PickWith } from '@peertube/peertube-typescript-utils'-import { MAccountDefault, MAccountFormattable } from './account.js'+import { AccountBlocklistModel } from '../../../models/blocklist/account-blocklist.js'+import { MBlocklistSubscription } from './blocklist-subscription.js'+import { MAccountDefault, MAccountFormattable } from '../account/account.js'type Use<K extends keyof AccountBlocklistModel, M> = PickWith<AccountBlocklistModel, K, M>// ############################################################################-export type MAccountBlocklist = Omit<AccountBlocklistModel, 'ByAccount' | 'BlockedAccount'>+export type MAccountBlocklist = Omit<AccountBlocklistModel, 'ByAccount' | 'BlockedAccount' | 'BlocklistSubscription'>// ############################################################################@@ -25,3 +26,4 @@ export type MAccountBlocklistFormattable =& Pick<MAccountBlocklist, 'createdAt'>& Use<'ByAccount', MAccountFormattable>& Use<'BlockedAccount', MAccountFormattable>+ & Use<'BlocklistSubscription', MBlocklistSubscription>diff --git a/server/core/types/models/blocklist/blocklist-log.ts b/server/core/types/models/blocklist/blocklist-log.tsnew file mode 100644index 0000000000..f7575063f8--- /dev/null+++ b/server/core/types/models/blocklist/blocklist-log.ts@@ -0,0 +1,3 @@+import { BlocklistLogModel } from '@server/models/blocklist/blocklist-log.js'++export type MBlocklistLog = Omit<BlocklistLogModel, 'Account' | 'BlocklistSubscription'>diff --git a/server/core/types/models/blocklist/blocklist-subscription.ts b/server/core/types/models/blocklist/blocklist-subscription.tsnew file mode 100644index 0000000000..0fceafd8da--- /dev/null+++ b/server/core/types/models/blocklist/blocklist-subscription.ts@@ -0,0 +1,3 @@+import { BlocklistSubscriptionModel } from '@server/models/blocklist/blocklist-subscription.js'++export type MBlocklistSubscription = Omit<BlocklistSubscriptionModel, 'AccountBlocklists' | 'ServerBlocklists' | 'BlocklistLogs'>diff --git a/server/core/types/models/blocklist/index.ts b/server/core/types/models/blocklist/index.tsnew file mode 100644index 0000000000..d4466e1222--- /dev/null+++ b/server/core/types/models/blocklist/index.ts@@ -0,0 +1,4 @@+export * from './account-blocklist.js'+export * from './blocklist-log.js'+export * from './blocklist-subscription.js'+export * from './server-blocklist.js'diff --git a/server/core/types/models/server/server-blocklist.ts b/server/core/types/models/blocklist/server-blocklist.tssimilarity index 72%rename from server/core/types/models/server/server-blocklist.tsrename to server/core/types/models/blocklist/server-blocklist.tsindex e290c0c76b..c2f0f390d8 100644--- a/server/core/types/models/server/server-blocklist.ts+++ b/server/core/types/models/blocklist/server-blocklist.ts@@ -1,13 +1,14 @@-import { ServerBlocklistModel } from '@server/models/server/server-blocklist.js'import { PickWith } from '@peertube/peertube-typescript-utils'+import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.js'import { MAccountDefault, MAccountFormattable } from '../account/account.js'-import { MServer, MServerFormattable } from './server.js'+import { MBlocklistSubscription } from './blocklist-subscription.js'+import { MServer, MServerFormattable } from '../server/server.js'type Use<K extends keyof ServerBlocklistModel, M> = PickWith<ServerBlocklistModel, K, M>// ############################################################################-export type MServerBlocklist = Omit<ServerBlocklistModel, 'ByAccount' | 'BlockedServer'>+export type MServerBlocklist = Omit<ServerBlocklistModel, 'ByAccount' | 'BlockedServer' | 'BlocklistSubscriptions'>// ############################################################################@@ -24,3 +25,4 @@ export type MServerBlocklistFormattable =& Pick<MServerBlocklist, 'createdAt'>& Use<'ByAccount', MAccountFormattable>& Use<'BlockedServer', MServerFormattable>+ & Use<'BlocklistSubscription', MBlocklistSubscription>diff --git a/server/core/types/models/index.ts b/server/core/types/models/index.tsindex eccab5c81b..fd03eb162c 100644--- a/server/core/types/models/index.ts+++ b/server/core/types/models/index.ts@@ -3,6 +3,7 @@ export * from './account/index.js'export * from './actor/index.js'export * from './application/index.js'export * from './automatic-tag/index.js'+export * from './blocklist/index.js'export * from './oauth/index.js'export * from './server/index.js'export * from './user/index.js'diff --git a/server/core/types/models/server/index.ts b/server/core/types/models/server/index.tsindex ed5482b70a..ec0f9a621f 100644--- a/server/core/types/models/server/index.ts+++ b/server/core/types/models/server/index.ts@@ -1,3 +1,2 @@export * from './plugin.js'export * from './server.js'-export * from './server-blocklist.js'diff --git a/server/core/types/models/server/server.ts b/server/core/types/models/server/server.tsindex 744042dc07..07f93624a9 100644--- a/server/core/types/models/server/server.ts+++ b/server/core/types/models/server/server.ts@@ -1,6 +1,6 @@import { FunctionProperties, PickWith } from '@peertube/peertube-typescript-utils'import { ServerModel } from '../../../models/server/server.js'-import { MAccountBlocklistId } from '../account/index.js'+import { MAccountBlocklistId } from '../blocklist/account-blocklist.js'type Use<K extends keyof ServerModel, M> = PickWith<ServerModel, K, M>diff --git a/server/server.ts b/server/server.tsindex 274aab8340..2102d8bd00 100644--- a/server/server.ts+++ b/server/server.ts@@ -140,6 +140,7 @@ import { PluginManager } from './core/lib/plugins/plugin-manager.js'import { Redis } from './core/lib/redis.js'import { ActorFollowScheduler } from './core/lib/schedulers/actor-follow-scheduler.js'import { AutoFollowIndexInstances } from './core/lib/schedulers/auto-follow-index-instances.js'+import { BlocklistSubscriptionsScheduler } from './core/lib/schedulers/blocklist-subscriptions-scheduler.js'import { GeoIPUpdateScheduler } from './core/lib/schedulers/geo-ip-update-scheduler.js'import { PeerTubeVersionCheckScheduler } from './core/lib/schedulers/peertube-version-check-scheduler.js'import { PluginsCheckScheduler } from './core/lib/schedulers/plugins-check-scheduler.js'@@ -322,6 +323,7 @@ async function startApplication () {PluginsCheckScheduler.Instance.enable()PeerTubeVersionCheckScheduler.Instance.enable()AutoFollowIndexInstances.Instance.enable()+ BlocklistSubscriptionsScheduler.Instance.enable()RemoveDanglingResumableUploadsScheduler.Instance.enable()VideoChannelSyncLatestScheduler.Instance.enable()VideoStatsBufferScheduler.Instance.enable()diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yamlindex ef0b62d6e3..92bf03f759 100644--- a/support/doc/api/openapi.yaml+++ b/support/doc/api/openapi.yaml@@ -6845,6 +6845,12 @@ paths:- $ref: '#/components/parameters/start'- $ref: '#/components/parameters/count'- $ref: '#/components/parameters/sort'+ -+ name: subscriptionName+ in: query+ required: false+ schema:+ type: stringresponses:'200':description: successful operation@@ -6918,6 +6924,12 @@ paths:- $ref: '#/components/parameters/start'- $ref: '#/components/parameters/count'- $ref: '#/components/parameters/sort'+ -+ name: subscriptionName+ in: query+ required: false+ schema:+ type: stringresponses:'200':description: successful operation@@ -6980,6 +6992,104 @@ paths:'404':description: server block does not exist+ /api/v1/server/blocklist/subscriptions:+ get:+ tags:+ - Server Blocklist+ summary: List server blocklist subscriptions+ security:+ - OAuth2:+ - admin+ parameters:+ - $ref: '#/components/parameters/start'+ - $ref: '#/components/parameters/count'+ - $ref: '#/components/parameters/sort'+ - $ref: '#/components/parameters/search'+ responses:+ '200':+ description: successful operation+ content:+ application/json:+ schema:+ type: object+ properties:+ total:+ type: integer+ example: 1+ data:+ type: array+ items:+ $ref: '#/components/schemas/BlocklistSubscription'+ post:+ tags:+ - Server Blocklist+ summary: Add a server blocklist subscription+ security:+ - OAuth2:+ - admin+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ url:+ type: string+ format: url+ required:+ - url+ responses:+ '200':+ description: successful operation+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BlocklistSubscription'+ '409':+ description: subscription already exists++ '/api/v1/server/blocklist/subscriptions/{id}':+ delete:+ tags:+ - Server Blocklist+ summary: Delete a server blocklist subscription+ security:+ - OAuth2:+ - admin+ parameters:+ - name: id+ in: path+ required: true+ schema:+ type: integer+ responses:+ '204':+ description: successful operation+ '404':+ description: subscription does not exist++ /api/v1/server/blocklist/public-log:+ get:+ tags:+ - Server Blocklist+ summary: List publicly shared server blocklist log entries+ parameters:+ - name: startDate+ in: query+ required: true+ schema:+ type: string+ format: date-time+ responses:+ '200':+ description: successful operation+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AutoMuteList'+ '403':+ description: public log is disabled+/api/v1/server/redundancy/{host}:put:tags:@@ -9685,6 +9795,8 @@ components:properties:blockedByServer:type: boolean+ blockedByServerSubscription:+ type: stringblockedByUser:type: booleanhosts:@@ -9695,6 +9807,8 @@ components:properties:blockedByServer:type: boolean+ blockedByServerSubscription:+ type: stringblockedByUser:type: boolean@@ -10389,6 +10503,9 @@ components:blockedAccount:$ref: '#/components/schemas/Account'type: boolean+ blocklistSubscription:+ $ref: '#/components/schemas/BlocklistSubscriptionSummary'+ nullable: truecreatedAt:type: stringformat: date-time@@ -10402,9 +10519,78 @@ components:host:type: stringformat: hostname+ blocklistSubscription:+ $ref: '#/components/schemas/BlocklistSubscriptionSummary'+ nullable: truecreatedAt:type: stringformat: date-time+ BlocklistSubscription:+ properties:+ id:+ $ref: '#/components/schemas/id'+ name:+ type: string+ url:+ type: string+ format: url+ mutedAccountsCount:+ type: integer+ minimum: 0+ mutedServersCount:+ type: integer+ minimum: 0+ lastSyncAt:+ type: string+ format: date-time+ createdAt:+ type: string+ format: date-time+ updatedAt:+ type: string+ format: date-time+ BlocklistSubscriptionSummary:+ properties:+ id:+ $ref: '#/components/schemas/id'+ name:+ type: string+ url:+ type: string+ format: url+ BlocklistLog:+ properties:+ id:+ $ref: '#/components/schemas/id'+ action:+ type: string+ enum:+ - add+ - delete+ target:+ type: string+ createdAt:+ type: string+ format: date-time+ AutoMuteList:+ properties:+ name:+ type: string+ actions:+ type: array+ items:+ type: object+ properties:+ type:+ type: string+ enum:+ - block+ - unblock+ target:+ type: string+ createdAt:+ type: string+ format: date-timeCommentAutoTagPolicies:properties:review:@@ -11226,6 +11412,14 @@ components:properties:enabled:type: boolean+ blocklist:+ type: object+ properties:+ publicLog:+ type: object+ properties:+ enabled:+ type: booleanavatar:type: objectproperties:@@ -11736,6 +11930,14 @@ components:properties:enabled:type: boolean+ blocklist:+ type: object+ properties:+ publicLog:+ type: object+ properties:+ enabled:+ type: booleanfollowers:type: objectproperties:@@ -13031,6 +13233,8 @@ components:- 29- 30- 31+ - 32+ - 33description: >Notification type. One of the following values:@@ -13096,6 +13300,8 @@ components:- `31` CHANNEL_OWNERSHIP_CHANGED_REJECTED+ - `32` AUTOMATIC_BLOCKLIST_UPDATE+NewFeatureInfoType:type: integerenum: