Fix e2e tests
[oweals/peertube.git] / client / src / app / shared / video-playlist / video-playlist.service.ts
1 import { bufferTime, catchError, filter, map, observeOn, share, switchMap, tap } from 'rxjs/operators'
2 import { Injectable, NgZone } from '@angular/core'
3 import { asyncScheduler, merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
4 import { RestExtractor } from '../rest/rest-extractor.service'
5 import { HttpClient, HttpParams } from '@angular/common/http'
6 import { ResultList, VideoPlaylistElementCreate, VideoPlaylistElementUpdate } from '../../../../../shared'
7 import { environment } from '../../../environments/environment'
8 import { VideoPlaylist as VideoPlaylistServerModel } from '@shared/models/videos/playlist/video-playlist.model'
9 import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
10 import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
11 import { VideoPlaylistCreate } from '@shared/models/videos/playlist/video-playlist-create.model'
12 import { VideoPlaylistUpdate } from '@shared/models/videos/playlist/video-playlist-update.model'
13 import { objectToFormData } from '@app/shared/misc/utils'
14 import { AuthUser, ServerService } from '@app/core'
15 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
16 import { AccountService } from '@app/shared/account/account.service'
17 import { Account } from '@app/shared/account/account.model'
18 import { RestService } from '@app/shared/rest'
19 import { VideoExistInPlaylist, VideosExistInPlaylists } from '@shared/models/videos/playlist/video-exist-in-playlist.model'
20 import { VideoPlaylistReorder } from '@shared/models/videos/playlist/video-playlist-reorder.model'
21 import { ComponentPaginationLight } from '@app/shared/rest/component-pagination.model'
22 import { VideoPlaylistElement as ServerVideoPlaylistElement } from '@shared/models/videos/playlist/video-playlist-element.model'
23 import { VideoPlaylistElement } from '@app/shared/video-playlist/video-playlist-element.model'
24 import { uniq } from 'lodash-es'
25 import * as debug from 'debug'
26 import { enterZone, leaveZone } from '@app/shared/rxjs/zone'
27
28 const logger = debug('peertube:playlists:VideoPlaylistService')
29
30 export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
31
32 @Injectable()
33 export class VideoPlaylistService {
34   static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
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
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
46   private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
47   private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
48
49   constructor (
50     private authHttp: HttpClient,
51     private serverService: ServerService,
52     private restExtractor: RestExtractor,
53     private restService: RestService,
54     private ngZone: NgZone
55   ) {
56     this.videoExistsInPlaylistObservable = merge(
57       this.videoExistsInPlaylistNotifier.pipe(
58         // We leave Angular zone so Protractor does not get stuck
59         bufferTime(500, leaveZone(this.ngZone, asyncScheduler)),
60         filter(videoIds => videoIds.length !== 0),
61         map(videoIds => uniq(videoIds)),
62         observeOn(enterZone(this.ngZone, asyncScheduler)),
63         switchMap(videoIds => this.doVideosExistInPlaylist(videoIds)),
64         share()
65       ),
66
67       this.videoExistsInPlaylistCacheSubject
68     )
69   }
70
71   listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
72     const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
73     const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
74
75     let params = new HttpParams()
76     params = this.restService.addRestGetParams(params, pagination)
77
78     return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
79                .pipe(
80                  switchMap(res => this.extractPlaylists(res)),
81                  catchError(err => this.restExtractor.handleError(err))
82                )
83   }
84
85   listMyPlaylistWithCache (user: AuthUser, search?: string) {
86     if (!search) {
87       if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
88       if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
89     }
90
91     const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
92                .pipe(
93                  tap(result => {
94                    if (!search) {
95                      this.myAccountPlaylistCacheRunning = undefined
96                      this.myAccountPlaylistCache = result
97                    }
98                  }),
99                  share()
100                )
101
102     if (!search) this.myAccountPlaylistCacheRunning = obs
103     return obs
104   }
105
106   listAccountPlaylists (
107     account: Account,
108     componentPagination: ComponentPaginationLight,
109     sort: string,
110     search?: string
111   ): Observable<ResultList<VideoPlaylist>> {
112     const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
113     const pagination = componentPagination
114       ? this.restService.componentPaginationToRestPagination(componentPagination)
115       : undefined
116
117     let params = new HttpParams()
118     params = this.restService.addRestGetParams(params, pagination, sort)
119     if (search) params = this.restService.addObjectParams(params, { search })
120
121     return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
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
141     return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
142                .pipe(
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                  }),
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),
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                  }),
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),
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                  }),
184                  catchError(err => this.restExtractor.handleError(err))
185                )
186   }
187
188   addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
189     const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
190
191     return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
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                )
206   }
207
208   updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
209     return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
210                .pipe(
211                  map(this.restExtractor.extractDataBool),
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                  }),
221                  catchError(err => this.restExtractor.handleError(err))
222                )
223   }
224
225   removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
226     return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
227                .pipe(
228                  map(this.restExtractor.extractDataBool),
229                  tap(() => {
230                    if (!videoId) return
231
232                    this.videoExistsCache[videoId] = this.videoExistsCache[videoId].filter(e => e.playlistElementId !== playlistElementId)
233                    this.runPlaylistCheck(videoId)
234                  }),
235                  catchError(err => this.restExtractor.handleError(err))
236                )
237   }
238
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
252   getPlaylistVideos (
253     videoPlaylistId: number | string,
254     componentPagination: ComponentPaginationLight
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
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     }
298
299     logger('Fetching from network for %d.', videoId)
300     return this.videoExistsInPlaylistNotifier.next(videoId)
301   }
302
303   extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
304     return this.serverService.getServerLocale()
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) {
321     return this.serverService.getServerLocale()
322                .pipe(map(translations => new VideoPlaylist(playlist, translations)))
323   }
324
325   extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
326     return this.serverService.getServerLocale()
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
342   private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
343     const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
344
345     let params = new HttpParams()
346     params = this.restService.addObjectParams(params, { videoIds })
347
348     return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
349                .pipe(catchError(err => this.restExtractor.handleError(err)))
350   }
351 }