]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/commitdiff
Make subscribe buttons observe subscription statuses to synchronise
authorRigel Kent <sendmemail@rigelk.eu>
Wed, 8 Jan 2020 21:13:47 +0000 (22:13 +0100)
committerChocobozzz <chocobozzz@cpy.re>
Fri, 10 Jan 2020 09:12:09 +0000 (10:12 +0100)
client/src/app/+accounts/account-video-channels/account-video-channels.component.html
client/src/app/+accounts/accounts.component.html
client/src/app/+accounts/accounts.component.ts
client/src/app/shared/user-subscription/subscribe-button.component.html
client/src/app/shared/user-subscription/subscribe-button.component.scss
client/src/app/shared/user-subscription/subscribe-button.component.ts
client/src/app/shared/user-subscription/user-subscription.service.ts
client/src/app/shared/video/video-miniature.component.html

index 93f43a35046ecd8dfe617bd67145b98bd9ca23d2..78115684012c36e4db7bc924fe12083845433db9 100644 (file)
@@ -9,11 +9,7 @@
           <img [src]="videoChannel.avatarUrl" alt="Avatar" />
 
           <div>{{ videoChannel.displayName }}</div>
-          <div class="followers">{{ videoChannel.followersCount }} 
-            <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>
+          <div class="followers" i18n>{videoChannel.followersCount, plural, =1 {1 subscriber} other {{{ videoChannel.followersCount }} subscribers}}</div>
         </a>
 
         <my-subscribe-button [videoChannels]="[videoChannel]"></my-subscribe-button>
index 1b6eb480ebb13df1ba2650f34a98ffa4a0f7c1bb..be40b63cae971d8cd22579af3aeb910a9c540754 100644 (file)
           >
           </my-user-moderation-dropdown>
         </div>
-        <div class="actor-followers">
-          {{ 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 class="actor-followers" i18n>{account.followersCount, plural, =1 {1 subscriber} other {{{ account.followersCount }} subscribers}}</div>
       </div>
 
       <my-subscribe-button *ngIf="videoChannels" [account]="account" [videoChannels]="videoChannels"></my-subscribe-button>
index e3a503f4cb8ac97d91d9e033dbfd55293d2a9c06..8bde7ad070689123a34b1acd9c98b12e1a859918 100644 (file)
@@ -40,15 +40,15 @@ export class AccountsComponent implements OnInit, OnDestroy {
         map(params => params[ 'accountId' ]),
         distinctUntilChanged(),
         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 ]))
       )
       .subscribe(
-        account => {
-          this.account = account
-          this.videoChannelService.listAccountVideoChannels(account)
-            .subscribe(videoChannels => this.videoChannels = videoChannels.data)
-        },
+        videoChannels => this.videoChannels = videoChannels.data,
 
         err => this.notifier.error(err.message)
       )
index 6ac8af3de92c94bde674c14c4ef3869039b1a8e2..275349b7f379263512e7635ed548d74b15cc8df1 100644 (file)
@@ -1,13 +1,13 @@
 <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>
-    <span [ngClass]="{ 'extra-text': subscribeStatus(true).length > 0 }">
+    <span [ngClass]="{ 'extra-text': isAtLeastOneChannelSubscribed() }">
       <ng-container *ngIf="account; then multiple; else single"></ng-container>
       <ng-template i18n #single>Subscribe</ng-template>
       <ng-template #multiple>
         <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>
         </span>
       </ng-template>
     <button
       *ngIf="isAllChannelsSubscribed()" type="button"
       class="btn btn-sm" role="button"
-      (click)="unsubscribe()" i18n
-    >
-      <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>
+      (click)="unsubscribe()">
+      <ng-container i18n>{account + "", select, undefined {Unsubscribe} other {Unsubscribe from all channels}}</ng-container>
     </button>
   </ng-template>
 
index 164b917b866cc6170998e6d867c40bf9813faa97..d5b3796a16c29cade40a16a245a7d9d9f24bc7de 100644 (file)
     font-size: 15px;
   }
 
+  &.big {
+    height: 35px;
+
+    button .extra-text {
+      span:first-child {
+        line-height: 80%;
+      }
+    
+      span:not(:first-child) {
+        font-size: 75%;
+      }
+    }
+  }
+
   // Unlogged
   & > .dropdown > .dropdown-toggle span {
     padding-right: 3px;
@@ -80,5 +94,6 @@
 
   span:not(:first-child) {
     font-size: 60%;
+    text-align: left;
   }
 }
index f0bee9d4779f605ba19d3d1e7538a95c87e325cb..14a6bfe66ed2493ba3667d3933eefc6a8d6179db 100644 (file)
@@ -7,7 +7,7 @@ import { I18n } from '@ngx-translate/i18n-polyfill'
 import { VideoService } from '@app/shared/video/video.service'
 import { FeedFormat } from '../../../../../shared/models/feeds'
 import { Account } from '@app/shared/account/account.model'
-import { forkJoin } from 'rxjs'
+import { forkJoin, merge } from 'rxjs'
 
 @Component({
   selector: 'my-subscribe-button',
@@ -26,7 +26,7 @@ export class SubscribeButtonComponent implements OnInit {
   @Input() displayFollowers = false
   @Input() size: 'small' | 'normal' = 'normal'
 
-  subscribed: Map<string, boolean>
+  subscribed = new Map<string, boolean>()
 
   constructor (
     private authService: AuthService,
@@ -35,9 +35,7 @@ export class SubscribeButtonComponent implements OnInit {
     private userSubscriptionService: UserSubscriptionService,
     private i18n: I18n,
     private videoService: VideoService
-  ) {
-    this.subscribed = new Map<string, boolean>()
-  }
+  ) { }
 
   get handle () {
     return this.account
@@ -68,19 +66,7 @@ export class SubscribeButtonComponent implements OnInit {
   }
 
   ngOnInit () {
-    if (this.isUserLoggedIn()) {
-
-      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)
-          )
-      }))
-    }
+    this.loadSubscribedStatus()
   }
 
   subscribe () {
@@ -92,31 +78,22 @@ export class SubscribeButtonComponent implements OnInit {
   }
 
   localSubscribe () {
-    const observableBatch: any = []
-
-    this.videoChannels
-      .filter(videoChannel => this.subscribeStatus(false).includes(this.getChannelHandler(videoChannel)))
-      .forEach(videoChannel => observableBatch.push(
-        this.userSubscriptionService.addSubscription(this.getChannelHandler(videoChannel))
-      ))
+    const observableBatch = this.videoChannels
+      .map(videoChannel => this.getChannelHandler(videoChannel))
+      .filter(handle => this.subscribeStatus(false).includes(handle))
+      .map(handle => this.userSubscriptionService.addSubscription(handle))
 
     forkJoin(observableBatch)
       .subscribe(
         () => {
-          [...this.subscribed.keys()].forEach((key) => {
-            this.subscribed.set(key, true)
-          })
-
           this.notifier.success(
             this.account
               ? this.i18n(
-                  'Subscribed to all current channels of {{nameWithHost}}. ' +
-                  'You will be notified of all their new videos.',
+                  'Subscribed to all current channels of {{nameWithHost}}. You will be notified of all their new videos.',
                   { nameWithHost: this.account.displayName }
                 )
               : this.i18n(
-                  'Subscribed to {{nameWithHost}}. ' +
-                  'You will be notified of all their new videos.',
+                  'Subscribed to {{nameWithHost}}. You will be notified of all their new videos.',
                   { nameWithHost: this.videoChannels[0].displayName }
                 )
             ,
@@ -135,21 +112,14 @@ export class SubscribeButtonComponent implements OnInit {
   }
 
   localUnsubscribe () {
-    const observableBatch: any = []
-
-    this.videoChannels
-      .filter(videoChannel => this.subscribeStatus(true).includes(this.getChannelHandler(videoChannel)))
-      .forEach(videoChannel => observableBatch.push(
-        this.userSubscriptionService.deleteSubscription(this.getChannelHandler(videoChannel))
-      ))
+    const observableBatch = this.videoChannels
+      .map(videoChannel => this.getChannelHandler(videoChannel))
+      .filter(handle => this.subscribeStatus(true).includes(handle))
+      .map(handle => this.userSubscriptionService.deleteSubscription(handle))
 
     forkJoin(observableBatch)
         .subscribe(
           () => {
-            [...this.subscribed.keys()].forEach((key) => {
-              this.subscribed.set(key, false)
-            })
-
             this.notifier.success(
               this.account
                 ? 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)
   }
 
+  isAtLeastOneChannelSubscribed () {
+    return this.subscribeStatus(true).length > 0
+  }
+
+  isBigButton () {
+    return this.videoChannels.length > 1 && this.isAtLeastOneChannelSubscribed()
+  }
+
   gotoLogin () {
     this.router.navigate([ '/login' ])
   }
@@ -180,10 +158,28 @@ export class SubscribeButtonComponent implements OnInit {
   }
 
   private subscribeStatus (subscribed: boolean) {
-    const accumulator = []
+    const accumulator: string[] = []
     for (const [key, value] of this.subscribed.entries()) {
       if (value === subscribed) accumulator.push(key)
     }
     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)
+          )
+    }
+  }
 }
index 83df40a43f51587fa49ec975eff5974dab712395..bfb5848bc212b4df232298fb2abaff4d38e16a4f 100644 (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 { Injectable } from '@angular/core'
 import { ResultList } from '../../../../../shared'
 import { environment } from '../../../environments/environment'
 import { RestExtractor, RestService } from '../rest'
-import { Observable, ReplaySubject, Subject } from 'rxjs'
 import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
 import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
 import { VideoChannel as VideoChannelServer } from '../../../../../shared/models/videos'
 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 SubscriptionExistResultObservable = { [ uri: string ]: Observable<boolean> }
 
 @Injectable()
 export class UserSubscriptionService {
   static BASE_USER_SUBSCRIPTIONS_URL = environment.apiUrl + '/api/v1/users/me/subscriptions'
 
   // 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 myAccountSubscriptionCache: SubscriptionExistResult = {}
+  private myAccountSubscriptionCacheObservable: SubscriptionExistResultObservable = {}
+  private myAccountSubscriptionCacheSubject = new Subject<SubscriptionExistResult>()
+
   constructor (
     private authHttp: HttpClient,
     private restExtractor: RestExtractor,
     private restService: RestService
   ) {
-    this.existsObservable = this.existsSubject.pipe(
-      bufferTime(500),
-      filter(uris => uris.length !== 0),
-      switchMap(uris => this.doSubscriptionsExist(uris)),
-      share()
+    this.existsObservable = merge(
+      this.existsSubject.pipe(
+        bufferTime(500),
+        filter(uris => uris.length !== 0),
+        map(uris => uniq(uris)),
+        switchMap(uris => this.doSubscriptionsExist(uris)),
+        share()
+      ),
+
+      this.myAccountSubscriptionCacheSubject
     )
   }
 
+  /**
+   * Subscription part
+   */
+
   deleteSubscription (nameWithHost: string) {
     const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/' + nameWithHost
 
     return this.authHttp.delete(url)
                .pipe(
                  map(this.restExtractor.extractDataBool),
+                 tap(() => {
+                   this.myAccountSubscriptionCache[nameWithHost] = false
+
+                   this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
+                 }),
                  catchError(err => this.restExtractor.handleError(err))
                )
   }
@@ -50,6 +73,11 @@ export class UserSubscriptionService {
     return this.authHttp.post(url, body)
                .pipe(
                  map(this.restExtractor.extractDataBool),
+                 tap(() => {
+                   this.myAccountSubscriptionCache[nameWithHost] = true
+
+                   this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
+                 }),
                  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) {
+    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)
 
-    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> {
@@ -82,6 +146,14 @@ export class UserSubscriptionService {
     params = this.restService.addObjectParams(params, { uris })
 
     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))
+               )
   }
 }
index a31165a415ba47cf6c9435a98a9e66fdfbcf776f..ce977b3e637c33866e26bb885d539bef39bfe18b 100644 (file)
 
         <span class="views">
           <ng-container *ngIf="displayOptions.date && displayOptions.views"> • </ng-container>
-          <ng-container i18n *ngIf="displayOptions.views">{{ video.views | myNumberFormatter }} 
-            <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>
+          <ng-container i18n *ngIf="displayOptions.views">{video.views, plural, =1 {1 view} other {{{ video.views | myNumberFormatter }} views}}</ng-container>
         </span>
       </span>