1 import * as debug from 'debug'
2 import { Subject, Subscription } from 'rxjs'
3 import { debounceTime, filter } from 'rxjs/operators'
4 import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core'
5 import { AuthService, DisableForReuseHook, Notifier } from '@app/core'
6 import { FormReactive, FormReactiveService } from '@app/shared/shared-forms'
7 import { secondsToTime } from '@shared/core-utils'
12 VideoPlaylistElementCreate,
13 VideoPlaylistElementUpdate,
15 } from '@shared/models'
16 import { VIDEO_PLAYLIST_DISPLAY_NAME_VALIDATOR } from '../form-validators/video-playlist-validators'
17 import { CachedPlaylist, VideoPlaylistService } from './video-playlist.service'
19 const debugLogger = debug('peertube:playlists:VideoAddToPlaylistComponent')
21 type PlaylistElement = {
23 playlistElementId?: number
24 startTimestamp?: number
25 stopTimestamp?: number
28 type PlaylistSummary = {
31 optionalRowDisplayed: boolean
33 elements: PlaylistElement[]
37 selector: 'my-video-add-to-playlist',
38 styleUrls: [ './video-add-to-playlist.component.scss' ],
39 templateUrl: './video-add-to-playlist.component.html',
40 changeDetection: ChangeDetectionStrategy.OnPush
42 export class VideoAddToPlaylistComponent extends FormReactive implements OnInit, OnChanges, OnDestroy, DisableForReuseHook {
44 @Input() currentVideoTimestamp: number
45 @Input() lazyLoad = false
47 isNewPlaylistBlockOpened = false
49 videoPlaylistSearch: string
50 videoPlaylistSearchChanged = new Subject<void>()
52 videoPlaylists: PlaylistSummary[] = []
54 private disabled = false
56 private listenToPlaylistChangeSub: Subscription
57 private playlistsData: CachedPlaylist[] = []
59 private pendingAddId: number
62 protected formReactiveService: FormReactiveService,
63 private authService: AuthService,
64 private notifier: Notifier,
65 private videoPlaylistService: VideoPlaylistService,
66 private cd: ChangeDetectorRef
72 return this.authService.getUser()
77 displayName: VIDEO_PLAYLIST_DISPLAY_NAME_VALIDATOR
80 this.videoPlaylistService.listenToMyAccountPlaylistsChange()
81 .subscribe(result => {
82 this.playlistsData = result.data
84 this.videoPlaylistService.runPlaylistCheck(this.video.id)
87 this.videoPlaylistSearchChanged
88 .pipe(debounceTime(500))
89 .subscribe(() => this.load())
91 if (this.lazyLoad === false) this.load()
94 ngOnChanges (simpleChanges: SimpleChanges) {
95 if (simpleChanges['video']) {
101 this.unsubscribePlaylistChanges()
109 this.disabled = false
113 debugLogger('Reloading component')
115 this.videoPlaylists = []
116 this.videoPlaylistSearch = undefined
120 this.cd.markForCheck()
124 debugLogger('Loading component')
126 this.listenToVideoPlaylistChange()
128 this.videoPlaylistService.listMyPlaylistWithCache(this.user, this.videoPlaylistSearch)
129 .subscribe(playlistsResult => {
130 this.playlistsData = playlistsResult.data
132 this.videoPlaylistService.runPlaylistCheck(this.video.id)
136 openChange (opened: boolean) {
137 if (opened === false) {
138 this.isNewPlaylistBlockOpened = false
142 openCreateBlock (event: Event) {
143 event.preventDefault()
145 this.isNewPlaylistBlockOpened = true
148 toggleMainPlaylist (e: Event, playlist: PlaylistSummary) {
151 if (this.isPresentMultipleTimes(playlist) || playlist.optionalRowDisplayed) return
153 if (playlist.elements.length === 0) {
154 const element: PlaylistElement = {
156 playlistElementId: undefined,
158 stopTimestamp: this.video.duration
161 this.addVideoInPlaylist(playlist, element)
163 this.removeVideoFromPlaylist(playlist, playlist.elements[0].playlistElementId)
164 playlist.elements = []
167 this.cd.markForCheck()
170 toggleOptionalPlaylist (e: Event, playlist: PlaylistSummary, element: PlaylistElement, startTimestamp: number, stopTimestamp: number) {
173 if (element.enabled) {
174 this.removeVideoFromPlaylist(playlist, element.playlistElementId)
175 element.enabled = false
177 // Hide optional rows pane when the user unchecked all the playlists
178 if (this.isPrimaryCheckboxChecked(playlist) === false) {
179 playlist.optionalRowDisplayed = false
182 const element: PlaylistElement = {
184 playlistElementId: undefined,
189 this.addVideoInPlaylist(playlist, element)
192 this.cd.markForCheck()
196 const displayName = this.form.value['displayName']
198 const videoPlaylistCreate: VideoPlaylistCreate = {
200 privacy: VideoPlaylistPrivacy.PRIVATE
203 this.videoPlaylistService.createVideoPlaylist(videoPlaylistCreate)
206 this.isNewPlaylistBlockOpened = false
208 this.cd.markForCheck()
211 error: err => this.notifier.error(err.message)
215 onVideoPlaylistSearchChanged () {
216 this.videoPlaylistSearchChanged.next()
219 isPrimaryCheckboxChecked (playlist: PlaylistSummary) {
220 // Reduce latency when adding a video to a playlist using pendingAddId
221 return this.pendingAddId === playlist.id ||
222 playlist.elements.filter(e => e.enabled).length !== 0
225 toggleOptionalRow (playlist: PlaylistSummary) {
226 playlist.optionalRowDisplayed = !playlist.optionalRowDisplayed
228 this.cd.markForCheck()
231 getPrimaryInputName (playlist: PlaylistSummary) {
232 return 'in-playlist-primary-' + playlist.id
235 getOptionalInputName (playlist: PlaylistSummary, element?: PlaylistElement) {
236 const suffix = element
237 ? '-' + element.playlistElementId
240 return 'in-playlist-optional-' + playlist.id + suffix
243 buildOptionalRowElements (playlist: PlaylistSummary) {
244 const elements = playlist.elements
246 const lastElement = elements.length === 0
248 : elements[elements.length - 1]
250 // Build an empty last element
251 if (!lastElement || lastElement.enabled === true) {
255 stopTimestamp: this.video.duration
262 isPresentMultipleTimes (playlist: PlaylistSummary) {
263 return playlist.elements.filter(e => e.enabled === true).length > 1
266 onElementTimestampUpdate (playlist: PlaylistSummary, element: PlaylistElement) {
267 if (!element.playlistElementId || element.enabled === false) return
269 const body: VideoPlaylistElementUpdate = {
270 startTimestamp: element.startTimestamp,
271 stopTimestamp: element.stopTimestamp
274 this.videoPlaylistService.updateVideoOfPlaylist(playlist.id, element.playlistElementId, body, this.video.id)
277 this.notifier.success($localize`Timestamps updated`)
280 error: err => this.notifier.error(err.message),
282 complete: () => this.cd.markForCheck()
286 private isOptionalRowDisplayed (playlist: PlaylistSummary) {
287 const elements = playlist.elements.filter(e => e.enabled)
289 if (elements.length > 1) return true
291 if (elements.length === 1) {
292 const element = elements[0]
295 (element.startTimestamp && element.startTimestamp !== 0) ||
296 (element.stopTimestamp && element.stopTimestamp !== this.video.duration)
305 private removeVideoFromPlaylist (playlist: PlaylistSummary, elementId: number) {
306 this.videoPlaylistService.removeVideoFromPlaylist(playlist.id, elementId, this.video.id)
309 this.notifier.success($localize`Video removed from ${playlist.displayName}`)
312 error: err => this.notifier.error(err.message),
314 complete: () => this.cd.markForCheck()
318 private listenToVideoPlaylistChange () {
319 this.unsubscribePlaylistChanges()
321 this.listenToPlaylistChangeSub = this.videoPlaylistService.listenToVideoPlaylistChange(this.video.id)
322 .pipe(filter(() => this.disabled === false))
323 .subscribe(existResult => this.rebuildPlaylists(existResult))
326 private unsubscribePlaylistChanges () {
327 if (this.listenToPlaylistChangeSub) {
328 this.listenToPlaylistChangeSub.unsubscribe()
329 this.listenToPlaylistChangeSub = undefined
333 private rebuildPlaylists (existResult: VideoExistInPlaylist[]) {
334 debugLogger('Got existing results for %d.', this.video.id, existResult)
336 const oldPlaylists = this.videoPlaylists
338 this.videoPlaylists = []
339 for (const playlist of this.playlistsData) {
340 const existingPlaylists = existResult.filter(p => p.playlistId === playlist.id)
342 const playlistSummary = {
344 optionalRowDisplayed: false,
345 displayName: playlist.displayName,
346 elements: existingPlaylists.map(e => ({
348 playlistElementId: e.playlistElementId,
349 startTimestamp: e.startTimestamp || 0,
350 stopTimestamp: e.stopTimestamp || this.video.duration
354 const oldPlaylist = oldPlaylists.find(p => p.id === playlist.id)
355 playlistSummary.optionalRowDisplayed = oldPlaylist
356 ? oldPlaylist.optionalRowDisplayed
357 : this.isOptionalRowDisplayed(playlistSummary)
359 this.videoPlaylists.push(playlistSummary)
362 debugLogger('Rebuilt playlist state for video %d.', this.video.id, this.videoPlaylists)
364 this.cd.markForCheck()
367 private addVideoInPlaylist (playlist: PlaylistSummary, element: PlaylistElement) {
368 const body: VideoPlaylistElementCreate = { videoId: this.video.id }
370 if (element.startTimestamp) body.startTimestamp = element.startTimestamp
371 if (element.stopTimestamp && element.stopTimestamp !== this.video.duration) body.stopTimestamp = element.stopTimestamp
373 this.pendingAddId = playlist.id
375 this.videoPlaylistService.addVideoInPlaylist(playlist.id, body)
378 const message = body.startTimestamp || body.stopTimestamp
379 ? $localize`Video added in ${playlist.displayName} at timestamps ${this.formatTimestamp(element)}`
380 : $localize`Video added in ${playlist.displayName}`
382 this.notifier.success(message)
384 if (element) element.playlistElementId = res.videoPlaylistElement.id
388 this.pendingAddId = undefined
389 this.cd.markForCheck()
391 this.notifier.error(err.message)
395 this.pendingAddId = undefined
396 this.cd.markForCheck()
401 private formatTimestamp (element: PlaylistElement) {
402 const start = element.startTimestamp ? secondsToTime(element.startTimestamp) : ''
403 const stop = element.stopTimestamp ? secondsToTime(element.stopTimestamp) : ''
405 return `(${start}-${stop})`