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 this.getVideosObservableFunction(this.pagination, this.filters)
212 next: ({ data }) => {
213 this.hasDoneFirstQuery = true
214 this.lastQueryLength = data.length
216 if (reset) this.videos = []
217 this.videos = this.videos.concat(data)
219 if (this.groupByDate) this.buildGroupedDateLabels()
221 this.onDataSubject.next(data)
225 const message = $localize`Cannot load more videos. Try again later.`
227 console.error(message, { err })
228 this.notifier.error(message)
234 this.pagination.currentPage = 1
235 this.loadMoreVideos(true)
238 removeVideoFromArray (video: Video) {
239 this.videos = this.videos.filter(v => v.id !== video.id)
242 buildGroupedDateLabels () {
243 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
247 value: GroupDate.TODAY,
248 validator: (d: Date) => isToday(d)
251 value: GroupDate.YESTERDAY,
252 validator: (d: Date) => isYesterday(d)
255 value: GroupDate.THIS_WEEK,
256 validator: (d: Date) => isLastWeek(d)
259 value: GroupDate.THIS_MONTH,
260 validator: (d: Date) => isThisMonth(d)
263 value: GroupDate.LAST_MONTH,
264 validator: (d: Date) => isLastMonth(d)
267 value: GroupDate.OLDER,
268 validator: () => true
272 for (const video of this.videos) {
273 const publishedDate = video.publishedAt
275 for (let i = 0; i < periods.length; i++) {
276 const period = periods[i]
278 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
280 if (currentGroupedDate !== period.value) {
281 currentGroupedDate = period.value
282 this.groupedDates[video.id] = currentGroupedDate
291 getCurrentGroupedDateLabel (video: Video) {
292 if (this.groupByDate === false) return undefined
294 return this.groupedDateLabels[this.groupedDates[video.id]]
297 scheduleOnFiltersChanged (customizedByUser: boolean) {
298 // We'll reload videos, but avoid weird UI effect
301 setTimeout(() => this.onFiltersChanged(customizedByUser))
304 onFiltersChanged (customizedByUser: boolean) {
305 logger('Running on filters changed')
307 this.updateUrl(customizedByUser)
309 this.filters.triggerChange()
311 this.reloadSyndicationItems()
315 protected enableAllFilterIfPossible () {
316 if (!this.authService.isLoggedIn()) return
318 this.authService.userInformationLoaded
320 const user = this.authService.getUser()
321 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
325 private calcPageSizes () {
326 if (this.screenService.isInMobileView()) {
327 this.pagination.itemsPerPage = 5
331 private loadUserSettings (user: User) {
332 this.filters.setNSFWPolicy(user.nsfwPolicy)
334 // Don't reset language filter if we don't want to refresh the component
335 if (!this.hasBeenCustomizedByUser()) {
336 this.filters.load({ languageOneOf: user.videoLanguages })
340 private reloadSyndicationItems () {
341 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
343 if (!items || items.length === 0) this.syndicationItems = undefined
344 else this.syndicationItems = items
346 .catch(err => console.error('Cannot get syndication items.', err))
349 private updateUrl (customizedByUser: boolean) {
350 const baseQuery = this.filters.toUrlObject()
352 // Set or reset customized by user query param
353 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
354 ? { ...baseQuery, c: customizedByUser }
357 logger('Will inject %O in URL query', queryParams)
359 const baseRoute = this.baseRouteBuilderFunction
360 ? this.baseRouteBuilderFunction(this.filters)
363 const pathname = window.location.pathname
365 const baseRouteChanged = baseRoute.length !== 0 &&
366 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
367 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
369 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
370 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
373 this.filtersChanged.emit(this.filters)
376 private hasBeenCustomizedByUser () {
377 return this.route.snapshot.queryParams['c'] === 'true'
380 private subscribeToAnonymousUpdate () {
381 this.userSub = this.userService.listenAnonymousUpdate()
382 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
384 if (this.loadUserVideoPreferences) {
385 this.loadUserSettings(user)
388 if (this.hasDoneFirstQuery) {
394 private subscribeToSearchChange () {
395 this.routeSub = this.route.queryParams.subscribe(param => {
396 if (!param['search']) return
398 this.filters.load({ search: param['search'] })
399 this.onFiltersChanged(true)