1 import * as debug from 'debug'
2 import { merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
3 import { catchError, filter, map, switchMap, tap } from 'rxjs/operators'
4 import { HttpClient, HttpParams } from '@angular/common/http'
5 import { Injectable } from '@angular/core'
6 import { ComponentPaginationLight, RestExtractor, RestService } from '@app/core'
7 import { buildBulkObservable } from '@app/helpers'
8 import { Video, VideoChannel, VideoChannelService, VideoService } from '@app/shared/shared-main'
9 import { ActorFollow, ResultList, VideoChannel as VideoChannelServer, VideoSortField } from '@shared/models'
10 import { environment } from '../../../environments/environment'
12 const logger = debug('peertube:subscriptions:UserSubscriptionService')
14 type SubscriptionExistResult = { [ uri: string ]: boolean }
15 type SubscriptionExistResultObservable = { [ uri: string ]: Observable<boolean> }
18 export class UserSubscriptionService {
19 static BASE_USER_SUBSCRIPTIONS_URL = environment.apiUrl + '/api/v1/users/me/subscriptions'
20 static BASE_VIDEO_CHANNELS_URL = environment.apiUrl + '/api/v1/video-channels'
21 static BASE_ACCOUNTS_URL = environment.apiUrl + '/api/v1/accounts'
23 // Use a replay subject because we "next" a value before subscribing
24 private existsSubject = new ReplaySubject<string>(1)
25 private readonly existsObservable: Observable<SubscriptionExistResult>
27 private myAccountSubscriptionCache: SubscriptionExistResult = {}
28 private myAccountSubscriptionCacheObservable: SubscriptionExistResultObservable = {}
29 private myAccountSubscriptionCacheSubject = new Subject<SubscriptionExistResult>()
32 private authHttp: HttpClient,
33 private restExtractor: RestExtractor,
34 private videoService: VideoService,
35 private restService: RestService
37 this.existsObservable = merge(
40 notifierObservable: this.existsSubject,
41 bulkGet: this.doSubscriptionsExist.bind(this)
42 }).pipe(map(r => r.response)),
44 this.myAccountSubscriptionCacheSubject
48 listFollowers (parameters: {
49 pagination: ComponentPaginationLight
53 const { pagination, nameWithHost, search } = parameters
55 let url = `${UserSubscriptionService.BASE_ACCOUNTS_URL}/${nameWithHost}/followers`
57 let params = new HttpParams()
58 params = this.restService.addRestGetParams(params, this.restService.componentToRestPagination(pagination), '-createdAt')
61 const filters = this.restService.parseQueryStringFilter(search, {
67 if (filters.channel) {
68 url = `${UserSubscriptionService.BASE_VIDEO_CHANNELS_URL}/${filters.channel}/followers`
71 params = this.restService.addObjectParams(params, { search: filters.search })
75 .get<ResultList<ActorFollow>>(url, { params })
77 catchError(err => this.restExtractor.handleError(err))
81 getUserSubscriptionVideos (parameters: {
82 videoPagination: ComponentPaginationLight
85 }): Observable<ResultList<Video>> {
86 const { videoPagination, sort, skipCount } = parameters
87 const pagination = this.restService.componentToRestPagination(videoPagination)
89 let params = new HttpParams()
90 params = this.restService.addRestGetParams(params, pagination, sort)
92 if (skipCount) params = params.set('skipCount', skipCount + '')
95 .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
97 switchMap(res => this.videoService.extractVideos(res)),
98 catchError(err => this.restExtractor.handleError(err))
106 deleteSubscription (nameWithHost: string) {
107 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/' + nameWithHost
109 return this.authHttp.delete(url)
111 map(this.restExtractor.extractDataBool),
113 this.myAccountSubscriptionCache[nameWithHost] = false
115 this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
117 catchError(err => this.restExtractor.handleError(err))
121 addSubscription (nameWithHost: string) {
122 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL
124 const body = { uri: nameWithHost }
125 return this.authHttp.post(url, body)
127 map(this.restExtractor.extractDataBool),
129 this.myAccountSubscriptionCache[nameWithHost] = true
131 this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
133 catchError(err => this.restExtractor.handleError(err))
137 listSubscriptions (parameters: {
138 pagination: ComponentPaginationLight
140 }): Observable<ResultList<VideoChannel>> {
141 const { pagination, search } = parameters
142 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL
144 const restPagination = this.restService.componentToRestPagination(pagination)
146 let params = new HttpParams()
147 params = this.restService.addRestGetParams(params, restPagination)
148 if (search) params = params.append('search', search)
150 return this.authHttp.get<ResultList<VideoChannelServer>>(url, { params })
152 map(res => VideoChannelService.extractVideoChannels(res)),
153 catchError(err => this.restExtractor.handleError(err))
158 * SubscriptionExist part
161 listenToMyAccountSubscriptionCacheSubject () {
162 return this.myAccountSubscriptionCacheSubject.asObservable()
165 listenToSubscriptionCacheChange (nameWithHost: string) {
166 if (nameWithHost in this.myAccountSubscriptionCacheObservable) {
167 return this.myAccountSubscriptionCacheObservable[nameWithHost]
170 const obs = this.existsObservable
172 filter(existsResult => existsResult[nameWithHost] !== undefined),
173 map(existsResult => existsResult[nameWithHost])
176 this.myAccountSubscriptionCacheObservable[nameWithHost] = obs
180 doesSubscriptionExist (nameWithHost: string) {
181 logger('Running subscription check for %d.', nameWithHost)
183 if (nameWithHost in this.myAccountSubscriptionCache) {
184 logger('Found cache for %d.', nameWithHost)
186 return of(this.myAccountSubscriptionCache[nameWithHost])
189 this.existsSubject.next(nameWithHost)
191 logger('Fetching from network for %d.', nameWithHost)
192 return this.existsObservable.pipe(
193 filter(existsResult => existsResult[nameWithHost] !== undefined),
194 map(existsResult => existsResult[nameWithHost]),
195 tap(result => this.myAccountSubscriptionCache[nameWithHost] = result)
199 private doSubscriptionsExist (uris: string[]): Observable<SubscriptionExistResult> {
200 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/exist'
201 let params = new HttpParams()
203 params = this.restService.addObjectParams(params, { uris })
205 return this.authHttp.get<SubscriptionExistResult>(url, { params })
208 this.myAccountSubscriptionCache = {
209 ...this.myAccountSubscriptionCache,
213 catchError(err => this.restExtractor.handleError(err))