]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/video-playlist/video-playlist.service.ts
Add bulk comment actions on account dropdown
[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 143 tap(res => {
ec10e8ed
C
144 if (!this.myAccountPlaylistCache) return
145
51b34a11
C
146 this.myAccountPlaylistCache.total++
147
148 this.myAccountPlaylistCache.data.push({
149 id: res.videoPlaylist.id,
150 displayName: body.displayName
151 })
152
153 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
154 }),
830b4faf
C
155 catchError(err => this.restExtractor.handleError(err))
156 )
157 }
158
159 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
160 const data = objectToFormData(body)
161
162 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
163 .pipe(
164 map(this.restExtractor.extractDataBool),
51b34a11 165 tap(() => {
ec10e8ed
C
166 if (!this.myAccountPlaylistCache) return
167
51b34a11
C
168 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
169 playlist.displayName = body.displayName
170
171 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
172 }),
830b4faf
C
173 catchError(err => this.restExtractor.handleError(err))
174 )
175 }
176
177 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
178 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
179 .pipe(
180 map(this.restExtractor.extractDataBool),
51b34a11 181 tap(() => {
ec10e8ed
C
182 if (!this.myAccountPlaylistCache) return
183
51b34a11
C
184 this.myAccountPlaylistCache.total--
185 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
186 .filter(p => p.id !== videoPlaylist.id)
187
188 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
189 }),
830b4faf
C
190 catchError(err => this.restExtractor.handleError(err))
191 )
192 }
193
f0a39880 194 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
a3671f07
C
195 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
196
197 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
51b34a11
C
198 .pipe(
199 tap(res => {
200 const existsResult = this.videoExistsCache[body.videoId]
201 existsResult.push({
202 playlistId,
203 playlistElementId: res.videoPlaylistElement.id,
204 startTimestamp: body.startTimestamp,
205 stopTimestamp: body.stopTimestamp
206 })
207
208 this.runPlaylistCheck(body.videoId)
209 }),
210 catchError(err => this.restExtractor.handleError(err))
211 )
f0a39880
C
212 }
213
51b34a11 214 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
bfbd9128 215 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
f0a39880
C
216 .pipe(
217 map(this.restExtractor.extractDataBool),
51b34a11
C
218 tap(() => {
219 const existsResult = this.videoExistsCache[videoId]
220 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
221
222 elem.startTimestamp = body.startTimestamp
223 elem.stopTimestamp = body.stopTimestamp
224
225 this.runPlaylistCheck(videoId)
226 }),
f0a39880
C
227 catchError(err => this.restExtractor.handleError(err))
228 )
229 }
230
51b34a11 231 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
bfbd9128 232 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
f0a39880
C
233 .pipe(
234 map(this.restExtractor.extractDataBool),
51b34a11
C
235 tap(() => {
236 if (!videoId) return
237
238 this.videoExistsCache[videoId] = this.videoExistsCache[videoId].filter(e => e.playlistElementId !== playlistElementId)
239 this.runPlaylistCheck(videoId)
240 }),
f0a39880
C
241 catchError(err => this.restExtractor.handleError(err))
242 )
243 }
244
15e9d5ca
C
245 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
246 const body: VideoPlaylistReorder = {
247 startPosition: oldPosition,
248 insertAfterPosition: newPosition
249 }
250
251 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
252 .pipe(
253 map(this.restExtractor.extractDataBool),
254 catchError(err => this.restExtractor.handleError(err))
255 )
256 }
257
bfbd9128
C
258 getPlaylistVideos (
259 videoPlaylistId: number | string,
440d39c5 260 componentPagination: ComponentPaginationLight
bfbd9128
C
261 ): Observable<ResultList<VideoPlaylistElement>> {
262 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylistId + '/videos'
263 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
264
265 let params = new HttpParams()
266 params = this.restService.addRestGetParams(params, pagination)
267
268 return this.authHttp
269 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
270 .pipe(
271 switchMap(res => this.extractVideoPlaylistElements(res)),
272 catchError(err => this.restExtractor.handleError(err))
273 )
274 }
275
51b34a11
C
276 listenToMyAccountPlaylistsChange () {
277 return this.myAccountPlaylistCacheSubject.asObservable()
278 }
279
280 listenToVideoPlaylistChange (videoId: number) {
281 if (this.videoExistsObservableCache[ videoId ]) {
282 return this.videoExistsObservableCache[ videoId ]
283 }
284
285 const obs = this.videoExistsInPlaylistObservable
286 .pipe(
287 map(existsResult => existsResult[ videoId ]),
288 filter(r => !!r),
289 tap(result => this.videoExistsCache[ videoId ] = result)
290 )
291
292 this.videoExistsObservableCache[ videoId ] = obs
293 return obs
294 }
295
296 runPlaylistCheck (videoId: number) {
297 logger('Running playlist check.')
298
299 if (this.videoExistsCache[videoId]) {
300 logger('Found cache for %d.', videoId)
301
302 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
303 }
f0a39880 304
51b34a11
C
305 logger('Fetching from network for %d.', videoId)
306 return this.videoExistsInPlaylistNotifier.next(videoId)
f0a39880
C
307 }
308
830b4faf 309 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
ba430d75 310 return this.serverService.getServerLocale()
830b4faf
C
311 .pipe(
312 map(translations => {
313 const playlistsJSON = result.data
314 const total = result.total
315 const playlists: VideoPlaylist[] = []
316
317 for (const playlistJSON of playlistsJSON) {
318 playlists.push(new VideoPlaylist(playlistJSON, translations))
319 }
320
321 return { data: playlists, total }
322 })
323 )
324 }
325
326 extractPlaylist (playlist: VideoPlaylistServerModel) {
ba430d75 327 return this.serverService.getServerLocale()
830b4faf
C
328 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
329 }
f0a39880 330
bfbd9128 331 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
ba430d75 332 return this.serverService.getServerLocale()
bfbd9128
C
333 .pipe(
334 map(translations => {
335 const elementsJson = result.data
336 const total = result.total
337 const elements: VideoPlaylistElement[] = []
338
339 for (const elementJson of elementsJson) {
340 elements.push(new VideoPlaylistElement(elementJson, translations))
341 }
342
343 return { total, data: elements }
344 })
345 )
346 }
347
51b34a11 348 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
f0a39880 349 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
f0a39880 350
c06af501 351 let params = new HttpParams()
f0a39880
C
352 params = this.restService.addObjectParams(params, { videoIds })
353
b7819090 354 return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
f0a39880
C
355 .pipe(catchError(err => this.restExtractor.handleError(err)))
356 }
830b4faf 357}