1
0
Fork 0

Make subscribe buttons observe subscription statuses to synchronise

This commit is contained in:
Rigel Kent 2020-01-08 22:13:47 +01:00 committed by Chocobozzz
parent b061c8edb0
commit 9270ccf6dc
8 changed files with 152 additions and 87 deletions

View file

@ -9,11 +9,7 @@
<img [src]="videoChannel.avatarUrl" alt="Avatar" /> <img [src]="videoChannel.avatarUrl" alt="Avatar" />
<div>{{ videoChannel.displayName }}</div> <div>{{ videoChannel.displayName }}</div>
<div class="followers">{{ videoChannel.followersCount }} <div class="followers" i18n>{videoChannel.followersCount, plural, =1 {1 subscriber} other {{{ videoChannel.followersCount }} subscribers}}</div>
<ng-container *ngIf="videoChannel.followersCount === 1; then single; else multiple"></ng-container>
<ng-template i18n #single>subscriber</ng-template>
<ng-template i18n #multiple>subscribers</ng-template>
</div>
</a> </a>
<my-subscribe-button [videoChannels]="[videoChannel]"></my-subscribe-button> <my-subscribe-button [videoChannels]="[videoChannel]"></my-subscribe-button>

View file

@ -28,12 +28,7 @@
> >
</my-user-moderation-dropdown> </my-user-moderation-dropdown>
</div> </div>
<div class="actor-followers"> <div class="actor-followers" i18n>{account.followersCount, plural, =1 {1 subscriber} other {{{ account.followersCount }} subscribers}}</div>
{{ account.followersCount }}
<ng-container *ngIf="account.followersCount === 1; then single; else multiple"></ng-container>
<ng-template i18n #single>subscriber</ng-template>
<ng-template i18n #multiple>subscribers</ng-template>
</div>
</div> </div>
<my-subscribe-button *ngIf="videoChannels" [account]="account" [videoChannels]="videoChannels"></my-subscribe-button> <my-subscribe-button *ngIf="videoChannels" [account]="account" [videoChannels]="videoChannels"></my-subscribe-button>

View file

@ -40,15 +40,15 @@ export class AccountsComponent implements OnInit, OnDestroy {
map(params => params[ 'accountId' ]), map(params => params[ 'accountId' ]),
distinctUntilChanged(), distinctUntilChanged(),
switchMap(accountId => this.accountService.getAccount(accountId)), switchMap(accountId => this.accountService.getAccount(accountId)),
tap(account => this.getUserIfNeeded(account)), tap(account => {
this.account = account
this.getUserIfNeeded(account)
}),
switchMap(account => this.videoChannelService.listAccountVideoChannels(account)),
catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ])) catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ]))
) )
.subscribe( .subscribe(
account => { videoChannels => this.videoChannels = videoChannels.data,
this.account = account
this.videoChannelService.listAccountVideoChannels(account)
.subscribe(videoChannels => this.videoChannels = videoChannels.data)
},
err => this.notifier.error(err.message) err => this.notifier.error(err.message)
) )

View file

@ -1,13 +1,13 @@
<div class="btn-group-subscribe btn-group" <div class="btn-group-subscribe btn-group"
[ngClass]="{'subscribe-button': !isAllChannelsSubscribed(), 'unsubscribe-button': isAllChannelsSubscribed()}"> [ngClass]="{'subscribe-button': !isAllChannelsSubscribed(), 'unsubscribe-button': isAllChannelsSubscribed(), 'big': isBigButton() }">
<ng-template #userLoggedOut> <ng-template #userLoggedOut>
<span [ngClass]="{ 'extra-text': subscribeStatus(true).length > 0 }"> <span [ngClass]="{ 'extra-text': isAtLeastOneChannelSubscribed() }">
<ng-container *ngIf="account; then multiple; else single"></ng-container> <ng-container *ngIf="account; then multiple; else single"></ng-container>
<ng-template i18n #single>Subscribe</ng-template> <ng-template i18n #single>Subscribe</ng-template>
<ng-template #multiple> <ng-template #multiple>
<span i18n>Subscribe to all channels</span> <span i18n>Subscribe to all channels</span>
<span *ngIf="subscribeStatus(true).length > 0">{{subscribeStatus(true).length}}/{{subscribed.size}} <span *ngIf="isAtLeastOneChannelSubscribed()">{{subscribeStatus(true).length}}/{{subscribed.size}}
<ng-container i18n>channels subscribed</ng-container> <ng-container i18n>channels subscribed</ng-container>
</span> </span>
</ng-template> </ng-template>
@ -27,13 +27,8 @@
<button <button
*ngIf="isAllChannelsSubscribed()" type="button" *ngIf="isAllChannelsSubscribed()" type="button"
class="btn btn-sm" role="button" class="btn btn-sm" role="button"
(click)="unsubscribe()" i18n (click)="unsubscribe()">
> <ng-container i18n>{account + "", select, undefined {Unsubscribe} other {Unsubscribe from all channels}}</ng-container>
<span>
<ng-container *ngIf="account; then multiple; else single"></ng-container>
<ng-template i18n #single>Unsubscribe</ng-template>
<ng-template i18n #multiple>Unsubscribe from all channels</ng-template>
</span>
</button> </button>
</ng-template> </ng-template>

View file

@ -13,6 +13,20 @@
font-size: 15px; font-size: 15px;
} }
&.big {
height: 35px;
button .extra-text {
span:first-child {
line-height: 80%;
}
span:not(:first-child) {
font-size: 75%;
}
}
}
// Unlogged // Unlogged
& > .dropdown > .dropdown-toggle span { & > .dropdown > .dropdown-toggle span {
padding-right: 3px; padding-right: 3px;
@ -80,5 +94,6 @@
span:not(:first-child) { span:not(:first-child) {
font-size: 60%; font-size: 60%;
text-align: left;
} }
} }

View file

@ -7,7 +7,7 @@ import { I18n } from '@ngx-translate/i18n-polyfill'
import { VideoService } from '@app/shared/video/video.service' import { VideoService } from '@app/shared/video/video.service'
import { FeedFormat } from '../../../../../shared/models/feeds' import { FeedFormat } from '../../../../../shared/models/feeds'
import { Account } from '@app/shared/account/account.model' import { Account } from '@app/shared/account/account.model'
import { forkJoin } from 'rxjs' import { forkJoin, merge } from 'rxjs'
@Component({ @Component({
selector: 'my-subscribe-button', selector: 'my-subscribe-button',
@ -26,7 +26,7 @@ export class SubscribeButtonComponent implements OnInit {
@Input() displayFollowers = false @Input() displayFollowers = false
@Input() size: 'small' | 'normal' = 'normal' @Input() size: 'small' | 'normal' = 'normal'
subscribed: Map<string, boolean> subscribed = new Map<string, boolean>()
constructor ( constructor (
private authService: AuthService, private authService: AuthService,
@ -35,9 +35,7 @@ export class SubscribeButtonComponent implements OnInit {
private userSubscriptionService: UserSubscriptionService, private userSubscriptionService: UserSubscriptionService,
private i18n: I18n, private i18n: I18n,
private videoService: VideoService private videoService: VideoService
) { ) { }
this.subscribed = new Map<string, boolean>()
}
get handle () { get handle () {
return this.account return this.account
@ -68,19 +66,7 @@ export class SubscribeButtonComponent implements OnInit {
} }
ngOnInit () { ngOnInit () {
if (this.isUserLoggedIn()) { this.loadSubscribedStatus()
forkJoin(this.videoChannels.map(videoChannel => {
const handle = this.getChannelHandler(videoChannel)
this.subscribed.set(handle, false)
this.userSubscriptionService.doesSubscriptionExist(handle)
.subscribe(
res => this.subscribed.set(handle, res[handle]),
err => this.notifier.error(err.message)
)
}))
}
} }
subscribe () { subscribe () {
@ -92,31 +78,22 @@ export class SubscribeButtonComponent implements OnInit {
} }
localSubscribe () { localSubscribe () {
const observableBatch: any = [] const observableBatch = this.videoChannels
.map(videoChannel => this.getChannelHandler(videoChannel))
this.videoChannels .filter(handle => this.subscribeStatus(false).includes(handle))
.filter(videoChannel => this.subscribeStatus(false).includes(this.getChannelHandler(videoChannel))) .map(handle => this.userSubscriptionService.addSubscription(handle))
.forEach(videoChannel => observableBatch.push(
this.userSubscriptionService.addSubscription(this.getChannelHandler(videoChannel))
))
forkJoin(observableBatch) forkJoin(observableBatch)
.subscribe( .subscribe(
() => { () => {
[...this.subscribed.keys()].forEach((key) => {
this.subscribed.set(key, true)
})
this.notifier.success( this.notifier.success(
this.account this.account
? this.i18n( ? this.i18n(
'Subscribed to all current channels of {{nameWithHost}}. ' + 'Subscribed to all current channels of {{nameWithHost}}. You will be notified of all their new videos.',
'You will be notified of all their new videos.',
{ nameWithHost: this.account.displayName } { nameWithHost: this.account.displayName }
) )
: this.i18n( : this.i18n(
'Subscribed to {{nameWithHost}}. ' + 'Subscribed to {{nameWithHost}}. You will be notified of all their new videos.',
'You will be notified of all their new videos.',
{ nameWithHost: this.videoChannels[0].displayName } { nameWithHost: this.videoChannels[0].displayName }
) )
, ,
@ -135,21 +112,14 @@ export class SubscribeButtonComponent implements OnInit {
} }
localUnsubscribe () { localUnsubscribe () {
const observableBatch: any = [] const observableBatch = this.videoChannels
.map(videoChannel => this.getChannelHandler(videoChannel))
this.videoChannels .filter(handle => this.subscribeStatus(true).includes(handle))
.filter(videoChannel => this.subscribeStatus(true).includes(this.getChannelHandler(videoChannel))) .map(handle => this.userSubscriptionService.deleteSubscription(handle))
.forEach(videoChannel => observableBatch.push(
this.userSubscriptionService.deleteSubscription(this.getChannelHandler(videoChannel))
))
forkJoin(observableBatch) forkJoin(observableBatch)
.subscribe( .subscribe(
() => { () => {
[...this.subscribed.keys()].forEach((key) => {
this.subscribed.set(key, false)
})
this.notifier.success( this.notifier.success(
this.account this.account
? this.i18n('Unsubscribed from all channels of {{nameWithHost}}', { nameWithHost: this.account.nameWithHost }) ? this.i18n('Unsubscribed from all channels of {{nameWithHost}}', { nameWithHost: this.account.nameWithHost })
@ -171,6 +141,14 @@ export class SubscribeButtonComponent implements OnInit {
return !Array.from(this.subscribed.values()).includes(false) return !Array.from(this.subscribed.values()).includes(false)
} }
isAtLeastOneChannelSubscribed () {
return this.subscribeStatus(true).length > 0
}
isBigButton () {
return this.videoChannels.length > 1 && this.isAtLeastOneChannelSubscribed()
}
gotoLogin () { gotoLogin () {
this.router.navigate([ '/login' ]) this.router.navigate([ '/login' ])
} }
@ -180,10 +158,28 @@ export class SubscribeButtonComponent implements OnInit {
} }
private subscribeStatus (subscribed: boolean) { private subscribeStatus (subscribed: boolean) {
const accumulator = [] const accumulator: string[] = []
for (const [key, value] of this.subscribed.entries()) { for (const [key, value] of this.subscribed.entries()) {
if (value === subscribed) accumulator.push(key) if (value === subscribed) accumulator.push(key)
} }
return accumulator return accumulator
} }
private loadSubscribedStatus () {
if (!this.isUserLoggedIn()) return
for (const videoChannel of this.videoChannels) {
const handle = this.getChannelHandler(videoChannel)
this.subscribed.set(handle, false)
merge(
this.userSubscriptionService.listenToSubscriptionCacheChange(handle),
this.userSubscriptionService.doesSubscriptionExist(handle)
)
.subscribe(
res => this.subscribed.set(handle, res),
err => this.notifier.error(err.message)
)
}
}
} }

View file

@ -1,44 +1,67 @@
import { bufferTime, catchError, filter, first, map, share, switchMap } from 'rxjs/operators' import { bufferTime, catchError, filter, map, tap, share, switchMap } from 'rxjs/operators'
import { Observable, ReplaySubject, Subject, of, merge } from 'rxjs'
import { HttpClient, HttpParams } from '@angular/common/http' import { HttpClient, HttpParams } from '@angular/common/http'
import { Injectable } from '@angular/core' import { Injectable } from '@angular/core'
import { ResultList } from '../../../../../shared' import { ResultList } from '../../../../../shared'
import { environment } from '../../../environments/environment' import { environment } from '../../../environments/environment'
import { RestExtractor, RestService } from '../rest' import { RestExtractor, RestService } from '../rest'
import { Observable, ReplaySubject, Subject } from 'rxjs'
import { VideoChannel } from '@app/shared/video-channel/video-channel.model' import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
import { VideoChannelService } from '@app/shared/video-channel/video-channel.service' import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
import { VideoChannel as VideoChannelServer } from '../../../../../shared/models/videos' import { VideoChannel as VideoChannelServer } from '../../../../../shared/models/videos'
import { ComponentPaginationLight } from '@app/shared/rest/component-pagination.model' import { ComponentPaginationLight } from '@app/shared/rest/component-pagination.model'
import { uniq } from 'lodash-es'
import * as debug from 'debug'
const logger = debug('peertube:subscriptions:UserSubscriptionService')
type SubscriptionExistResult = { [ uri: string ]: boolean } type SubscriptionExistResult = { [ uri: string ]: boolean }
type SubscriptionExistResultObservable = { [ uri: string ]: Observable<boolean> }
@Injectable() @Injectable()
export class UserSubscriptionService { export class UserSubscriptionService {
static BASE_USER_SUBSCRIPTIONS_URL = environment.apiUrl + '/api/v1/users/me/subscriptions' static BASE_USER_SUBSCRIPTIONS_URL = environment.apiUrl + '/api/v1/users/me/subscriptions'
// Use a replay subject because we "next" a value before subscribing // Use a replay subject because we "next" a value before subscribing
private existsSubject: Subject<string> = new ReplaySubject(1) private existsSubject = new ReplaySubject<string>(1)
private readonly existsObservable: Observable<SubscriptionExistResult> private readonly existsObservable: Observable<SubscriptionExistResult>
private myAccountSubscriptionCache: SubscriptionExistResult = {}
private myAccountSubscriptionCacheObservable: SubscriptionExistResultObservable = {}
private myAccountSubscriptionCacheSubject = new Subject<SubscriptionExistResult>()
constructor ( constructor (
private authHttp: HttpClient, private authHttp: HttpClient,
private restExtractor: RestExtractor, private restExtractor: RestExtractor,
private restService: RestService private restService: RestService
) { ) {
this.existsObservable = this.existsSubject.pipe( this.existsObservable = merge(
bufferTime(500), this.existsSubject.pipe(
filter(uris => uris.length !== 0), bufferTime(500),
switchMap(uris => this.doSubscriptionsExist(uris)), filter(uris => uris.length !== 0),
share() map(uris => uniq(uris)),
switchMap(uris => this.doSubscriptionsExist(uris)),
share()
),
this.myAccountSubscriptionCacheSubject
) )
} }
/**
* Subscription part
*/
deleteSubscription (nameWithHost: string) { deleteSubscription (nameWithHost: string) {
const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/' + nameWithHost const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/' + nameWithHost
return this.authHttp.delete(url) return this.authHttp.delete(url)
.pipe( .pipe(
map(this.restExtractor.extractDataBool), map(this.restExtractor.extractDataBool),
tap(() => {
this.myAccountSubscriptionCache[nameWithHost] = false
this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
}),
catchError(err => this.restExtractor.handleError(err)) catchError(err => this.restExtractor.handleError(err))
) )
} }
@ -50,6 +73,11 @@ export class UserSubscriptionService {
return this.authHttp.post(url, body) return this.authHttp.post(url, body)
.pipe( .pipe(
map(this.restExtractor.extractDataBool), map(this.restExtractor.extractDataBool),
tap(() => {
this.myAccountSubscriptionCache[nameWithHost] = true
this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
}),
catchError(err => this.restExtractor.handleError(err)) catchError(err => this.restExtractor.handleError(err))
) )
} }
@ -69,10 +97,46 @@ export class UserSubscriptionService {
) )
} }
/**
* SubscriptionExist part
*/
listenToMyAccountSubscriptionCacheSubject () {
return this.myAccountSubscriptionCacheSubject.asObservable()
}
listenToSubscriptionCacheChange (nameWithHost: string) {
if (nameWithHost in this.myAccountSubscriptionCacheObservable) {
return this.myAccountSubscriptionCacheObservable[ nameWithHost ]
}
const obs = this.existsObservable
.pipe(
filter(existsResult => existsResult[ nameWithHost ] !== undefined),
map(existsResult => existsResult[ nameWithHost ])
)
this.myAccountSubscriptionCacheObservable[ nameWithHost ] = obs
return obs
}
doesSubscriptionExist (nameWithHost: string) { doesSubscriptionExist (nameWithHost: string) {
logger('Running subscription check for %d.', nameWithHost)
if (nameWithHost in this.myAccountSubscriptionCache) {
logger('Found cache for %d.', nameWithHost)
return of(this.myAccountSubscriptionCache[ nameWithHost ])
}
this.existsSubject.next(nameWithHost) this.existsSubject.next(nameWithHost)
return this.existsObservable.pipe(first()) logger('Fetching from network for %d.', nameWithHost)
return this.existsObservable.pipe(
filter(existsResult => existsResult[ nameWithHost ] !== undefined),
map(existsResult => existsResult[ nameWithHost ]),
tap(result => this.myAccountSubscriptionCache[ nameWithHost ] = result)
)
} }
private doSubscriptionsExist (uris: string[]): Observable<SubscriptionExistResult> { private doSubscriptionsExist (uris: string[]): Observable<SubscriptionExistResult> {
@ -82,6 +146,14 @@ export class UserSubscriptionService {
params = this.restService.addObjectParams(params, { uris }) params = this.restService.addObjectParams(params, { uris })
return this.authHttp.get<SubscriptionExistResult>(url, { params }) return this.authHttp.get<SubscriptionExistResult>(url, { params })
.pipe(catchError(err => this.restExtractor.handleError(err))) .pipe(
tap(res => {
this.myAccountSubscriptionCache = {
...this.myAccountSubscriptionCache,
...res
}
}),
catchError(err => this.restExtractor.handleError(err))
)
} }
} }

View file

@ -24,11 +24,7 @@
<span class="views"> <span class="views">
<ng-container *ngIf="displayOptions.date && displayOptions.views"></ng-container> <ng-container *ngIf="displayOptions.date && displayOptions.views"></ng-container>
<ng-container i18n *ngIf="displayOptions.views">{{ video.views | myNumberFormatter }} <ng-container i18n *ngIf="displayOptions.views">{video.views, plural, =1 {1 view} other {{{ video.views | myNumberFormatter }} views}}</ng-container>
<ng-container *ngIf="video.views === 1; then single; else multiple"></ng-container>
<ng-template i18n #single>view</ng-template>
<ng-template i18n #multiple>views</ng-template>
</ng-container>
</span> </span>
</span> </span>