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