]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-user-subscription/user-subscription.service.ts
Add video-playlist-element.created hook (#4196)
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-user-subscription / user-subscription.service.ts
CommitLineData
67ed6552
C
1import * as debug from 'debug'
2import { uniq } from 'lodash-es'
44d4ee4f 3import { asyncScheduler, merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
67ed6552 4import { bufferTime, catchError, filter, map, observeOn, share, switchMap, tap } from 'rxjs/operators'
f37dc0dd 5import { HttpClient, HttpParams } from '@angular/common/http'
44d4ee4f 6import { Injectable, NgZone } from '@angular/core'
67ed6552
C
7import { ComponentPaginationLight, RestExtractor, RestService } from '@app/core'
8import { enterZone, leaveZone } from '@app/helpers'
9import { Video, VideoChannel, VideoChannelService, VideoService } from '@app/shared/shared-main'
10import { ResultList, VideoChannel as VideoChannelServer, VideoSortField } from '@shared/models'
22a16e36 11import { environment } from '../../../environments/environment'
9270ccf6
RK
12
13const logger = debug('peertube:subscriptions:UserSubscriptionService')
22a16e36 14
f37dc0dd 15type SubscriptionExistResult = { [ uri: string ]: boolean }
9270ccf6 16type SubscriptionExistResultObservable = { [ uri: string ]: Observable<boolean> }
f37dc0dd 17
22a16e36
C
18@Injectable()
19export class UserSubscriptionService {
20 static BASE_USER_SUBSCRIPTIONS_URL = environment.apiUrl + '/api/v1/users/me/subscriptions'
21
f37dc0dd 22 // Use a replay subject because we "next" a value before subscribing
9270ccf6 23 private existsSubject = new ReplaySubject<string>(1)
aa55a4da 24 private readonly existsObservable: Observable<SubscriptionExistResult>
f37dc0dd 25
9270ccf6
RK
26 private myAccountSubscriptionCache: SubscriptionExistResult = {}
27 private myAccountSubscriptionCacheObservable: SubscriptionExistResultObservable = {}
28 private myAccountSubscriptionCacheSubject = new Subject<SubscriptionExistResult>()
29
22a16e36
C
30 constructor (
31 private authHttp: HttpClient,
f37dc0dd 32 private restExtractor: RestExtractor,
67ed6552 33 private videoService: VideoService,
44d4ee4f
C
34 private restService: RestService,
35 private ngZone: NgZone
22a16e36 36 ) {
9270ccf6
RK
37 this.existsObservable = merge(
38 this.existsSubject.pipe(
44d4ee4f
C
39 // We leave Angular zone so Protractor does not get stuck
40 bufferTime(500, leaveZone(this.ngZone, asyncScheduler)),
9270ccf6
RK
41 filter(uris => uris.length !== 0),
42 map(uris => uniq(uris)),
44d4ee4f 43 observeOn(enterZone(this.ngZone, asyncScheduler)),
9270ccf6
RK
44 switchMap(uris => this.doSubscriptionsExist(uris)),
45 share()
46 ),
47
48 this.myAccountSubscriptionCacheSubject
f37dc0dd 49 )
22a16e36
C
50 }
51
67ed6552
C
52 getUserSubscriptionVideos (parameters: {
53 videoPagination: ComponentPaginationLight,
54 sort: VideoSortField,
55 skipCount?: boolean
56 }): Observable<ResultList<Video>> {
57 const { videoPagination, sort, skipCount } = parameters
58 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
59
60 let params = new HttpParams()
61 params = this.restService.addRestGetParams(params, pagination, sort)
62
63 if (skipCount) params = params.set('skipCount', skipCount + '')
64
65 return this.authHttp
66 .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
67 .pipe(
68 switchMap(res => this.videoService.extractVideos(res)),
69 catchError(err => this.restExtractor.handleError(err))
70 )
71 }
72
9270ccf6
RK
73 /**
74 * Subscription part
75 */
76
22a16e36
C
77 deleteSubscription (nameWithHost: string) {
78 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/' + nameWithHost
79
80 return this.authHttp.delete(url)
81 .pipe(
82 map(this.restExtractor.extractDataBool),
9270ccf6
RK
83 tap(() => {
84 this.myAccountSubscriptionCache[nameWithHost] = false
85
86 this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
87 }),
22a16e36
C
88 catchError(err => this.restExtractor.handleError(err))
89 )
90 }
91
92 addSubscription (nameWithHost: string) {
93 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL
94
95 const body = { uri: nameWithHost }
96 return this.authHttp.post(url, body)
97 .pipe(
98 map(this.restExtractor.extractDataBool),
9270ccf6
RK
99 tap(() => {
100 this.myAccountSubscriptionCache[nameWithHost] = true
101
102 this.myAccountSubscriptionCacheSubject.next(this.myAccountSubscriptionCache)
103 }),
22a16e36
C
104 catchError(err => this.restExtractor.handleError(err))
105 )
106 }
107
4f5d0459
RK
108 listSubscriptions (parameters: {
109 pagination: ComponentPaginationLight
110 search: string
111 }): Observable<ResultList<VideoChannel>> {
112 const { pagination, search } = parameters
22a16e36
C
113 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL
114
4f5d0459 115 const restPagination = this.restService.componentPaginationToRestPagination(pagination)
aa55a4da
C
116
117 let params = new HttpParams()
4f5d0459
RK
118 params = this.restService.addRestGetParams(params, restPagination)
119 if (search) params = params.append('search', search)
aa55a4da
C
120
121 return this.authHttp.get<ResultList<VideoChannelServer>>(url, { params })
22a16e36
C
122 .pipe(
123 map(res => VideoChannelService.extractVideoChannels(res)),
124 catchError(err => this.restExtractor.handleError(err))
125 )
126 }
127
9270ccf6
RK
128 /**
129 * SubscriptionExist part
130 */
131
132 listenToMyAccountSubscriptionCacheSubject () {
133 return this.myAccountSubscriptionCacheSubject.asObservable()
134 }
135
136 listenToSubscriptionCacheChange (nameWithHost: string) {
137 if (nameWithHost in this.myAccountSubscriptionCacheObservable) {
138 return this.myAccountSubscriptionCacheObservable[ nameWithHost ]
139 }
140
141 const obs = this.existsObservable
142 .pipe(
143 filter(existsResult => existsResult[ nameWithHost ] !== undefined),
144 map(existsResult => existsResult[ nameWithHost ])
145 )
146
147 this.myAccountSubscriptionCacheObservable[ nameWithHost ] = obs
148 return obs
149 }
150
f0a39880 151 doesSubscriptionExist (nameWithHost: string) {
9270ccf6
RK
152 logger('Running subscription check for %d.', nameWithHost)
153
154 if (nameWithHost in this.myAccountSubscriptionCache) {
155 logger('Found cache for %d.', nameWithHost)
156
157 return of(this.myAccountSubscriptionCache[ nameWithHost ])
158 }
159
f37dc0dd 160 this.existsSubject.next(nameWithHost)
22a16e36 161
9270ccf6
RK
162 logger('Fetching from network for %d.', nameWithHost)
163 return this.existsObservable.pipe(
164 filter(existsResult => existsResult[ nameWithHost ] !== undefined),
165 map(existsResult => existsResult[ nameWithHost ]),
166 tap(result => this.myAccountSubscriptionCache[ nameWithHost ] = result)
167 )
f37dc0dd 168 }
22a16e36 169
f0a39880 170 private doSubscriptionsExist (uris: string[]): Observable<SubscriptionExistResult> {
f37dc0dd
C
171 const url = UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/exist'
172 let params = new HttpParams()
173
174 params = this.restService.addObjectParams(params, { uris })
175
176 return this.authHttp.get<SubscriptionExistResult>(url, { params })
9270ccf6
RK
177 .pipe(
178 tap(res => {
179 this.myAccountSubscriptionCache = {
180 ...this.myAccountSubscriptionCache,
181 ...res
182 }
183 }),
184 catchError(err => this.restExtractor.handleError(err))
185 )
22a16e36
C
186 }
187}