1 import * as debug from 'debug'
2 import { fromEvent, Observable, Subject, Subscription } from 'rxjs'
3 import { debounceTime, switchMap } from 'rxjs/operators'
4 import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges } from '@angular/core'
5 import { ActivatedRoute } from '@angular/router'
6 import { AuthService, ComponentPaginationLight, Notifier, PeerTubeRouterService, ScreenService, User, UserService } from '@app/core'
7 import { GlobalIconName } from '@app/shared/shared-icons'
8 import { isLastMonth, isLastWeek, isThisMonth, isToday, isYesterday } from '@shared/core-utils'
9 import { ResultList, UserRight, VideoSortField } from '@shared/models'
10 import { Syndication, Video } from '../shared-main'
11 import { VideoFilters, VideoFilterScope } from './video-filters.model'
12 import { MiniatureDisplayOptions } from './video-miniature.component'
14 const logger = debug('peertube:videos:VideosListComponent')
16 export type HeaderAction = {
17 iconName: GlobalIconName
22 click?: (e: Event) => void
36 selector: 'my-videos-list',
37 templateUrl: './videos-list.component.html',
38 styleUrls: [ './videos-list.component.scss' ]
40 export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
41 @Input() getVideosObservableFunction: (pagination: ComponentPaginationLight, filters: VideoFilters) => Observable<ResultList<Video>>
42 @Input() getSyndicationItemsFunction: (filters: VideoFilters) => Promise<Syndication[]> | Syndication[]
43 @Input() baseRouteBuilderFunction: (filters: VideoFilters) => string[]
45 @Input() title: string
46 @Input() titleTooltip: string
47 @Input() displayTitle = true
49 @Input() defaultSort: VideoSortField
50 @Input() defaultScope: VideoFilterScope = 'federated'
51 @Input() displayFilters = false
52 @Input() displayModerationBlock = false
54 @Input() loadUserVideoPreferences = false
56 @Input() displayAsRow = false
57 @Input() displayVideoActions = true
58 @Input() groupByDate = false
60 @Input() headerActions: HeaderAction[] = []
62 @Input() hideScopeFilter = false
64 @Input() displayOptions: MiniatureDisplayOptions = {
75 @Input() disabled = false
77 @Output() filtersChanged = new EventEmitter<VideoFilters>()
81 syndicationItems: Syndication[]
83 onDataSubject = new Subject<any[]>()
84 hasDoneFirstQuery = false
88 private routeSub: Subscription
89 private userSub: Subscription
90 private resizeSub: Subscription
92 private pagination: ComponentPaginationLight = {
97 private groupedDateLabels: { [id in GroupDate]: string }
98 private groupedDates: { [id: number]: GroupDate } = {}
100 private lastQueryLength: number
103 private notifier: Notifier,
104 private authService: AuthService,
105 private userService: UserService,
106 private route: ActivatedRoute,
107 private screenService: ScreenService,
108 private peertubeRouter: PeerTubeRouterService
114 const hiddenFilters = this.hideScopeFilter
118 this.filters = new VideoFilters(this.defaultSort, this.defaultScope, hiddenFilters)
119 this.filters.load({ ...this.route.snapshot.queryParams, scope: this.defaultScope })
121 this.groupedDateLabels = {
122 [GroupDate.UNKNOWN]: null,
123 [GroupDate.TODAY]: $localize`Today`,
124 [GroupDate.YESTERDAY]: $localize`Yesterday`,
125 [GroupDate.THIS_WEEK]: $localize`This week`,
126 [GroupDate.THIS_MONTH]: $localize`This month`,
127 [GroupDate.LAST_MONTH]: $localize`Last month`,
128 [GroupDate.OLDER]: $localize`Older`
131 this.resizeSub = fromEvent(window, 'resize')
132 .pipe(debounceTime(500))
133 .subscribe(() => this.calcPageSizes())
137 this.userService.getAnonymousOrLoggedUser()
139 this.userMiniature = user
141 if (this.loadUserVideoPreferences) {
142 this.loadUserSettings(user)
145 this.scheduleOnFiltersChanged(false)
147 this.subscribeToAnonymousUpdate()
148 this.subscribeToSearchChange()
151 // Display avatar in mobile view
152 if (this.screenService.isInMobileView()) {
153 this.displayOptions.avatar = true
158 if (this.resizeSub) this.resizeSub.unsubscribe()
159 if (this.routeSub) this.routeSub.unsubscribe()
160 if (this.userSub) this.userSub.unsubscribe()
163 ngOnChanges (changes: SimpleChanges) {
164 if (!this.filters) return
168 if (changes['defaultScope']) {
170 this.filters.setDefaultScope(this.defaultScope)
173 if (changes['defaultSort']) {
175 this.filters.setDefaultSort(this.defaultSort)
180 const customizedByUser = this.hasBeenCustomizedByUser()
182 if (!customizedByUser) {
183 if (this.loadUserVideoPreferences) {
184 this.loadUserSettings(this.userMiniature)
187 this.filters.reset('scope')
188 this.filters.reset('sort')
191 this.scheduleOnFiltersChanged(customizedByUser)
194 videoById (_index: number, video: Video) {
199 if (this.disabled) return
202 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
204 this.pagination.currentPage += 1
206 this.loadMoreVideos()
209 loadMoreVideos (reset = false) {
210 if (reset) this.hasDoneFirstQuery = false
212 this.getVideosObservableFunction(this.pagination, this.filters)
214 next: ({ data }) => {
215 this.hasDoneFirstQuery = true
216 this.lastQueryLength = data.length
218 if (reset) this.videos = []
219 this.videos = this.videos.concat(data)
221 if (this.groupByDate) this.buildGroupedDateLabels()
223 this.onDataSubject.next(data)
227 const message = $localize`Cannot load more videos. Try again later.`
229 console.error(message, { err })
230 this.notifier.error(message)
236 this.pagination.currentPage = 1
237 this.loadMoreVideos(true)
240 removeVideoFromArray (video: Video) {
241 this.videos = this.videos.filter(v => v.id !== video.id)
244 buildGroupedDateLabels () {
245 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
249 value: GroupDate.TODAY,
250 validator: (d: Date) => isToday(d)
253 value: GroupDate.YESTERDAY,
254 validator: (d: Date) => isYesterday(d)
257 value: GroupDate.THIS_WEEK,
258 validator: (d: Date) => isLastWeek(d)
261 value: GroupDate.THIS_MONTH,
262 validator: (d: Date) => isThisMonth(d)
265 value: GroupDate.LAST_MONTH,
266 validator: (d: Date) => isLastMonth(d)
269 value: GroupDate.OLDER,
270 validator: () => true
274 for (const video of this.videos) {
275 const publishedDate = video.publishedAt
277 for (let i = 0; i < periods.length; i++) {
278 const period = periods[i]
280 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
282 if (currentGroupedDate !== period.value) {
283 currentGroupedDate = period.value
284 this.groupedDates[video.id] = currentGroupedDate
293 getCurrentGroupedDateLabel (video: Video) {
294 if (this.groupByDate === false) return undefined
296 return this.groupedDateLabels[this.groupedDates[video.id]]
299 scheduleOnFiltersChanged (customizedByUser: boolean) {
300 // We'll reload videos, but avoid weird UI effect
303 setTimeout(() => this.onFiltersChanged(customizedByUser))
306 onFiltersChanged (customizedByUser: boolean) {
307 logger('Running on filters changed')
309 this.updateUrl(customizedByUser)
311 this.filters.triggerChange()
313 this.reloadSyndicationItems()
317 protected enableAllFilterIfPossible () {
318 if (!this.authService.isLoggedIn()) return
320 this.authService.userInformationLoaded
322 const user = this.authService.getUser()
323 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
327 private calcPageSizes () {
328 if (this.screenService.isInMobileView()) {
329 this.pagination.itemsPerPage = 5
333 private loadUserSettings (user: User) {
334 this.filters.setNSFWPolicy(user.nsfwPolicy)
336 // Don't reset language filter if we don't want to refresh the component
337 if (!this.hasBeenCustomizedByUser()) {
338 this.filters.load({ languageOneOf: user.videoLanguages })
342 private reloadSyndicationItems () {
343 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
345 if (!items || items.length === 0) this.syndicationItems = undefined
346 else this.syndicationItems = items
348 .catch(err => console.error('Cannot get syndication items.', err))
351 private updateUrl (customizedByUser: boolean) {
352 const baseQuery = this.filters.toUrlObject()
354 // Set or reset customized by user query param
355 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
356 ? { ...baseQuery, c: customizedByUser }
359 logger('Will inject %O in URL query', queryParams)
361 const baseRoute = this.baseRouteBuilderFunction
362 ? this.baseRouteBuilderFunction(this.filters)
365 const pathname = window.location.pathname
367 const baseRouteChanged = baseRoute.length !== 0 &&
368 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
369 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
371 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
372 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
375 this.filtersChanged.emit(this.filters)
378 private hasBeenCustomizedByUser () {
379 return this.route.snapshot.queryParams['c'] === 'true'
382 private subscribeToAnonymousUpdate () {
383 this.userSub = this.userService.listenAnonymousUpdate()
384 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
386 if (this.loadUserVideoPreferences) {
387 this.loadUserSettings(user)
390 if (this.hasDoneFirstQuery) {
396 private subscribeToSearchChange () {
397 this.routeSub = this.route.queryParams.subscribe(param => {
398 if (!param['search']) return
400 this.filters.load({ search: param['search'] })
401 this.onFiltersChanged(true)