]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-video-playlist/video-playlist.service.ts
Display video actions in homepage
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-playlist / video-playlist.service.ts
CommitLineData
67ed6552 1import * as debug from 'debug'
3da38d6e
C
2import { merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
3import { catchError, filter, map, share, switchMap, tap } from 'rxjs/operators'
9744bb2a 4import { HttpClient, HttpContext, HttpParams } from '@angular/common/http'
afb7d2d5 5import { Injectable } from '@angular/core'
37b1d97f 6import { AuthService, AuthUser, ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'
3da38d6e 7import { buildBulkObservable, objectToFormData } from '@app/helpers'
67ed6552 8import { Account, AccountService, VideoChannel, VideoChannelService } from '@app/shared/shared-main'
9744bb2a 9import { NGX_LOADING_BAR_IGNORED } from '@ngx-loading-bar/http-client'
67ed6552 10import {
38a3ccc7 11 CachedVideoExistInPlaylist,
12 CachedVideosExistInPlaylists,
67ed6552
C
13 ResultList,
14 VideoExistInPlaylist,
15 VideoPlaylist as VideoPlaylistServerModel,
16 VideoPlaylistCreate,
17 VideoPlaylistElement as ServerVideoPlaylistElement,
18 VideoPlaylistElementCreate,
19 VideoPlaylistElementUpdate,
20 VideoPlaylistReorder,
21 VideoPlaylistUpdate,
22 VideosExistInPlaylists
23} from '@shared/models'
830b4faf 24import { environment } from '../../../environments/environment'
67ed6552
C
25import { VideoPlaylistElement } from './video-playlist-element.model'
26import { VideoPlaylist } from './video-playlist.model'
51b34a11 27
42b40636 28const debugLogger = debug('peertube:playlists:VideoPlaylistService')
51b34a11 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 38 private videoExistsInPlaylistNotifier = new ReplaySubject<number>(1)
38a3ccc7 39 private videoExistsInPlaylistCacheSubject = new Subject<CachedVideosExistInPlaylists>()
40 private readonly videoExistsInPlaylistObservable: Observable<CachedVideosExistInPlaylists>
51b34a11 41
38a3ccc7 42 private videoExistsObservableCache: { [ id: number ]: Observable<CachedVideoExistInPlaylist[]> } = {}
43 private videoExistsCache: { [ id: number ]: CachedVideoExistInPlaylist[] } = {}
51b34a11
C
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,
37b1d97f 51 private auth: AuthService,
830b4faf 52 private serverService: ServerService,
f0a39880 53 private restExtractor: RestExtractor,
afb7d2d5 54 private restService: RestService
f0a39880 55 ) {
51b34a11 56 this.videoExistsInPlaylistObservable = merge(
3da38d6e
C
57 buildBulkObservable({
58 time: 500,
37b1d97f
C
59 bulkGet: (videoIds: number[]) => {
60 // We added a delay to the request, so ensure the user is still logged in
61 if (this.auth.isLoggedIn()) {
62 return this.doVideosExistInPlaylist(videoIds)
63 }
64
65 return of({})
66 },
3da38d6e 67 notifierObservable: this.videoExistsInPlaylistNotifier
2cc276f9 68 }).pipe(map(({ response }) => response)),
51b34a11
C
69
70 this.videoExistsInPlaylistCacheSubject
f0a39880
C
71 )
72 }
830b4faf 73
440d39c5 74 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
830b4faf 75 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
4beda9e1 76 const pagination = this.restService.componentToRestPagination(componentPagination)
830b4faf 77
ad453580
C
78 let params = new HttpParams()
79 params = this.restService.addRestGetParams(params, pagination)
80
81 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
830b4faf
C
82 .pipe(
83 switchMap(res => this.extractPlaylists(res)),
84 catchError(err => this.restExtractor.handleError(err))
85 )
86 }
87
51b34a11 88 listMyPlaylistWithCache (user: AuthUser, search?: string) {
6b0c3c7c 89 if (!search) {
f44a284a 90 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
6b0c3c7c
C
91 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
92 }
93
f44a284a 94 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
51b34a11
C
95 .pipe(
96 tap(result => {
6b0c3c7c 97 if (!search) {
f44a284a 98 this.myAccountPlaylistCacheRunning = undefined
6b0c3c7c
C
99 this.myAccountPlaylistCache = result
100 }
f44a284a
C
101 }),
102 share()
51b34a11 103 )
f44a284a
C
104
105 if (!search) this.myAccountPlaylistCacheRunning = obs
106 return obs
51b34a11
C
107 }
108
c06af501
RK
109 listAccountPlaylists (
110 account: Account,
440d39c5 111 componentPagination: ComponentPaginationLight,
c06af501
RK
112 sort: string,
113 search?: string
114 ): Observable<ResultList<VideoPlaylist>> {
830b4faf 115 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
ad453580 116 const pagination = componentPagination
4beda9e1 117 ? this.restService.componentToRestPagination(componentPagination)
ad453580 118 : undefined
830b4faf 119
f0a39880 120 let params = new HttpParams()
ad453580 121 params = this.restService.addRestGetParams(params, pagination, sort)
c06af501 122 if (search) params = this.restService.addObjectParams(params, { search })
f0a39880
C
123
124 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
830b4faf
C
125 .pipe(
126 switchMap(res => this.extractPlaylists(res)),
127 catchError(err => this.restExtractor.handleError(err))
128 )
129 }
130
131 getVideoPlaylist (id: string | number) {
132 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
133
134 return this.authHttp.get<VideoPlaylist>(url)
135 .pipe(
136 switchMap(res => this.extractPlaylist(res)),
137 catchError(err => this.restExtractor.handleError(err))
138 )
139 }
140
141 createVideoPlaylist (body: VideoPlaylistCreate) {
142 const data = objectToFormData(body)
143
f0a39880 144 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
830b4faf 145 .pipe(
51b34a11 146 tap(res => {
ec10e8ed
C
147 if (!this.myAccountPlaylistCache) return
148
51b34a11
C
149 this.myAccountPlaylistCache.total++
150
151 this.myAccountPlaylistCache.data.push({
152 id: res.videoPlaylist.id,
153 displayName: body.displayName
154 })
155
156 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
157 }),
830b4faf
C
158 catchError(err => this.restExtractor.handleError(err))
159 )
160 }
161
162 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
163 const data = objectToFormData(body)
164
165 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
166 .pipe(
51b34a11 167 tap(() => {
ec10e8ed
C
168 if (!this.myAccountPlaylistCache) return
169
51b34a11
C
170 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
171 playlist.displayName = body.displayName
172
173 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
174 }),
830b4faf
C
175 catchError(err => this.restExtractor.handleError(err))
176 )
177 }
178
179 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
180 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
181 .pipe(
51b34a11 182 tap(() => {
ec10e8ed
C
183 if (!this.myAccountPlaylistCache) return
184
51b34a11
C
185 this.myAccountPlaylistCache.total--
186 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
187 .filter(p => p.id !== videoPlaylist.id)
188
189 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
190 }),
830b4faf
C
191 catchError(err => this.restExtractor.handleError(err))
192 )
193 }
194
f0a39880 195 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
a3671f07
C
196 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
197
198 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
51b34a11
C
199 .pipe(
200 tap(res => {
201 const existsResult = this.videoExistsCache[body.videoId]
202 existsResult.push({
203 playlistId,
204 playlistElementId: res.videoPlaylistElement.id,
205 startTimestamp: body.startTimestamp,
206 stopTimestamp: body.stopTimestamp
207 })
208
209 this.runPlaylistCheck(body.videoId)
210 }),
211 catchError(err => this.restExtractor.handleError(err))
212 )
f0a39880
C
213 }
214
51b34a11 215 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
bfbd9128 216 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
f0a39880 217 .pipe(
51b34a11
C
218 tap(() => {
219 const existsResult = this.videoExistsCache[videoId]
51b34a11 220
50a1e91d
C
221 if (existsResult) {
222 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
223
224 elem.startTimestamp = body.startTimestamp
225 elem.stopTimestamp = body.stopTimestamp
226 }
51b34a11
C
227
228 this.runPlaylistCheck(videoId)
229 }),
f0a39880
C
230 catchError(err => this.restExtractor.handleError(err))
231 )
232 }
233
51b34a11 234 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
bfbd9128 235 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
f0a39880 236 .pipe(
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)
e8bffe96 258 .pipe(catchError(err => this.restExtractor.handleError(err)))
15e9d5ca
C
259 }
260
c3bb0441 261 getPlaylistVideos (options: {
262 videoPlaylistId: number | string
440d39c5 263 componentPagination: ComponentPaginationLight
c3bb0441 264 }): Observable<ResultList<VideoPlaylistElement>> {
265 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + options.videoPlaylistId + '/videos'
4beda9e1 266 const pagination = this.restService.componentToRestPagination(options.componentPagination)
bfbd9128
C
267
268 let params = new HttpParams()
269 params = this.restService.addRestGetParams(params, pagination)
270
271 return this.authHttp
272 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
273 .pipe(
274 switchMap(res => this.extractVideoPlaylistElements(res)),
275 catchError(err => this.restExtractor.handleError(err))
276 )
277 }
278
51b34a11
C
279 listenToMyAccountPlaylistsChange () {
280 return this.myAccountPlaylistCacheSubject.asObservable()
281 }
282
283 listenToVideoPlaylistChange (videoId: number) {
9df52d66
C
284 if (this.videoExistsObservableCache[videoId]) {
285 return this.videoExistsObservableCache[videoId]
51b34a11
C
286 }
287
288 const obs = this.videoExistsInPlaylistObservable
289 .pipe(
9df52d66 290 map(existsResult => existsResult[videoId]),
51b34a11 291 filter(r => !!r),
9df52d66 292 tap(result => this.videoExistsCache[videoId] = result)
51b34a11
C
293 )
294
9df52d66 295 this.videoExistsObservableCache[videoId] = obs
51b34a11
C
296 return obs
297 }
298
299 runPlaylistCheck (videoId: number) {
42b40636 300 debugLogger('Running playlist check.')
51b34a11
C
301
302 if (this.videoExistsCache[videoId]) {
42b40636 303 debugLogger('Found cache for %d.', videoId)
51b34a11
C
304
305 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
306 }
f0a39880 307
42b40636 308 debugLogger('Fetching from network for %d.', videoId)
51b34a11 309 return this.videoExistsInPlaylistNotifier.next(videoId)
f0a39880
C
310 }
311
830b4faf 312 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
ba430d75 313 return this.serverService.getServerLocale()
830b4faf
C
314 .pipe(
315 map(translations => {
316 const playlistsJSON = result.data
317 const total = result.total
318 const playlists: VideoPlaylist[] = []
319
320 for (const playlistJSON of playlistsJSON) {
321 playlists.push(new VideoPlaylist(playlistJSON, translations))
322 }
323
324 return { data: playlists, total }
325 })
326 )
327 }
328
329 extractPlaylist (playlist: VideoPlaylistServerModel) {
ba430d75 330 return this.serverService.getServerLocale()
830b4faf
C
331 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
332 }
f0a39880 333
bfbd9128 334 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
ba430d75 335 return this.serverService.getServerLocale()
bfbd9128
C
336 .pipe(
337 map(translations => {
338 const elementsJson = result.data
339 const total = result.total
340 const elements: VideoPlaylistElement[] = []
341
342 for (const elementJson of elementsJson) {
343 elements.push(new VideoPlaylistElement(elementJson, translations))
344 }
345
346 return { total, data: elements }
347 })
348 )
349 }
350
38a3ccc7 351 doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
f0a39880 352 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
f0a39880 353
c06af501 354 let params = new HttpParams()
f0a39880
C
355 params = this.restService.addObjectParams(params, { videoIds })
356
9744bb2a 357 return this.authHttp.get<VideoExistInPlaylist>(url, { params, context: new HttpContext().set(NGX_LOADING_BAR_IGNORED, true) })
f0a39880
C
358 .pipe(catchError(err => this.restExtractor.handleError(err)))
359 }
830b4faf 360}