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