From: Chocobozzz Date: Wed, 15 Nov 2017 09:10:41 +0000 (+0100) Subject: Add follow tabs X-Git-Tag: v0.0.1-alpha~219 X-Git-Url: https://git.librecmc.org/?a=commitdiff_plain;h=51548b31815c6f96f314ae96588a9adca150519d;p=oweals%2Fpeertube.git Add follow tabs Following Follow Followers --- diff --git a/client/src/app/+admin/admin-routing.module.ts b/client/src/app/+admin/admin-routing.module.ts index 88f44a811..cd8b9bdef 100644 --- a/client/src/app/+admin/admin-routing.module.ts +++ b/client/src/app/+admin/admin-routing.module.ts @@ -4,7 +4,7 @@ import { RouterModule, Routes } from '@angular/router' import { MetaGuard } from '@ngx-meta/core' import { AdminComponent } from './admin.component' -import { FriendsRoutes } from './friends' +import { FollowsRoutes } from './follows' import { UsersRoutes } from './users' import { VideoAbusesRoutes } from './video-abuses' import { VideoBlacklistRoutes } from './video-blacklist' @@ -21,7 +21,7 @@ const adminRoutes: Routes = [ redirectTo: 'users', pathMatch: 'full' }, - ...FriendsRoutes, + ...FollowsRoutes, ...UsersRoutes, ...VideoAbusesRoutes, ...VideoBlacklistRoutes diff --git a/client/src/app/+admin/admin.module.ts b/client/src/app/+admin/admin.module.ts index 32f6c42a6..3c6b7a793 100644 --- a/client/src/app/+admin/admin.module.ts +++ b/client/src/app/+admin/admin.module.ts @@ -1,25 +1,28 @@ import { NgModule } from '@angular/core' - -import { AdminComponent } from './admin.component' +import { TabsModule } from 'ngx-bootstrap/tabs' +import { SharedModule } from '../shared' import { AdminRoutingModule } from './admin-routing.module' -import { FriendsComponent, FriendAddComponent, FriendListComponent, FriendService } from './friends' -import { UsersComponent, UserAddComponent, UserUpdateComponent, UserListComponent, UserService } from './users' -import { VideoAbusesComponent, VideoAbuseListComponent } from './video-abuses' +import { AdminComponent } from './admin.component' +import { FollowersListComponent, FollowingAddComponent, FollowsComponent, FollowService } from './follows' +import { FollowingListComponent } from './follows/following-list/following-list.component' +import { UserAddComponent, UserListComponent, UsersComponent, UserService, UserUpdateComponent } from './users' +import { VideoAbuseListComponent, VideoAbusesComponent } from './video-abuses' import { VideoBlacklistComponent, VideoBlacklistListComponent } from './video-blacklist' -import { SharedModule } from '../shared' @NgModule({ imports: [ AdminRoutingModule, + TabsModule.forRoot(), SharedModule ], declarations: [ AdminComponent, - FriendsComponent, - FriendAddComponent, - FriendListComponent, + FollowsComponent, + FollowingAddComponent, + FollowersListComponent, + FollowingListComponent, UsersComponent, UserAddComponent, @@ -38,7 +41,7 @@ import { SharedModule } from '../shared' ], providers: [ - FriendService, + FollowService, UserService ] }) diff --git a/client/src/app/+admin/follows/followers-list/followers-list.component.html b/client/src/app/+admin/follows/followers-list/followers-list.component.html new file mode 100644 index 000000000..24d75d2b3 --- /dev/null +++ b/client/src/app/+admin/follows/followers-list/followers-list.component.html @@ -0,0 +1,16 @@ +
+
+

Followers list

+ + + + + + + + +
+
diff --git a/client/src/app/+admin/follows/followers-list/followers-list.component.scss b/client/src/app/+admin/follows/followers-list/followers-list.component.scss new file mode 100644 index 000000000..0a0f621c6 --- /dev/null +++ b/client/src/app/+admin/follows/followers-list/followers-list.component.scss @@ -0,0 +1,3 @@ +.btn { + margin-top: 10px; +} diff --git a/client/src/app/+admin/follows/followers-list/followers-list.component.ts b/client/src/app/+admin/follows/followers-list/followers-list.component.ts new file mode 100644 index 000000000..208a0c648 --- /dev/null +++ b/client/src/app/+admin/follows/followers-list/followers-list.component.ts @@ -0,0 +1,41 @@ +import { Component, OnInit } from '@angular/core' + +import { NotificationsService } from 'angular2-notifications' +import { SortMeta } from 'primeng/primeng' + +import { ConfirmService } from '../../../core' +import { RestTable, RestPagination } from '../../../shared' +import { Pod } from '../../../../../../shared' +import { FollowService } from '../shared' + +@Component({ + selector: 'my-followers-list', + templateUrl: './followers-list.component.html', + styleUrls: [ './followers-list.component.scss' ] +}) +export class FollowersListComponent extends RestTable { + followers: Pod[] = [] + totalRecords = 0 + rowsPerPage = 10 + sort: SortMeta = { field: 'createdAt', order: 1 } + pagination: RestPagination = { count: this.rowsPerPage, start: 0 } + + constructor ( + private notificationsService: NotificationsService, + private followService: FollowService + ) { + super() + } + + protected loadData () { + this.followService.getFollowers(this.pagination, this.sort) + .subscribe( + resultList => { + this.followers = resultList.data + this.totalRecords = resultList.total + }, + + err => this.notificationsService.error('Error', err.message) + ) + } +} diff --git a/client/src/app/+admin/follows/followers-list/index.ts b/client/src/app/+admin/follows/followers-list/index.ts new file mode 100644 index 000000000..15390cfbe --- /dev/null +++ b/client/src/app/+admin/follows/followers-list/index.ts @@ -0,0 +1 @@ +export * from './followers-list.component' diff --git a/client/src/app/+admin/follows/following-add/following-add.component.html b/client/src/app/+admin/follows/following-add/following-add.component.html new file mode 100644 index 000000000..111f6a8de --- /dev/null +++ b/client/src/app/+admin/follows/following-add/following-add.component.html @@ -0,0 +1,35 @@ +
+
+ +

Add following

+ +
{{ error }}
+ +
+
+ + +
+ + + + + +
+ +
+ It should be a valid host. +
+
+ +
+ It seems that you are not on a HTTPS pod. Your webserver need to have TLS activated in order to follow servers. +
+ + +
+
+
diff --git a/client/src/app/+admin/follows/following-add/following-add.component.scss b/client/src/app/+admin/follows/following-add/following-add.component.scss new file mode 100644 index 000000000..5fde51636 --- /dev/null +++ b/client/src/app/+admin/follows/following-add/following-add.component.scss @@ -0,0 +1,7 @@ +table { + margin-bottom: 40px; +} + +.input-group-btn button { + width: 35px; +} diff --git a/client/src/app/+admin/follows/following-add/following-add.component.ts b/client/src/app/+admin/follows/following-add/following-add.component.ts new file mode 100644 index 000000000..d95d6afa9 --- /dev/null +++ b/client/src/app/+admin/follows/following-add/following-add.component.ts @@ -0,0 +1,121 @@ +import { Component, OnInit } from '@angular/core' +import { FormControl, FormGroup } from '@angular/forms' +import { Router } from '@angular/router' + +import { NotificationsService } from 'angular2-notifications' + +import { ConfirmService } from '../../../core' +import { validateHost } from '../../../shared' +import { FollowService } from '../shared' + +@Component({ + selector: 'my-following-add', + templateUrl: './following-add.component.html', + styleUrls: [ './following-add.component.scss' ] +}) +export class FollowingAddComponent implements OnInit { + form: FormGroup + hosts: string[] = [ ] + error: string = null + + constructor ( + private router: Router, + private notificationsService: NotificationsService, + private confirmService: ConfirmService, + private followService: FollowService + ) {} + + ngOnInit () { + this.form = new FormGroup({}) + this.addField() + } + + addField () { + this.form.addControl(`host-${this.hosts.length}`, new FormControl('', [ validateHost ])) + this.hosts.push('') + } + + canMakeFriends () { + return window.location.protocol === 'https:' + } + + customTrackBy (index: number, obj: any): any { + return index + } + + displayAddField (index: number) { + return index === (this.hosts.length - 1) + } + + displayRemoveField (index: number) { + return (index !== 0 || this.hosts.length > 1) && index !== (this.hosts.length - 1) + } + + isFormValid () { + // Do not check the last input + for (let i = 0; i < this.hosts.length - 1; i++) { + if (!this.form.controls[`host-${i}`].valid) return false + } + + const lastIndex = this.hosts.length - 1 + // If the last input (which is not the first) is empty, it's ok + if (this.hosts[lastIndex] === '' && lastIndex !== 0) { + return true + } else { + return this.form.controls[`host-${lastIndex}`].valid + } + } + + removeField (index: number) { + // Remove the last control + this.form.removeControl(`host-${this.hosts.length - 1}`) + this.hosts.splice(index, 1) + } + + addFollowing () { + this.error = '' + + const notEmptyHosts = this.getNotEmptyHosts() + if (notEmptyHosts.length === 0) { + this.error = 'You need to specify at least 1 host.' + return + } + + if (!this.isHostsUnique(notEmptyHosts)) { + this.error = 'Hosts need to be unique.' + return + } + + const confirmMessage = 'Are you sure to make friends with:
- ' + notEmptyHosts.join('
- ') + this.confirmService.confirm(confirmMessage, 'Follow new server(s)').subscribe( + res => { + if (res === false) return + + this.followService.follow(notEmptyHosts).subscribe( + status => { + this.notificationsService.success('Success', 'Follow request(s) sent!') + // Wait requests between pods + setTimeout(() => this.router.navigate([ '/admin/friends/list' ]), 1000) + }, + + err => this.notificationsService.error('Error', err.message) + ) + } + ) + } + + private getNotEmptyHosts () { + const notEmptyHosts = [] + + Object.keys(this.form.value).forEach((hostKey) => { + const host = this.form.value[hostKey] + if (host !== '') notEmptyHosts.push(host) + }) + + return notEmptyHosts + } + + private isHostsUnique (hosts: string[]) { + return hosts.every(host => hosts.indexOf(host) === hosts.lastIndexOf(host)) + } +} diff --git a/client/src/app/+admin/follows/following-add/index.ts b/client/src/app/+admin/follows/following-add/index.ts new file mode 100644 index 000000000..1b1897ffa --- /dev/null +++ b/client/src/app/+admin/follows/following-add/index.ts @@ -0,0 +1 @@ +export * from './following-add.component' diff --git a/client/src/app/+admin/follows/following-list/following-list.component.html b/client/src/app/+admin/follows/following-list/following-list.component.html new file mode 100644 index 000000000..fbcebfaa7 --- /dev/null +++ b/client/src/app/+admin/follows/following-list/following-list.component.html @@ -0,0 +1,16 @@ +
+
+

Following list

+ + + + + + + + +
+
diff --git a/client/src/app/+admin/follows/following-list/following-list.component.ts b/client/src/app/+admin/follows/following-list/following-list.component.ts new file mode 100644 index 000000000..7d2c5084b --- /dev/null +++ b/client/src/app/+admin/follows/following-list/following-list.component.ts @@ -0,0 +1,40 @@ +import { Component, OnInit } from '@angular/core' + +import { NotificationsService } from 'angular2-notifications' +import { SortMeta } from 'primeng/primeng' + +import { ConfirmService } from '../../../core' +import { RestTable, RestPagination } from '../../../shared' +import { Pod } from '../../../../../../shared' +import { FollowService } from '../shared' + +@Component({ + selector: 'my-followers-list', + templateUrl: './following-list.component.html' +}) +export class FollowingListComponent extends RestTable { + following: Pod[] = [] + totalRecords = 0 + rowsPerPage = 10 + sort: SortMeta = { field: 'createdAt', order: 1 } + pagination: RestPagination = { count: this.rowsPerPage, start: 0 } + + constructor ( + private notificationsService: NotificationsService, + private followService: FollowService + ) { + super() + } + + protected loadData () { + this.followService.getFollowing(this.pagination, this.sort) + .subscribe( + resultList => { + this.following = resultList.data + this.totalRecords = resultList.total + }, + + err => this.notificationsService.error('Error', err.message) + ) + } +} diff --git a/client/src/app/+admin/follows/following-list/index.ts b/client/src/app/+admin/follows/following-list/index.ts new file mode 100644 index 000000000..a70d46a7e --- /dev/null +++ b/client/src/app/+admin/follows/following-list/index.ts @@ -0,0 +1 @@ +export * from './following-list.component' diff --git a/client/src/app/+admin/follows/follows.component.html b/client/src/app/+admin/follows/follows.component.html new file mode 100644 index 000000000..b67bc9736 --- /dev/null +++ b/client/src/app/+admin/follows/follows.component.html @@ -0,0 +1,11 @@ +
+ + + + {{ link.title }} + + + +
+ + diff --git a/client/src/app/+admin/follows/follows.component.scss b/client/src/app/+admin/follows/follows.component.scss new file mode 100644 index 000000000..d8ab41975 --- /dev/null +++ b/client/src/app/+admin/follows/follows.component.scss @@ -0,0 +1,21 @@ +.follows-menu { + margin-top: 20px; +} + +tabset /deep/ { + .nav-link { + padding: 0; + } + + .tab-link { + display: block; + text-align: center; + height: 40px; + width: 120px; + line-height: 40px; + + &:hover, &:active, &:focus { + text-decoration: none !important; + } + } +} diff --git a/client/src/app/+admin/follows/follows.component.ts b/client/src/app/+admin/follows/follows.component.ts new file mode 100644 index 000000000..97422a41b --- /dev/null +++ b/client/src/app/+admin/follows/follows.component.ts @@ -0,0 +1,43 @@ +import { AfterViewInit, Component, ViewChild } from '@angular/core' +import { TabsetComponent } from 'ngx-bootstrap/tabs' + +@Component({ + templateUrl: './follows.component.html', + styleUrls: [ './follows.component.scss' ] +}) +export class FollowsComponent implements AfterViewInit { + @ViewChild('followsMenuTabs') followsMenuTabs: TabsetComponent + + links = [ + { + path: 'following-list', + title: 'Following' + }, + { + path: 'following-add', + title: 'Follow' + }, + { + path: 'followers-list', + title: 'Followers' + } + ] + + ngAfterViewInit () { + // Avoid issue with change detector + setTimeout(() => this.updateActiveTab()) + } + + private updateActiveTab () { + const url = window.location.pathname + + for (let i = 0; i < this.links.length; i++) { + const path = this.links[i].path + + if (url.endsWith(path) === true) { + this.followsMenuTabs.tabs[i].active = true + return + } + } + } +} diff --git a/client/src/app/+admin/follows/follows.routes.ts b/client/src/app/+admin/follows/follows.routes.ts new file mode 100644 index 000000000..b7d44f75b --- /dev/null +++ b/client/src/app/+admin/follows/follows.routes.ts @@ -0,0 +1,53 @@ +import { Routes } from '@angular/router' + +import { UserRightGuard } from '../../core' +import { FollowsComponent } from './follows.component' +import { FollowingAddComponent } from './following-add' +import { FollowersListComponent } from './followers-list' +import { UserRight } from '../../../../../shared' +import { FollowingListComponent } from './following-list/following-list.component' + +export const FollowsRoutes: Routes = [ + { + path: 'follows', + component: FollowsComponent, + canActivate: [ UserRightGuard ], + data: { + userRight: UserRight.MANAGE_APPLICATION_FOLLOW + }, + children: [ + { + path: '', + redirectTo: 'following-list', + pathMatch: 'full' + }, + { + path: 'following-list', + component: FollowingListComponent, + data: { + meta: { + title: 'Following list' + } + } + }, + { + path: 'followers-list', + component: FollowersListComponent, + data: { + meta: { + title: 'Followers list' + } + } + }, + { + path: 'following-add', + component: FollowingAddComponent, + data: { + meta: { + title: 'Add follow' + } + } + } + ] + } +] diff --git a/client/src/app/+admin/follows/index.ts b/client/src/app/+admin/follows/index.ts new file mode 100644 index 000000000..7849a06e7 --- /dev/null +++ b/client/src/app/+admin/follows/index.ts @@ -0,0 +1,6 @@ +export * from './following-add' +export * from './followers-list' +export * from './following-list' +export * from './shared' +export * from './follows.component' +export * from './follows.routes' diff --git a/client/src/app/+admin/follows/shared/follow.service.ts b/client/src/app/+admin/follows/shared/follow.service.ts new file mode 100644 index 000000000..622c33cea --- /dev/null +++ b/client/src/app/+admin/follows/shared/follow.service.ts @@ -0,0 +1,49 @@ +import { Injectable } from '@angular/core' +import { HttpClient, HttpParams } from '@angular/common/http' +import { Observable } from 'rxjs/Observable' +import 'rxjs/add/operator/catch' +import 'rxjs/add/operator/map' + +import { SortMeta } from 'primeng/primeng' + +import { RestExtractor, RestPagination, RestService } from '../../../shared' +import { Pod, ResultList } from '../../../../../../shared' + +@Injectable() +export class FollowService { + private static BASE_APPLICATION_URL = API_URL + '/api/v1/application' + + constructor ( + private authHttp: HttpClient, + private restService: RestService, + private restExtractor: RestExtractor + ) {} + + getFollowing (pagination: RestPagination, sort: SortMeta): Observable> { + let params = new HttpParams() + params = this.restService.addRestGetParams(params, pagination, sort) + + return this.authHttp.get>(FollowService.BASE_APPLICATION_URL + '/following', { params }) + .map(res => this.restExtractor.convertResultListDateToHuman(res)) + .catch(res => this.restExtractor.handleError(res)) + } + + getFollowers (pagination: RestPagination, sort: SortMeta): Observable> { + let params = new HttpParams() + params = this.restService.addRestGetParams(params, pagination, sort) + + return this.authHttp.get>(FollowService.BASE_APPLICATION_URL + '/followers', { params }) + .map(res => this.restExtractor.convertResultListDateToHuman(res)) + .catch(res => this.restExtractor.handleError(res)) + } + + follow (notEmptyHosts: String[]) { + const body = { + hosts: notEmptyHosts + } + + return this.authHttp.post(FollowService.BASE_APPLICATION_URL + '/follow', body) + .map(this.restExtractor.extractDataBool) + .catch(res => this.restExtractor.handleError(res)) + } +} diff --git a/client/src/app/+admin/follows/shared/index.ts b/client/src/app/+admin/follows/shared/index.ts new file mode 100644 index 000000000..78d456def --- /dev/null +++ b/client/src/app/+admin/follows/shared/index.ts @@ -0,0 +1 @@ +export * from './follow.service' diff --git a/client/src/app/+admin/friends/friend-add/friend-add.component.html b/client/src/app/+admin/friends/friend-add/friend-add.component.html deleted file mode 100644 index 81d8291cd..000000000 --- a/client/src/app/+admin/friends/friend-add/friend-add.component.html +++ /dev/null @@ -1,35 +0,0 @@ -
-
- -

Make friends

- -
{{ error }}
- -
-
- - -
- - - - - -
- -
- It should be a valid host. -
-
- -
- It seems that you are not on a HTTPS pod. Your webserver need to have TLS activated in order to make friends. -
- - -
-
-
diff --git a/client/src/app/+admin/friends/friend-add/friend-add.component.scss b/client/src/app/+admin/friends/friend-add/friend-add.component.scss deleted file mode 100644 index 5fde51636..000000000 --- a/client/src/app/+admin/friends/friend-add/friend-add.component.scss +++ /dev/null @@ -1,7 +0,0 @@ -table { - margin-bottom: 40px; -} - -.input-group-btn button { - width: 35px; -} diff --git a/client/src/app/+admin/friends/friend-add/friend-add.component.ts b/client/src/app/+admin/friends/friend-add/friend-add.component.ts deleted file mode 100644 index 29ed23e0c..000000000 --- a/client/src/app/+admin/friends/friend-add/friend-add.component.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { Component, OnInit } from '@angular/core' -import { FormControl, FormGroup } from '@angular/forms' -import { Router } from '@angular/router' - -import { NotificationsService } from 'angular2-notifications' - -import { ConfirmService } from '../../../core' -import { validateHost } from '../../../shared' -import { FriendService } from '../shared' - -@Component({ - selector: 'my-friend-add', - templateUrl: './friend-add.component.html', - styleUrls: [ './friend-add.component.scss' ] -}) -export class FriendAddComponent implements OnInit { - form: FormGroup - hosts: string[] = [ ] - error: string = null - - constructor ( - private router: Router, - private notificationsService: NotificationsService, - private confirmService: ConfirmService, - private friendService: FriendService - ) {} - - ngOnInit () { - this.form = new FormGroup({}) - this.addField() - } - - addField () { - this.form.addControl(`host-${this.hosts.length}`, new FormControl('', [ validateHost ])) - this.hosts.push('') - } - - canMakeFriends () { - return window.location.protocol === 'https:' - } - - customTrackBy (index: number, obj: any): any { - return index - } - - displayAddField (index: number) { - return index === (this.hosts.length - 1) - } - - displayRemoveField (index: number) { - return (index !== 0 || this.hosts.length > 1) && index !== (this.hosts.length - 1) - } - - isFormValid () { - // Do not check the last input - for (let i = 0; i < this.hosts.length - 1; i++) { - if (!this.form.controls[`host-${i}`].valid) return false - } - - const lastIndex = this.hosts.length - 1 - // If the last input (which is not the first) is empty, it's ok - if (this.hosts[lastIndex] === '' && lastIndex !== 0) { - return true - } else { - return this.form.controls[`host-${lastIndex}`].valid - } - } - - removeField (index: number) { - // Remove the last control - this.form.removeControl(`host-${this.hosts.length - 1}`) - this.hosts.splice(index, 1) - } - - makeFriends () { - this.error = '' - - const notEmptyHosts = this.getNotEmptyHosts() - if (notEmptyHosts.length === 0) { - this.error = 'You need to specify at least 1 host.' - return - } - - if (!this.isHostsUnique(notEmptyHosts)) { - this.error = 'Hosts need to be unique.' - return - } - - const confirmMessage = 'Are you sure to make friends with:
- ' + notEmptyHosts.join('
- ') - this.confirmService.confirm(confirmMessage, 'Make friends').subscribe( - res => { - if (res === false) return - - this.friendService.follow(notEmptyHosts).subscribe( - status => { - this.notificationsService.success('Success', 'Make friends request sent!') - // Wait requests between pods - setTimeout(() => this.router.navigate([ '/admin/friends/list' ]), 1000) - }, - - err => this.notificationsService.error('Error', err.message) - ) - } - ) - } - - private getNotEmptyHosts () { - const notEmptyHosts = [] - - Object.keys(this.form.value).forEach((hostKey) => { - const host = this.form.value[hostKey] - if (host !== '') notEmptyHosts.push(host) - }) - - return notEmptyHosts - } - - private isHostsUnique (hosts: string[]) { - return hosts.every(host => hosts.indexOf(host) === hosts.lastIndexOf(host)) - } -} diff --git a/client/src/app/+admin/friends/friend-add/index.ts b/client/src/app/+admin/friends/friend-add/index.ts deleted file mode 100644 index 978ab3d46..000000000 --- a/client/src/app/+admin/friends/friend-add/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './friend-add.component' diff --git a/client/src/app/+admin/friends/friend-list/friend-list.component.html b/client/src/app/+admin/friends/friend-list/friend-list.component.html deleted file mode 100644 index df5a570fd..000000000 --- a/client/src/app/+admin/friends/friend-list/friend-list.component.html +++ /dev/null @@ -1,29 +0,0 @@ -
-
-

Friends list

- - - - - - - - - - - - - - - - Quit friends - - - - Make friends - -
-
diff --git a/client/src/app/+admin/friends/friend-list/friend-list.component.scss b/client/src/app/+admin/friends/friend-list/friend-list.component.scss deleted file mode 100644 index 0a0f621c6..000000000 --- a/client/src/app/+admin/friends/friend-list/friend-list.component.scss +++ /dev/null @@ -1,3 +0,0 @@ -.btn { - margin-top: 10px; -} diff --git a/client/src/app/+admin/friends/friend-list/friend-list.component.ts b/client/src/app/+admin/friends/friend-list/friend-list.component.ts deleted file mode 100644 index 3fa8ef19f..000000000 --- a/client/src/app/+admin/friends/friend-list/friend-list.component.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Component, OnInit } from '@angular/core' - -import { NotificationsService } from 'angular2-notifications' -import { SortMeta } from 'primeng/primeng' - -import { ConfirmService } from '../../../core' -import { RestTable, RestPagination } from '../../../shared' -import { Pod } from '../../../../../../shared' -import { FriendService } from '../shared' - -@Component({ - selector: 'my-friend-list', - templateUrl: './friend-list.component.html', - styleUrls: ['./friend-list.component.scss'] -}) -export class FriendListComponent extends RestTable implements OnInit { - friends: Pod[] = [] - totalRecords = 0 - rowsPerPage = 10 - sort: SortMeta = { field: 'createdAt', order: 1 } - pagination: RestPagination = { count: this.rowsPerPage, start: 0 } - - constructor ( - private notificationsService: NotificationsService, - private confirmService: ConfirmService, - private friendService: FriendService - ) { - super() - } - - ngOnInit () { - this.loadData() - } - - hasFriends () { - return this.friends.length !== 0 - } - - quitFriends () { - const confirmMessage = 'Do you really want to quit your friends? All their videos will be deleted.' - this.confirmService.confirm(confirmMessage, 'Quit friends').subscribe( - res => { - if (res === false) return - - this.friendService.quitFriends().subscribe( - status => { - this.notificationsService.success('Success', 'Friends left!') - this.loadData() - }, - - err => this.notificationsService.error('Error', err.message) - ) - } - ) - } - - removeFriend (friend: Pod) { - const confirmMessage = 'Do you really want to remove this friend ? All its videos will be deleted.' - - this.confirmService.confirm(confirmMessage, 'Remove').subscribe( - res => { - if (res === false) return - - this.friendService.removeFriend(friend).subscribe( - status => { - this.notificationsService.success('Success', 'Friend removed') - this.loadData() - }, - - err => this.notificationsService.error('Error', err.message) - ) - } - ) - } - - protected loadData () { - this.friendService.getFollowing(this.pagination, this.sort) - .subscribe( - resultList => { - this.friends = resultList.data - this.totalRecords = resultList.total - }, - - err => this.notificationsService.error('Error', err.message) - ) - } -} diff --git a/client/src/app/+admin/friends/friend-list/index.ts b/client/src/app/+admin/friends/friend-list/index.ts deleted file mode 100644 index c9cbd2800..000000000 --- a/client/src/app/+admin/friends/friend-list/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './friend-list.component' diff --git a/client/src/app/+admin/friends/friends.component.ts b/client/src/app/+admin/friends/friends.component.ts deleted file mode 100644 index 5ef0aaa03..000000000 --- a/client/src/app/+admin/friends/friends.component.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Component } from '@angular/core' - -@Component({ - template: '' -}) -export class FriendsComponent { -} diff --git a/client/src/app/+admin/friends/friends.routes.ts b/client/src/app/+admin/friends/friends.routes.ts deleted file mode 100644 index e2cb953b3..000000000 --- a/client/src/app/+admin/friends/friends.routes.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Routes } from '@angular/router' - -import { UserRightGuard } from '../../core' -import { FriendsComponent } from './friends.component' -import { FriendAddComponent } from './friend-add' -import { FriendListComponent } from './friend-list' -import { UserRight } from '../../../../../shared' - -export const FriendsRoutes: Routes = [ - { - path: 'friends', - component: FriendsComponent, - canActivate: [ UserRightGuard ], - data: { - userRight: UserRight.MANAGE_PEERTUBE_FOLLOW - }, - children: [ - { - path: '', - redirectTo: 'list', - pathMatch: 'full' - }, - { - path: 'list', - component: FriendListComponent, - data: { - meta: { - title: 'Friends list' - } - } - }, - { - path: 'add', - component: FriendAddComponent, - data: { - meta: { - title: 'Add friends' - } - } - } - ] - } -] diff --git a/client/src/app/+admin/friends/index.ts b/client/src/app/+admin/friends/index.ts deleted file mode 100644 index 356dee8e9..000000000 --- a/client/src/app/+admin/friends/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './friend-add' -export * from './friend-list' -export * from './shared' -export * from './friends.component' -export * from './friends.routes' diff --git a/client/src/app/+admin/friends/shared/friend.service.ts b/client/src/app/+admin/friends/shared/friend.service.ts deleted file mode 100644 index 867656a53..000000000 --- a/client/src/app/+admin/friends/shared/friend.service.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { Injectable } from '@angular/core' -import { HttpClient, HttpParams } from '@angular/common/http' -import { Observable } from 'rxjs/Observable' -import 'rxjs/add/operator/catch' -import 'rxjs/add/operator/map' - -import { SortMeta } from 'primeng/primeng' - -import { RestExtractor, RestPagination, RestService } from '../../../shared' -import { Pod, ResultList } from '../../../../../../shared' - -@Injectable() -export class FriendService { - private static BASE_FRIEND_URL = API_URL + '/api/v1/pods/' - - constructor ( - private authHttp: HttpClient, - private restService: RestService, - private restExtractor: RestExtractor - ) {} - - getFollowing (pagination: RestPagination, sort: SortMeta): Observable> { - let params = new HttpParams() - params = this.restService.addRestGetParams(params, pagination, sort) - - return this.authHttp.get>(API_URL + '/api/v1/pods/followers', { params }) - .map(res => this.restExtractor.convertResultListDateToHuman(res)) - .catch(res => this.restExtractor.handleError(res)) - } - - follow (notEmptyHosts: String[]) { - const body = { - hosts: notEmptyHosts - } - - return this.authHttp.post(API_URL + '/api/v1/pods/follow', body) - .map(this.restExtractor.extractDataBool) - .catch(res => this.restExtractor.handleError(res)) - } - - quitFriends () { - return this.authHttp.get(FriendService.BASE_FRIEND_URL + 'quit-friends') - .map(this.restExtractor.extractDataBool) - .catch(res => this.restExtractor.handleError(res)) - } - - removeFriend (friend: Pod) { - return this.authHttp.delete(FriendService.BASE_FRIEND_URL + friend.id) - .map(this.restExtractor.extractDataBool) - .catch(res => this.restExtractor.handleError(res)) - } -} diff --git a/client/src/app/+admin/friends/shared/index.ts b/client/src/app/+admin/friends/shared/index.ts deleted file mode 100644 index 65ab9fb46..000000000 --- a/client/src/app/+admin/friends/shared/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './friend.service' diff --git a/client/src/app/core/menu/menu-admin.component.html b/client/src/app/core/menu/menu-admin.component.html index 1966a944c..99ee287c5 100644 --- a/client/src/app/core/menu/menu-admin.component.html +++ b/client/src/app/core/menu/menu-admin.component.html @@ -5,9 +5,9 @@ List users - + - List friends + Manage follows diff --git a/client/src/app/core/menu/menu-admin.component.ts b/client/src/app/core/menu/menu-admin.component.ts index 92aab9a05..88a654d1f 100644 --- a/client/src/app/core/menu/menu-admin.component.ts +++ b/client/src/app/core/menu/menu-admin.component.ts @@ -15,8 +15,8 @@ export class MenuAdminComponent { return this.auth.getUser().hasRight(UserRight.MANAGE_USERS) } - hasFriendsRight () { - return this.auth.getUser().hasRight(UserRight.MANAGE_PEERTUBE_FOLLOW) + hasApplicationFollowRight () { + return this.auth.getUser().hasRight(UserRight.MANAGE_APPLICATION_FOLLOW) } hasVideoAbusesRight () { diff --git a/client/src/app/core/menu/menu.component.ts b/client/src/app/core/menu/menu.component.ts index 71295be86..872d29819 100644 --- a/client/src/app/core/menu/menu.component.ts +++ b/client/src/app/core/menu/menu.component.ts @@ -16,7 +16,7 @@ export class MenuComponent implements OnInit { private routesPerRight = { [UserRight.MANAGE_USERS]: '/admin/users', - [UserRight.MANAGE_PEERTUBE_FOLLOW]: '/admin/friends', + [UserRight.MANAGE_APPLICATION_FOLLOW]: '/admin/friends', [UserRight.MANAGE_VIDEO_ABUSES]: '/admin/video-abuses', [UserRight.MANAGE_VIDEO_BLACKLIST]: '/admin/video-blacklist' } @@ -58,7 +58,7 @@ export class MenuComponent implements OnInit { const adminRights = [ UserRight.MANAGE_USERS, - UserRight.MANAGE_PEERTUBE_FOLLOW, + UserRight.MANAGE_APPLICATION_FOLLOW, UserRight.MANAGE_VIDEO_ABUSES, UserRight.MANAGE_VIDEO_BLACKLIST ] diff --git a/scripts/update-host.ts b/scripts/update-host.ts index 7c46dc52b..05f0ef96d 100755 --- a/scripts/update-host.ts +++ b/scripts/update-host.ts @@ -3,7 +3,7 @@ import { database as db } from '../server/initializers/database' db.init(true) .then(() => { - // FIXME: check if has followers + // FIXME: check if has following // return hasFriends() return true }) diff --git a/server/controllers/activitypub/client.ts b/server/controllers/activitypub/client.ts index 56a4054fa..49dd24e79 100644 --- a/server/controllers/activitypub/client.ts +++ b/server/controllers/activitypub/client.ts @@ -46,7 +46,7 @@ async function accountFollowersController (req: express.Request, res: express.Re const page = req.params.page || 1 const { start, count } = pageToStartAndCount(page, ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE) - const result = await db.Account.listAcceptedFollowerUrlsForApi(account.id, start, count) + const result = await db.AccountFollow.listAcceptedFollowerUrlsForApi(account.id, start, count) const activityPubResult = activityPubCollectionPagination(req.url, page, result) return res.json(activityPubResult) @@ -58,7 +58,7 @@ async function accountFollowingController (req: express.Request, res: express.Re const page = req.params.page || 1 const { start, count } = pageToStartAndCount(page, ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE) - const result = await db.Account.listAcceptedFollowingUrlsForApi(account.id, start, count) + const result = await db.AccountFollow.listAcceptedFollowingUrlsForApi(account.id, start, count) const activityPubResult = activityPubCollectionPagination(req.url, page, result) return res.json(activityPubResult) diff --git a/server/controllers/activitypub/index.ts b/server/controllers/activitypub/index.ts index 0c8574ef7..c5bec6448 100644 --- a/server/controllers/activitypub/index.ts +++ b/server/controllers/activitypub/index.ts @@ -1,14 +1,11 @@ import * as express from 'express' - -import { badRequest } from '../../helpers' -import { inboxRouter } from './inbox' import { activityPubClientRouter } from './client' +import { inboxRouter } from './inbox' const activityPubRouter = express.Router() activityPubRouter.use('/', inboxRouter) activityPubRouter.use('/', activityPubClientRouter) -activityPubRouter.use('/*', badRequest) // --------------------------------------------------------------------------- diff --git a/server/controllers/api/application/follows.ts b/server/controllers/api/application/follows.ts new file mode 100644 index 000000000..000bbd23e --- /dev/null +++ b/server/controllers/api/application/follows.ts @@ -0,0 +1,127 @@ +import * as express from 'express' +import { UserRight } from '../../../../shared/models/users/user-right.enum' +import { getFormattedObjects } from '../../../helpers' +import { logger } from '../../../helpers/logger' +import { getApplicationAccount } from '../../../helpers/utils' +import { getAccountFromWebfinger } from '../../../helpers/webfinger' +import { SERVER_ACCOUNT_NAME } from '../../../initializers/constants' +import { database as db } from '../../../initializers/database' +import { sendFollow } from '../../../lib/activitypub/send-request' +import { asyncMiddleware, paginationValidator, setFollowersSort, setPagination } from '../../../middlewares' +import { authenticate } from '../../../middlewares/oauth' +import { setBodyHostsPort } from '../../../middlewares/pods' +import { setFollowingSort } from '../../../middlewares/sort' +import { ensureUserHasRight } from '../../../middlewares/user-right' +import { followValidator } from '../../../middlewares/validators/pods' +import { followersSortValidator, followingSortValidator } from '../../../middlewares/validators/sort' + +const applicationFollowsRouter = express.Router() + +applicationFollowsRouter.get('/following', + paginationValidator, + followingSortValidator, + setFollowingSort, + setPagination, + asyncMiddleware(listFollowing) +) + +applicationFollowsRouter.post('/follow', + authenticate, + ensureUserHasRight(UserRight.MANAGE_APPLICATION_FOLLOW), + followValidator, + setBodyHostsPort, + asyncMiddleware(follow) +) + +applicationFollowsRouter.get('/followers', + paginationValidator, + followersSortValidator, + setFollowersSort, + setPagination, + asyncMiddleware(listFollowers) +) + +// --------------------------------------------------------------------------- + +export { + applicationFollowsRouter +} + +// --------------------------------------------------------------------------- + +async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) { + const applicationAccount = await getApplicationAccount() + const resultList = await db.AccountFollow.listFollowingForApi(applicationAccount.id, req.query.start, req.query.count, req.query.sort) + + return res.json(getFormattedObjects(resultList.data, resultList.total)) +} + +async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) { + const applicationAccount = await getApplicationAccount() + const resultList = await db.AccountFollow.listFollowersForApi(applicationAccount.id, req.query.start, req.query.count, req.query.sort) + + return res.json(getFormattedObjects(resultList.data, resultList.total)) +} + +async function follow (req: express.Request, res: express.Response, next: express.NextFunction) { + const hosts = req.body.hosts as string[] + const fromAccount = await getApplicationAccount() + + const tasks: Promise[] = [] + const accountName = SERVER_ACCOUNT_NAME + + for (const host of hosts) { + + // We process each host in a specific transaction + // First, we add the follow request in the database + // Then we send the follow request to other account + const p = loadLocalOrGetAccountFromWebfinger(accountName, host) + .then(accountResult => { + let targetAccount = accountResult.account + + return db.sequelize.transaction(async t => { + if (accountResult.loadedFromDB === false) { + targetAccount = await targetAccount.save({ transaction: t }) + } + + const [ accountFollow ] = await db.AccountFollow.findOrCreate({ + where: { + accountId: fromAccount.id, + targetAccountId: targetAccount.id + }, + defaults: { + state: 'pending', + accountId: fromAccount.id, + targetAccountId: targetAccount.id + }, + transaction: t + }) + + // Send a notification to remote server + if (accountFollow.state === 'pending') { + await sendFollow(fromAccount, targetAccount, t) + } + }) + }) + .catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err)) + + tasks.push(p) + } + + await Promise.all(tasks) + + return res.status(204).end() +} + +async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) { + let loadedFromDB = true + let account = await db.Account.loadByNameAndHost(name, host) + + if (!account) { + const nameWithDomain = name + '@' + host + account = await getAccountFromWebfinger(nameWithDomain) + loadedFromDB = false + } + + return { account, loadedFromDB } +} diff --git a/server/controllers/api/application/index.ts b/server/controllers/api/application/index.ts new file mode 100644 index 000000000..011b971ed --- /dev/null +++ b/server/controllers/api/application/index.ts @@ -0,0 +1,12 @@ +import * as express from 'express' +import { applicationFollowsRouter } from './follows' + +const applicationRouter = express.Router() + +applicationRouter.use('/', applicationFollowsRouter) + +// --------------------------------------------------------------------------- + +export { + applicationRouter +} diff --git a/server/controllers/api/index.ts b/server/controllers/api/index.ts index 2e949d531..a22c78cce 100644 --- a/server/controllers/api/index.ts +++ b/server/controllers/api/index.ts @@ -4,15 +4,15 @@ import { badRequest } from '../../helpers' import { oauthClientsRouter } from './oauth-clients' import { configRouter } from './config' -import { podsRouter } from './pods' +import { applicationRouter } from './application' import { usersRouter } from './users' import { videosRouter } from './videos' const apiRouter = express.Router() +apiRouter.use('/application', applicationRouter) apiRouter.use('/oauth-clients', oauthClientsRouter) apiRouter.use('/config', configRouter) -apiRouter.use('/pods', podsRouter) apiRouter.use('/users', usersRouter) apiRouter.use('/videos', videosRouter) apiRouter.use('/ping', pong) diff --git a/server/controllers/api/pods.ts b/server/controllers/api/pods.ts deleted file mode 100644 index 0bd6971bb..000000000 --- a/server/controllers/api/pods.ts +++ /dev/null @@ -1,127 +0,0 @@ -import * as express from 'express' -import { UserRight } from '../../../shared/models/users/user-right.enum' -import { getFormattedObjects } from '../../helpers' -import { logger } from '../../helpers/logger' -import { getApplicationAccount } from '../../helpers/utils' -import { getAccountFromWebfinger } from '../../helpers/webfinger' -import { SERVER_ACCOUNT_NAME } from '../../initializers/constants' -import { database as db } from '../../initializers/database' -import { sendFollow } from '../../lib/activitypub/send-request' -import { asyncMiddleware, paginationValidator, setFollowersSort, setPagination } from '../../middlewares' -import { authenticate } from '../../middlewares/oauth' -import { setBodyHostsPort } from '../../middlewares/pods' -import { setFollowingSort } from '../../middlewares/sort' -import { ensureUserHasRight } from '../../middlewares/user-right' -import { followValidator } from '../../middlewares/validators/pods' -import { followersSortValidator, followingSortValidator } from '../../middlewares/validators/sort' - -const podsRouter = express.Router() - -podsRouter.get('/following', - paginationValidator, - followingSortValidator, - setFollowingSort, - setPagination, - asyncMiddleware(listFollowing) -) - -podsRouter.post('/follow', - authenticate, - ensureUserHasRight(UserRight.MANAGE_PEERTUBE_FOLLOW), - followValidator, - setBodyHostsPort, - asyncMiddleware(follow) -) - -podsRouter.get('/followers', - paginationValidator, - followersSortValidator, - setFollowersSort, - setPagination, - asyncMiddleware(listFollowers) -) - -// --------------------------------------------------------------------------- - -export { - podsRouter -} - -// --------------------------------------------------------------------------- - -async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) { - const applicationAccount = await getApplicationAccount() - const resultList = await db.Account.listFollowingForApi(applicationAccount.id, req.query.start, req.query.count, req.query.sort) - - return res.json(getFormattedObjects(resultList.data, resultList.total)) -} - -async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) { - const applicationAccount = await getApplicationAccount() - const resultList = await db.Account.listFollowersForApi(applicationAccount.id, req.query.start, req.query.count, req.query.sort) - - return res.json(getFormattedObjects(resultList.data, resultList.total)) -} - -async function follow (req: express.Request, res: express.Response, next: express.NextFunction) { - const hosts = req.body.hosts as string[] - const fromAccount = await getApplicationAccount() - - const tasks: Promise[] = [] - const accountName = SERVER_ACCOUNT_NAME - - for (const host of hosts) { - - // We process each host in a specific transaction - // First, we add the follow request in the database - // Then we send the follow request to other account - const p = loadLocalOrGetAccountFromWebfinger(accountName, host) - .then(accountResult => { - let targetAccount = accountResult.account - - return db.sequelize.transaction(async t => { - if (accountResult.loadedFromDB === false) { - targetAccount = await targetAccount.save({ transaction: t }) - } - - const [ accountFollow ] = await db.AccountFollow.findOrCreate({ - where: { - accountId: fromAccount.id, - targetAccountId: targetAccount.id - }, - defaults: { - state: 'pending', - accountId: fromAccount.id, - targetAccountId: targetAccount.id - }, - transaction: t - }) - - // Send a notification to remote server - if (accountFollow.state === 'pending') { - await sendFollow(fromAccount, targetAccount, t) - } - }) - }) - .catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err)) - - tasks.push(p) - } - - await Promise.all(tasks) - - return res.status(204).end() -} - -async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) { - let loadedFromDB = true - let account = await db.Account.loadByNameAndHost(name, host) - - if (!account) { - const nameWithDomain = name + '@' + host - account = await getAccountFromWebfinger(nameWithDomain) - loadedFromDB = false - } - - return { account, loadedFromDB } -} diff --git a/server/controllers/webfinger.ts b/server/controllers/webfinger.ts index 1c726f0cb..102ac0937 100644 --- a/server/controllers/webfinger.ts +++ b/server/controllers/webfinger.ts @@ -8,7 +8,7 @@ import { AccountInstance } from '../models/account/account-interface' const webfingerRouter = express.Router() -webfingerRouter.use('/.well-known/webfinger', +webfingerRouter.get('/.well-known/webfinger', webfingerValidator, webfingerController ) diff --git a/server/lib/activitypub/send-request.ts b/server/lib/activitypub/send-request.ts index d47040d6d..f942a2eba 100644 --- a/server/lib/activitypub/send-request.ts +++ b/server/lib/activitypub/send-request.ts @@ -85,7 +85,7 @@ export { // --------------------------------------------------------------------------- async function broadcastToFollowers (data: any, fromAccount: AccountInstance, t: Sequelize.Transaction) { - const result = await db.Account.listAcceptedFollowerUrlsForApi(fromAccount.id, 0) + const result = await db.AccountFollow.listAcceptedFollowerUrlsForApi(fromAccount.id, 0) const jobPayload = { uris: result.data, diff --git a/server/models/account/account-follow-interface.ts b/server/models/account/account-follow-interface.ts index efdff915e..413dad190 100644 --- a/server/models/account/account-follow-interface.ts +++ b/server/models/account/account-follow-interface.ts @@ -1,13 +1,26 @@ import * as Sequelize from 'sequelize' import * as Bluebird from 'bluebird' import { FollowState } from '../../../shared/models/accounts/follow.model' +import { ResultList } from '../../../shared/models/result-list.model' +import { AccountInstance } from './account-interface' export namespace AccountFollowMethods { export type LoadByAccountAndTarget = (accountId: number, targetAccountId: number) => Bluebird + + export type ListFollowingForApi = (id: number, start: number, count: number, sort: string) => Bluebird< ResultList > + export type ListFollowersForApi = (id: number, start: number, count: number, sort: string) => Bluebird< ResultList > + + export type ListAcceptedFollowerUrlsForApi = (id: number, start: number, count?: number) => Promise< ResultList > + export type ListAcceptedFollowingUrlsForApi = (id: number, start: number, count?: number) => Promise< ResultList > } export interface AccountFollowClass { loadByAccountAndTarget: AccountFollowMethods.LoadByAccountAndTarget + listFollowersForApi: AccountFollowMethods.ListFollowersForApi + listFollowingForApi: AccountFollowMethods.ListFollowingForApi + + listAcceptedFollowerUrlsForApi: AccountFollowMethods.ListAcceptedFollowerUrlsForApi + listAcceptedFollowingUrlsForApi: AccountFollowMethods.ListAcceptedFollowingUrlsForApi } export interface AccountFollowAttributes { @@ -20,6 +33,9 @@ export interface AccountFollowInstance extends AccountFollowClass, AccountFollow id: number createdAt: Date updatedAt: Date + + AccountFollower?: AccountInstance + AccountFollowing?: AccountInstance } export interface AccountFollowModel extends AccountFollowClass, Sequelize.Model {} diff --git a/server/models/account/account-follow.ts b/server/models/account/account-follow.ts index 7c129ab9d..6d7592326 100644 --- a/server/models/account/account-follow.ts +++ b/server/models/account/account-follow.ts @@ -1,12 +1,16 @@ import { values } from 'lodash' import * as Sequelize from 'sequelize' -import { addMethodsToModel } from '../utils' +import { addMethodsToModel, getSort } from '../utils' import { AccountFollowAttributes, AccountFollowInstance, AccountFollowMethods } from './account-follow-interface' import { FOLLOW_STATES } from '../../initializers/constants' let AccountFollow: Sequelize.Model let loadByAccountAndTarget: AccountFollowMethods.LoadByAccountAndTarget +let listFollowingForApi: AccountFollowMethods.ListFollowingForApi +let listFollowersForApi: AccountFollowMethods.ListFollowersForApi +let listAcceptedFollowerUrlsForApi: AccountFollowMethods.ListAcceptedFollowerUrlsForApi +let listAcceptedFollowingUrlsForApi: AccountFollowMethods.ListAcceptedFollowingUrlsForApi export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) { AccountFollow = sequelize.define('AccountFollow', @@ -34,7 +38,11 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da const classMethods = [ associate, - loadByAccountAndTarget + loadByAccountAndTarget, + listFollowingForApi, + listFollowersForApi, + listAcceptedFollowerUrlsForApi, + listAcceptedFollowingUrlsForApi ] addMethodsToModel(AccountFollow, classMethods) @@ -49,7 +57,7 @@ function associate (models) { name: 'accountId', allowNull: false }, - as: 'accountFollowers', + as: 'AccountFollower', onDelete: 'CASCADE' }) @@ -58,7 +66,7 @@ function associate (models) { name: 'targetAccountId', allowNull: false }, - as: 'accountFollowing', + as: 'AccountFollowing', onDelete: 'CASCADE' }) } @@ -73,3 +81,117 @@ loadByAccountAndTarget = function (accountId: number, targetAccountId: number) { return AccountFollow.findOne(query) } + +listFollowingForApi = function (id: number, start: number, count: number, sort: string) { + const query = { + distinct: true, + offset: start, + limit: count, + order: [ getSort(sort) ], + include: [ + { + model: AccountFollow[ 'sequelize' ].models.Account, + required: true, + as: 'AccountFollower', + where: { + id + } + }, + { + model: AccountFollow['sequelize'].models.Account, + as: 'AccountFollowing', + required: true, + include: [ AccountFollow['sequelize'].models.Pod ] + } + ] + } + + return AccountFollow.findAndCountAll(query).then(({ rows, count }) => { + return { + data: rows.map(r => r.AccountFollowing), + total: count + } + }) +} + +listFollowersForApi = function (id: number, start: number, count: number, sort: string) { + const query = { + distinct: true, + offset: start, + limit: count, + order: [ getSort(sort) ], + include: [ + { + model: AccountFollow[ 'sequelize' ].models.Account, + required: true, + as: 'AccountFollower', + include: [ AccountFollow['sequelize'].models.Pod ] + }, + { + model: AccountFollow['sequelize'].models.Account, + as: 'AccountFollowing', + required: true, + where: { + id + } + } + ] + } + + return AccountFollow.findAndCountAll(query).then(({ rows, count }) => { + return { + data: rows.map(r => r.AccountFollower), + total: count + } + }) +} + +listAcceptedFollowerUrlsForApi = function (id: number, start: number, count?: number) { + return createListAcceptedFollowForApiQuery('followers', id, start, count) +} + +listAcceptedFollowingUrlsForApi = function (id: number, start: number, count?: number) { + return createListAcceptedFollowForApiQuery('following', id, start, count) +} + +// ------------------------------ UTILS ------------------------------ + +async function createListAcceptedFollowForApiQuery (type: 'followers' | 'following', id: number, start: number, count?: number) { + let firstJoin: string + let secondJoin: string + + if (type === 'followers') { + firstJoin = 'targetAccountId' + secondJoin = 'accountId' + } else { + firstJoin = 'accountId' + secondJoin = 'targetAccountId' + } + + const selections = [ '"Followers"."url" AS "url"', 'COUNT(*) AS "total"' ] + const tasks: Promise[] = [] + + for (const selection of selections) { + let query = 'SELECT ' + selection + ' FROM "Account" ' + + 'INNER JOIN "AccountFollow" ON "AccountFollow"."' + firstJoin + '" = "Account"."id" ' + + 'INNER JOIN "Account" AS "Follows" ON "Followers"."id" = "Follows"."' + secondJoin + '" ' + + 'WHERE "Account"."id" = $id AND "AccountFollow"."state" = \'accepted\' ' + + 'LIMIT ' + start + + if (count !== undefined) query += ', ' + count + + const options = { + bind: { id }, + type: Sequelize.QueryTypes.SELECT + } + tasks.push(AccountFollow['sequelize'].query(query, options)) + } + + const [ followers, [ { total } ]] = await Promise.all(tasks) + const urls: string[] = followers.map(f => f.url) + + return { + data: urls, + total: parseInt(total, 10) + } +} diff --git a/server/models/account/account-interface.ts b/server/models/account/account-interface.ts index 6fc36ae9d..ce1afec02 100644 --- a/server/models/account/account-interface.ts +++ b/server/models/account/account-interface.ts @@ -15,10 +15,6 @@ export namespace AccountMethods { export type LoadLocalByName = (name: string) => Bluebird export type LoadByNameAndHost = (name: string, host: string) => Bluebird export type ListOwned = () => Bluebird - export type ListAcceptedFollowerUrlsForApi = (id: number, start: number, count?: number) => Promise< ResultList > - export type ListAcceptedFollowingUrlsForApi = (id: number, start: number, count?: number) => Promise< ResultList > - export type ListFollowingForApi = (id: number, start: number, count: number, sort: string) => Bluebird< ResultList > - export type ListFollowersForApi = (id: number, start: number, count: number, sort: string) => Bluebird< ResultList > export type ToActivityPubObject = (this: AccountInstance) => ActivityPubActor export type ToFormattedJSON = (this: AccountInstance) => FormattedAccount @@ -38,10 +34,6 @@ export interface AccountClass { loadLocalByName: AccountMethods.LoadLocalByName loadByNameAndHost: AccountMethods.LoadByNameAndHost listOwned: AccountMethods.ListOwned - listAcceptedFollowerUrlsForApi: AccountMethods.ListAcceptedFollowerUrlsForApi - listAcceptedFollowingUrlsForApi: AccountMethods.ListAcceptedFollowingUrlsForApi - listFollowingForApi: AccountMethods.ListFollowingForApi - listFollowersForApi: AccountMethods.ListFollowersForApi } export interface AccountAttributes { diff --git a/server/models/account/account.ts b/server/models/account/account.ts index d2293a939..e90eaae5e 100644 --- a/server/models/account/account.ts +++ b/server/models/account/account.ts @@ -23,7 +23,7 @@ import { AccountMethods } from './account-interface' import { sendDeleteAccount } from '../../lib/activitypub/send-request' -import { CONSTRAINTS_FIELDS } from '../../initializers/constants' +import { CONFIG, CONSTRAINTS_FIELDS } from '../../initializers/constants' let Account: Sequelize.Model let loadAccountByPodAndUUID: AccountMethods.LoadAccountByPodAndUUID @@ -34,10 +34,6 @@ let loadByUrl: AccountMethods.LoadByUrl let loadLocalByName: AccountMethods.LoadLocalByName let loadByNameAndHost: AccountMethods.LoadByNameAndHost let listOwned: AccountMethods.ListOwned -let listAcceptedFollowerUrlsForApi: AccountMethods.ListAcceptedFollowerUrlsForApi -let listAcceptedFollowingUrlsForApi: AccountMethods.ListAcceptedFollowingUrlsForApi -let listFollowingForApi: AccountMethods.ListFollowingForApi -let listFollowersForApi: AccountMethods.ListFollowersForApi let isOwned: AccountMethods.IsOwned let toActivityPubObject: AccountMethods.ToActivityPubObject let toFormattedJSON: AccountMethods.ToFormattedJSON @@ -185,7 +181,7 @@ export default function defineAccount (sequelize: Sequelize.Sequelize, DataTypes unique: true }, { - fields: [ 'name', 'podId' ], + fields: [ 'name', 'podId', 'applicationId' ], unique: true } ], @@ -202,11 +198,7 @@ export default function defineAccount (sequelize: Sequelize.Sequelize, DataTypes loadByUrl, loadLocalByName, loadByNameAndHost, - listOwned, - listAcceptedFollowerUrlsForApi, - listAcceptedFollowingUrlsForApi, - listFollowingForApi, - listFollowersForApi + listOwned ] const instanceMethods = [ isOwned, @@ -286,9 +278,11 @@ function afterDestroy (account: AccountInstance) { } toFormattedJSON = function (this: AccountInstance) { + let host = this.Pod ? this.Pod.host : CONFIG.WEBSERVER.HOST + const json = { id: this.id, - host: this.Pod.host, + host, name: this.name } @@ -346,7 +340,7 @@ getFollowerSharedInboxUrls = function (this: AccountInstance) { } getFollowingUrl = function (this: AccountInstance) { - return this.url + '/followers' + return this.url + '/following' } getFollowersUrl = function (this: AccountInstance) { @@ -369,76 +363,6 @@ listOwned = function () { return Account.findAll(query) } -listAcceptedFollowerUrlsForApi = function (id: number, start: number, count?: number) { - return createListAcceptedFollowForApiQuery('followers', id, start, count) -} - -listAcceptedFollowingUrlsForApi = function (id: number, start: number, count?: number) { - return createListAcceptedFollowForApiQuery('following', id, start, count) -} - -listFollowingForApi = function (id: number, start: number, count: number, sort: string) { - const query = { - distinct: true, - offset: start, - limit: count, - order: [ getSort(sort) ], - include: [ - { - model: Account['sequelize'].models.AccountFollow, - required: true, - as: 'following', - include: [ - { - model: Account['sequelize'].models.Account, - as: 'accountFollowing', - required: true, - include: [ Account['sequelize'].models.Pod ] - } - ] - } - ] - } - - return Account.findAndCountAll(query).then(({ rows, count }) => { - return { - data: rows, - total: count - } - }) -} - -listFollowersForApi = function (id: number, start: number, count: number, sort: string) { - const query = { - distinct: true, - offset: start, - limit: count, - order: [ getSort(sort) ], - include: [ - { - model: Account['sequelize'].models.AccountFollow, - required: true, - as: 'followers', - include: [ - { - model: Account['sequelize'].models.Account, - as: 'accountFollowers', - required: true, - include: [ Account['sequelize'].models.Pod ] - } - ] - } - ] - } - - return Account.findAndCountAll(query).then(({ rows, count }) => { - return { - data: rows, - total: count - } - }) -} - loadApplication = function () { return Account.findOne({ include: [ @@ -527,45 +451,3 @@ loadAccountByPodAndUUID = function (uuid: string, podId: number, transaction: Se return Account.find(query) } - -// ------------------------------ UTILS ------------------------------ - -async function createListAcceptedFollowForApiQuery (type: 'followers' | 'following', id: number, start: number, count?: number) { - let firstJoin: string - let secondJoin: string - - if (type === 'followers') { - firstJoin = 'targetAccountId' - secondJoin = 'accountId' - } else { - firstJoin = 'accountId' - secondJoin = 'targetAccountId' - } - - const selections = [ '"Followers"."url" AS "url"', 'COUNT(*) AS "total"' ] - const tasks: Promise[] = [] - - for (const selection of selections) { - let query = 'SELECT ' + selection + ' FROM "Account" ' + - 'INNER JOIN "AccountFollow" ON "AccountFollow"."' + firstJoin + '" = "Account"."id" ' + - 'INNER JOIN "Account" AS "Follows" ON "Followers"."id" = "Follows"."' + secondJoin + '" ' + - 'WHERE "Account"."id" = $id AND "AccountFollow"."state" = \'accepted\' ' + - 'LIMIT ' + start - - if (count !== undefined) query += ', ' + count - - const options = { - bind: { id }, - type: Sequelize.QueryTypes.SELECT - } - tasks.push(Account['sequelize'].query(query, options)) - } - - const [ followers, [ { total } ]] = await Promise.all(tasks) - const urls: string[] = followers.map(f => f.url) - - return { - data: urls, - total: parseInt(total, 10) - } -} diff --git a/shared/models/users/user-right.enum.ts b/shared/models/users/user-right.enum.ts index 9d5ebbb16..ecad69d6f 100644 --- a/shared/models/users/user-right.enum.ts +++ b/shared/models/users/user-right.enum.ts @@ -1,9 +1,9 @@ export enum UserRight { ALL, MANAGE_USERS, - MANAGE_PEERTUBE_FOLLOW, + MANAGE_APPLICATION_FOLLOW, MANAGE_VIDEO_ABUSES, MANAGE_VIDEO_BLACKLIST, REMOVE_ANY_VIDEO, - REMOVE_ANY_VIDEO_CHANNEL, + REMOVE_ANY_VIDEO_CHANNEL }