]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/video-playlist/video-playlist.service.ts
Fix angular 9 build
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / video-playlist / video-playlist.service.ts
CommitLineData
44d4ee4f
C
1import { bufferTime, catchError, filter, map, observeOn, share, switchMap, tap } from 'rxjs/operators'
2import { Injectable, NgZone } from '@angular/core'
3import { asyncScheduler, merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
830b4faf 4import { RestExtractor } from '../rest/rest-extractor.service'
f0a39880
C
5import { HttpClient, HttpParams } from '@angular/common/http'
6import { ResultList, VideoPlaylistElementCreate, VideoPlaylistElementUpdate } from '../../../../../shared'
830b4faf
C
7import { environment } from '../../../environments/environment'
8import { VideoPlaylist as VideoPlaylistServerModel } from '@shared/models/videos/playlist/video-playlist.model'
9import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
10import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
11import { VideoPlaylistCreate } from '@shared/models/videos/playlist/video-playlist-create.model'
12import { VideoPlaylistUpdate } from '@shared/models/videos/playlist/video-playlist-update.model'
13import { objectToFormData } from '@app/shared/misc/utils'
51b34a11 14import { AuthUser, ServerService } from '@app/core'
830b4faf
C
15import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
16import { AccountService } from '@app/shared/account/account.service'
17import { Account } from '@app/shared/account/account.model'
f0a39880 18import { RestService } from '@app/shared/rest'
51b34a11 19import { VideoExistInPlaylist, VideosExistInPlaylists } from '@shared/models/videos/playlist/video-exist-in-playlist.model'
15e9d5ca 20import { VideoPlaylistReorder } from '@shared/models/videos/playlist/video-playlist-reorder.model'
440d39c5 21import { ComponentPaginationLight } from '@app/shared/rest/component-pagination.model'
bfbd9128
C
22import { VideoPlaylistElement as ServerVideoPlaylistElement } from '@shared/models/videos/playlist/video-playlist-element.model'
23import { VideoPlaylistElement } from '@app/shared/video-playlist/video-playlist-element.model'
51b34a11
C
24import { uniq } from 'lodash-es'
25import * as debug from 'debug'
44d4ee4f 26import { enterZone, leaveZone } from '@app/shared/rxjs/zone'
51b34a11
C
27
28const logger = debug('peertube:playlists:VideoPlaylistService')
29
93d54cc7 30export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
830b4faf
C
31
32@Injectable()
33export class VideoPlaylistService {
34 static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
f0a39880
C
35 static MY_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/users/me/video-playlists/'
36
37 // Use a replay subject because we "next" a value before subscribing
51b34a11
C
38 private videoExistsInPlaylistNotifier = new ReplaySubject<number>(1)
39 private videoExistsInPlaylistCacheSubject = new Subject<VideosExistInPlaylists>()
40 private readonly videoExistsInPlaylistObservable: Observable<VideosExistInPlaylists>
41
42 private videoExistsObservableCache: { [ id: number ]: Observable<VideoExistInPlaylist[]> } = {}
43 private videoExistsCache: { [ id: number ]: VideoExistInPlaylist[] } = {}
44
45 private myAccountPlaylistCache: ResultList<CachedPlaylist> = undefined
f44a284a 46 private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
51b34a11 47 private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
830b4faf
C
48
49 constructor (
50 private authHttp: HttpClient,
51 private serverService: ServerService,
f0a39880 52 private restExtractor: RestExtractor,
44d4ee4f
C
53 private restService: RestService,
54 private ngZone: NgZone
f0a39880 55 ) {
51b34a11
C
56 this.videoExistsInPlaylistObservable = merge(
57 this.videoExistsInPlaylistNotifier.pipe(
44d4ee4f
C
58 // We leave Angular zone so Protractor does not get stuck
59 bufferTime(500, leaveZone(this.ngZone, asyncScheduler)),
51b34a11
C
60 filter(videoIds => videoIds.length !== 0),
61 map(videoIds => uniq(videoIds)),
44d4ee4f 62 observeOn(enterZone(this.ngZone, asyncScheduler)),
51b34a11
C
63 switchMap(videoIds => this.doVideosExistInPlaylist(videoIds)),
64 share()
65 ),
66
67 this.videoExistsInPlaylistCacheSubject
f0a39880
C
68 )
69 }
830b4faf 70
440d39c5 71 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
830b4faf 72 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
ad453580 73 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
830b4faf 74
ad453580
C
75 let params = new HttpParams()
76 params = this.restService.addRestGetParams(params, pagination)
77
78 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
830b4faf
C
79 .pipe(
80 switchMap(res => this.extractPlaylists(res)),
81 catchError(err => this.restExtractor.handleError(err))
82 )
83 }
84
51b34a11 85 listMyPlaylistWithCache (user: AuthUser, search?: string) {
6b0c3c7c 86 if (!search) {
f44a284a 87 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
6b0c3c7c
C
88 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
89 }
90
f44a284a 91 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
51b34a11
C
92 .pipe(
93 tap(result => {
6b0c3c7c 94 if (!search) {
f44a284a 95 this.myAccountPlaylistCacheRunning = undefined
6b0c3c7c
C
96 this.myAccountPlaylistCache = result
97 }
f44a284a
C
98 }),
99 share()
51b34a11 100 )
f44a284a
C
101
102 if (!search) this.myAccountPlaylistCacheRunning = obs
103 return obs
51b34a11
C
104 }
105
c06af501
RK
106 listAccountPlaylists (
107 account: Account,
440d39c5 108 componentPagination: ComponentPaginationLight,
c06af501
RK
109 sort: string,
110 search?: string
111 ): Observable<ResultList<VideoPlaylist>> {
830b4faf 112 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
ad453580
C
113 const pagination = componentPagination
114 ? this.restService.componentPaginationToRestPagination(componentPagination)
115 : undefined
830b4faf 116
f0a39880 117 let params = new HttpParams()
ad453580 118 params = this.restService.addRestGetParams(params, pagination, sort)
c06af501 119 if (search) params = this.restService.addObjectParams(params, { search })
f0a39880
C
120
121 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
830b4faf
C
122 .pipe(
123 switchMap(res => this.extractPlaylists(res)),
124 catchError(err => this.restExtractor.handleError(err))
125 )
126 }
127
128 getVideoPlaylist (id: string | number) {
129 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
130
131 return this.authHttp.get<VideoPlaylist>(url)
132 .pipe(
133 switchMap(res => this.extractPlaylist(res)),
134 catchError(err => this.restExtractor.handleError(err))
135 )
136 }
137
138 createVideoPlaylist (body: VideoPlaylistCreate) {
139 const data = objectToFormData(body)
140
f0a39880 141 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
830b4faf 142 .pipe(
51b34a11
C
143 tap(res => {
144 this.myAccountPlaylistCache.total++
145
146 this.myAccountPlaylistCache.data.push({
147 id: res.videoPlaylist.id,
148 displayName: body.displayName
149 })
150
151 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
152 }),
830b4faf
C
153 catchError(err => this.restExtractor.handleError(err))
154 )
155 }
156
157 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
158 const data = objectToFormData(body)
159
160 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
161 .pipe(
162 map(this.restExtractor.extractDataBool),
51b34a11
C
163 tap(() => {
164 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
165 playlist.displayName = body.displayName
166
167 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
168 }),
830b4faf
C
169 catchError(err => this.restExtractor.handleError(err))
170 )
171 }
172
173 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
174 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
175 .pipe(
176 map(this.restExtractor.extractDataBool),
51b34a11
C
177 tap(() => {
178 this.myAccountPlaylistCache.total--
179 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
180 .filter(p => p.id !== videoPlaylist.id)
181
182 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
183 }),
830b4faf
C
184 catchError(err => this.restExtractor.handleError(err))
185 )
186 }
187
f0a39880 188 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
a3671f07
C
189 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
190
191 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
51b34a11
C
192 .pipe(
193 tap(res => {
194 const existsResult = this.videoExistsCache[body.videoId]
195 existsResult.push({
196 playlistId,
197 playlistElementId: res.videoPlaylistElement.id,
198 startTimestamp: body.startTimestamp,
199 stopTimestamp: body.stopTimestamp
200 })
201
202 this.runPlaylistCheck(body.videoId)
203 }),
204 catchError(err => this.restExtractor.handleError(err))
205 )
f0a39880
C
206 }
207
51b34a11 208 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
bfbd9128 209 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
f0a39880
C
210 .pipe(
211 map(this.restExtractor.extractDataBool),
51b34a11
C
212 tap(() => {
213 const existsResult = this.videoExistsCache[videoId]
214 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
215
216 elem.startTimestamp = body.startTimestamp
217 elem.stopTimestamp = body.stopTimestamp
218
219 this.runPlaylistCheck(videoId)
220 }),
f0a39880
C
221 catchError(err => this.restExtractor.handleError(err))
222 )
223 }
224
51b34a11 225 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
bfbd9128 226 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
f0a39880
C
227 .pipe(
228 map(this.restExtractor.extractDataBool),
51b34a11
C
229 tap(() => {
230 if (!videoId) return
231
232 this.videoExistsCache[videoId] = this.videoExistsCache[videoId].filter(e => e.playlistElementId !== playlistElementId)
233 this.runPlaylistCheck(videoId)
234 }),
f0a39880
C
235 catchError(err => this.restExtractor.handleError(err))
236 )
237 }
238
15e9d5ca
C
239 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
240 const body: VideoPlaylistReorder = {
241 startPosition: oldPosition,
242 insertAfterPosition: newPosition
243 }
244
245 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
246 .pipe(
247 map(this.restExtractor.extractDataBool),
248 catchError(err => this.restExtractor.handleError(err))
249 )
250 }
251
bfbd9128
C
252 getPlaylistVideos (
253 videoPlaylistId: number | string,
440d39c5 254 componentPagination: ComponentPaginationLight
bfbd9128
C
255 ): Observable<ResultList<VideoPlaylistElement>> {
256 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylistId + '/videos'
257 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
258
259 let params = new HttpParams()
260 params = this.restService.addRestGetParams(params, pagination)
261
262 return this.authHttp
263 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
264 .pipe(
265 switchMap(res => this.extractVideoPlaylistElements(res)),
266 catchError(err => this.restExtractor.handleError(err))
267 )
268 }
269
51b34a11
C
270 listenToMyAccountPlaylistsChange () {
271 return this.myAccountPlaylistCacheSubject.asObservable()
272 }
273
274 listenToVideoPlaylistChange (videoId: number) {
275 if (this.videoExistsObservableCache[ videoId ]) {
276 return this.videoExistsObservableCache[ videoId ]
277 }
278
279 const obs = this.videoExistsInPlaylistObservable
280 .pipe(
281 map(existsResult => existsResult[ videoId ]),
282 filter(r => !!r),
283 tap(result => this.videoExistsCache[ videoId ] = result)
284 )
285
286 this.videoExistsObservableCache[ videoId ] = obs
287 return obs
288 }
289
290 runPlaylistCheck (videoId: number) {
291 logger('Running playlist check.')
292
293 if (this.videoExistsCache[videoId]) {
294 logger('Found cache for %d.', videoId)
295
296 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
297 }
f0a39880 298
51b34a11
C
299 logger('Fetching from network for %d.', videoId)
300 return this.videoExistsInPlaylistNotifier.next(videoId)
f0a39880
C
301 }
302
830b4faf 303 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
ba430d75 304 return this.serverService.getServerLocale()
830b4faf
C
305 .pipe(
306 map(translations => {
307 const playlistsJSON = result.data
308 const total = result.total
309 const playlists: VideoPlaylist[] = []
310
311 for (const playlistJSON of playlistsJSON) {
312 playlists.push(new VideoPlaylist(playlistJSON, translations))
313 }
314
315 return { data: playlists, total }
316 })
317 )
318 }
319
320 extractPlaylist (playlist: VideoPlaylistServerModel) {
ba430d75 321 return this.serverService.getServerLocale()
830b4faf
C
322 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
323 }
f0a39880 324
bfbd9128 325 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
ba430d75 326 return this.serverService.getServerLocale()
bfbd9128
C
327 .pipe(
328 map(translations => {
329 const elementsJson = result.data
330 const total = result.total
331 const elements: VideoPlaylistElement[] = []
332
333 for (const elementJson of elementsJson) {
334 elements.push(new VideoPlaylistElement(elementJson, translations))
335 }
336
337 return { total, data: elements }
338 })
339 )
340 }
341
51b34a11 342 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
f0a39880 343 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
f0a39880 344
c06af501 345 let params = new HttpParams()
f0a39880
C
346 params = this.restService.addObjectParams(params, { videoIds })
347
b7819090 348 return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
f0a39880
C
349 .pipe(catchError(err => this.restExtractor.handleError(err)))
350 }
830b4faf 351}