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'
8 ComponentPaginationLight,
10 PeerTubeRouterService,
16 import { GlobalIconName } from '@app/shared/shared-icons'
17 import { logger } from '@root-helpers/logger'
18 import { isLastMonth, isLastWeek, isThisMonth, isToday, isYesterday } from '@shared/core-utils'
19 import { ResultList, UserRight, VideoSortField } from '@shared/models'
20 import { Syndication, Video } from '../shared-main'
21 import { VideoFilters, VideoFilterScope } from './video-filters.model'
22 import { MiniatureDisplayOptions } from './video-miniature.component'
24 const debugLogger = debug('peertube:videos:VideosListComponent')
26 export type HeaderAction = {
27 iconName: GlobalIconName
32 click?: (e: Event) => void
46 selector: 'my-videos-list',
47 templateUrl: './videos-list.component.html',
48 styleUrls: [ './videos-list.component.scss' ]
50 export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
51 @Input() getVideosObservableFunction: (pagination: ComponentPaginationLight, filters: VideoFilters) => Observable<ResultList<Video>>
52 @Input() getSyndicationItemsFunction: (filters: VideoFilters) => Promise<Syndication[]> | Syndication[]
53 @Input() baseRouteBuilderFunction: (filters: VideoFilters) => string[]
55 @Input() title: string
56 @Input() titleTooltip: string
57 @Input() displayTitle = true
59 @Input() defaultSort: VideoSortField
60 @Input() defaultScope: VideoFilterScope = 'federated'
61 @Input() displayFilters = false
62 @Input() displayModerationBlock = false
64 @Input() loadUserVideoPreferences = false
66 @Input() displayAsRow = false
67 @Input() displayVideoActions = true
68 @Input() groupByDate = false
70 @Input() headerActions: HeaderAction[] = []
72 @Input() hideScopeFilter = false
74 @Input() displayOptions: MiniatureDisplayOptions
76 @Input() disabled = false
78 @Output() filtersChanged = new EventEmitter<VideoFilters>()
79 @Output() videosLoaded = new EventEmitter<Video[]>()
83 syndicationItems: Syndication[]
85 onDataSubject = new Subject<any[]>()
86 hasDoneFirstQuery = false
90 private defaultDisplayOptions: MiniatureDisplayOptions = {
100 private routeSub: Subscription
101 private userSub: Subscription
102 private resizeSub: Subscription
104 private pagination: ComponentPaginationLight = {
109 private groupedDateLabels: { [id in GroupDate]: string }
110 private groupedDates: { [id: number]: GroupDate } = {}
112 private lastQueryLength: number
115 private notifier: Notifier,
116 private authService: AuthService,
117 private userService: UserService,
118 private route: ActivatedRoute,
119 private screenService: ScreenService,
120 private peertubeRouter: PeerTubeRouterService,
121 private serverService: ServerService
127 const hiddenFilters = this.hideScopeFilter
131 this.filters = new VideoFilters(this.defaultSort, this.defaultScope, hiddenFilters)
132 this.filters.load({ ...this.route.snapshot.queryParams, scope: this.defaultScope })
134 this.groupedDateLabels = {
135 [GroupDate.UNKNOWN]: null,
136 [GroupDate.TODAY]: $localize`Today`,
137 [GroupDate.YESTERDAY]: $localize`Yesterday`,
138 [GroupDate.THIS_WEEK]: $localize`This week`,
139 [GroupDate.THIS_MONTH]: $localize`This month`,
140 [GroupDate.LAST_MONTH]: $localize`Last month`,
141 [GroupDate.OLDER]: $localize`Older`
144 this.resizeSub = fromEvent(window, 'resize')
145 .pipe(debounceTime(500))
146 .subscribe(() => this.calcPageSizes())
150 this.userService.getAnonymousOrLoggedUser()
152 this.userMiniature = user
154 if (this.loadUserVideoPreferences) {
155 this.loadUserSettings(user)
158 this.scheduleOnFiltersChanged(false)
160 this.subscribeToAnonymousUpdate()
161 this.subscribeToSearchChange()
164 // Display avatar in mobile view
165 if (this.screenService.isInMobileView()) {
166 this.displayOptions.avatar = true
171 if (this.resizeSub) this.resizeSub.unsubscribe()
172 if (this.routeSub) this.routeSub.unsubscribe()
173 if (this.userSub) this.userSub.unsubscribe()
176 ngOnChanges (changes: SimpleChanges) {
177 if (changes['displayOptions'] || !this.displayOptions) {
178 this.displayOptions = {
179 ...this.defaultDisplayOptions,
180 avatar: this.serverService.getHTMLConfig().client.videos.miniature.displayAuthorAvatar,
181 ...changes['displayOptions']
185 if (!this.filters) return
189 if (changes['defaultScope']) {
191 this.filters.setDefaultScope(this.defaultScope)
194 if (changes['defaultSort']) {
196 this.filters.setDefaultSort(this.defaultSort)
201 const customizedByUser = this.hasBeenCustomizedByUser()
203 if (!customizedByUser) {
204 if (this.loadUserVideoPreferences) {
205 this.loadUserSettings(this.userMiniature)
208 this.filters.reset('scope')
209 this.filters.reset('sort')
212 this.scheduleOnFiltersChanged(customizedByUser)
215 videoById (_index: number, video: Video) {
220 if (this.disabled) return
223 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
225 this.pagination.currentPage += 1
227 this.loadMoreVideos()
230 loadMoreVideos (reset = false) {
231 if (reset) this.hasDoneFirstQuery = false
233 this.getVideosObservableFunction(this.pagination, this.filters)
235 next: ({ data }) => {
236 this.hasDoneFirstQuery = true
237 this.lastQueryLength = data.length
239 if (reset) this.videos = []
240 this.videos = this.videos.concat(data)
242 if (this.groupByDate) this.buildGroupedDateLabels()
244 this.onDataSubject.next(data)
245 this.videosLoaded.emit(this.videos)
249 const message = $localize`Cannot load more videos. Try again later.`
251 logger.error(message, err)
252 this.notifier.error(message)
258 this.pagination.currentPage = 1
259 this.loadMoreVideos(true)
262 removeVideoFromArray (video: Video) {
263 this.videos = this.videos.filter(v => v.id !== video.id)
266 buildGroupedDateLabels () {
267 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
271 value: GroupDate.TODAY,
272 validator: (d: Date) => isToday(d)
275 value: GroupDate.YESTERDAY,
276 validator: (d: Date) => isYesterday(d)
279 value: GroupDate.THIS_WEEK,
280 validator: (d: Date) => isLastWeek(d)
283 value: GroupDate.THIS_MONTH,
284 validator: (d: Date) => isThisMonth(d)
287 value: GroupDate.LAST_MONTH,
288 validator: (d: Date) => isLastMonth(d)
291 value: GroupDate.OLDER,
292 validator: () => true
296 for (const video of this.videos) {
297 const publishedDate = video.publishedAt
299 for (let i = 0; i < periods.length; i++) {
300 const period = periods[i]
302 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
304 if (currentGroupedDate !== period.value) {
305 currentGroupedDate = period.value
306 this.groupedDates[video.id] = currentGroupedDate
315 getCurrentGroupedDateLabel (video: Video) {
316 if (this.groupByDate === false) return undefined
318 return this.groupedDateLabels[this.groupedDates[video.id]]
321 scheduleOnFiltersChanged (customizedByUser: boolean) {
322 // We'll reload videos, but avoid weird UI effect
325 setTimeout(() => this.onFiltersChanged(customizedByUser))
328 onFiltersChanged (customizedByUser: boolean) {
329 debugLogger('Running on filters changed')
331 this.updateUrl(customizedByUser)
333 this.filters.triggerChange()
335 this.reloadSyndicationItems()
339 protected enableAllFilterIfPossible () {
340 if (!this.authService.isLoggedIn()) return
342 this.authService.userInformationLoaded
344 const user = this.authService.getUser()
345 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
349 private calcPageSizes () {
350 if (this.screenService.isInMobileView()) {
351 this.pagination.itemsPerPage = 5
355 private loadUserSettings (user: User) {
356 this.filters.setNSFWPolicy(user.nsfwPolicy)
358 // Don't reset language filter if we don't want to refresh the component
359 if (!this.hasBeenCustomizedByUser()) {
360 this.filters.load({ languageOneOf: user.videoLanguages })
364 private reloadSyndicationItems () {
365 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
367 if (!items || items.length === 0) this.syndicationItems = undefined
368 else this.syndicationItems = items
370 .catch(err => logger.error('Cannot get syndication items.', err))
373 private updateUrl (customizedByUser: boolean) {
374 const baseQuery = this.filters.toUrlObject()
376 // Set or reset customized by user query param
377 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
378 ? { ...baseQuery, c: customizedByUser }
381 debugLogger('Will inject %O in URL query', queryParams)
383 const baseRoute = this.baseRouteBuilderFunction
384 ? this.baseRouteBuilderFunction(this.filters)
387 const pathname = window.location.pathname
389 const baseRouteChanged = baseRoute.length !== 0 &&
390 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
391 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
393 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
394 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
397 this.filtersChanged.emit(this.filters)
400 private hasBeenCustomizedByUser () {
401 return this.route.snapshot.queryParams['c'] === 'true'
404 private subscribeToAnonymousUpdate () {
405 this.userSub = this.userService.listenAnonymousUpdate()
406 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
408 if (this.loadUserVideoPreferences) {
409 this.loadUserSettings(user)
412 if (this.hasDoneFirstQuery) {
418 private subscribeToSearchChange () {
419 this.routeSub = this.route.queryParams.subscribe(param => {
420 if (!param['search']) return
422 this.filters.load({ search: param['search'] })
423 this.onFiltersChanged(true)