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>()
82 syndicationItems: Syndication[]
84 onDataSubject = new Subject<any[]>()
85 hasDoneFirstQuery = false
89 private defaultDisplayOptions: MiniatureDisplayOptions = {
99 private routeSub: Subscription
100 private userSub: Subscription
101 private resizeSub: Subscription
103 private pagination: ComponentPaginationLight = {
108 private groupedDateLabels: { [id in GroupDate]: string }
109 private groupedDates: { [id: number]: GroupDate } = {}
111 private lastQueryLength: number
114 private notifier: Notifier,
115 private authService: AuthService,
116 private userService: UserService,
117 private route: ActivatedRoute,
118 private screenService: ScreenService,
119 private peertubeRouter: PeerTubeRouterService,
120 private serverService: ServerService
126 const hiddenFilters = this.hideScopeFilter
130 this.filters = new VideoFilters(this.defaultSort, this.defaultScope, hiddenFilters)
131 this.filters.load({ ...this.route.snapshot.queryParams, scope: this.defaultScope })
133 this.groupedDateLabels = {
134 [GroupDate.UNKNOWN]: null,
135 [GroupDate.TODAY]: $localize`Today`,
136 [GroupDate.YESTERDAY]: $localize`Yesterday`,
137 [GroupDate.THIS_WEEK]: $localize`This week`,
138 [GroupDate.THIS_MONTH]: $localize`This month`,
139 [GroupDate.LAST_MONTH]: $localize`Last month`,
140 [GroupDate.OLDER]: $localize`Older`
143 this.resizeSub = fromEvent(window, 'resize')
144 .pipe(debounceTime(500))
145 .subscribe(() => this.calcPageSizes())
149 this.userService.getAnonymousOrLoggedUser()
151 this.userMiniature = user
153 if (this.loadUserVideoPreferences) {
154 this.loadUserSettings(user)
157 this.scheduleOnFiltersChanged(false)
159 this.subscribeToAnonymousUpdate()
160 this.subscribeToSearchChange()
163 // Display avatar in mobile view
164 if (this.screenService.isInMobileView()) {
165 this.displayOptions.avatar = true
170 if (this.resizeSub) this.resizeSub.unsubscribe()
171 if (this.routeSub) this.routeSub.unsubscribe()
172 if (this.userSub) this.userSub.unsubscribe()
175 ngOnChanges (changes: SimpleChanges) {
176 if (changes['displayOptions'] || !this.displayOptions) {
177 this.displayOptions = {
178 ...this.defaultDisplayOptions,
179 avatar: this.serverService.getHTMLConfig().client.videos.miniature.displayAuthorAvatar,
180 ...changes['displayOptions']
184 if (!this.filters) return
188 if (changes['defaultScope']) {
190 this.filters.setDefaultScope(this.defaultScope)
193 if (changes['defaultSort']) {
195 this.filters.setDefaultSort(this.defaultSort)
200 const customizedByUser = this.hasBeenCustomizedByUser()
202 if (!customizedByUser) {
203 if (this.loadUserVideoPreferences) {
204 this.loadUserSettings(this.userMiniature)
207 this.filters.reset('scope')
208 this.filters.reset('sort')
211 this.scheduleOnFiltersChanged(customizedByUser)
214 videoById (_index: number, video: Video) {
219 if (this.disabled) return
222 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
224 this.pagination.currentPage += 1
226 this.loadMoreVideos()
229 loadMoreVideos (reset = false) {
230 if (reset) this.hasDoneFirstQuery = false
232 this.getVideosObservableFunction(this.pagination, this.filters)
234 next: ({ data }) => {
235 this.hasDoneFirstQuery = true
236 this.lastQueryLength = data.length
238 if (reset) this.videos = []
239 this.videos = this.videos.concat(data)
241 if (this.groupByDate) this.buildGroupedDateLabels()
243 this.onDataSubject.next(data)
247 const message = $localize`Cannot load more videos. Try again later.`
249 logger.error(message, err)
250 this.notifier.error(message)
256 this.pagination.currentPage = 1
257 this.loadMoreVideos(true)
260 removeVideoFromArray (video: Video) {
261 this.videos = this.videos.filter(v => v.id !== video.id)
264 buildGroupedDateLabels () {
265 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
269 value: GroupDate.TODAY,
270 validator: (d: Date) => isToday(d)
273 value: GroupDate.YESTERDAY,
274 validator: (d: Date) => isYesterday(d)
277 value: GroupDate.THIS_WEEK,
278 validator: (d: Date) => isLastWeek(d)
281 value: GroupDate.THIS_MONTH,
282 validator: (d: Date) => isThisMonth(d)
285 value: GroupDate.LAST_MONTH,
286 validator: (d: Date) => isLastMonth(d)
289 value: GroupDate.OLDER,
290 validator: () => true
294 for (const video of this.videos) {
295 const publishedDate = video.publishedAt
297 for (let i = 0; i < periods.length; i++) {
298 const period = periods[i]
300 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
302 if (currentGroupedDate !== period.value) {
303 currentGroupedDate = period.value
304 this.groupedDates[video.id] = currentGroupedDate
313 getCurrentGroupedDateLabel (video: Video) {
314 if (this.groupByDate === false) return undefined
316 return this.groupedDateLabels[this.groupedDates[video.id]]
319 scheduleOnFiltersChanged (customizedByUser: boolean) {
320 // We'll reload videos, but avoid weird UI effect
323 setTimeout(() => this.onFiltersChanged(customizedByUser))
326 onFiltersChanged (customizedByUser: boolean) {
327 debugLogger('Running on filters changed')
329 this.updateUrl(customizedByUser)
331 this.filters.triggerChange()
333 this.reloadSyndicationItems()
337 protected enableAllFilterIfPossible () {
338 if (!this.authService.isLoggedIn()) return
340 this.authService.userInformationLoaded
342 const user = this.authService.getUser()
343 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
347 private calcPageSizes () {
348 if (this.screenService.isInMobileView()) {
349 this.pagination.itemsPerPage = 5
353 private loadUserSettings (user: User) {
354 this.filters.setNSFWPolicy(user.nsfwPolicy)
356 // Don't reset language filter if we don't want to refresh the component
357 if (!this.hasBeenCustomizedByUser()) {
358 this.filters.load({ languageOneOf: user.videoLanguages })
362 private reloadSyndicationItems () {
363 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
365 if (!items || items.length === 0) this.syndicationItems = undefined
366 else this.syndicationItems = items
368 .catch(err => logger.error('Cannot get syndication items.', err))
371 private updateUrl (customizedByUser: boolean) {
372 const baseQuery = this.filters.toUrlObject()
374 // Set or reset customized by user query param
375 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
376 ? { ...baseQuery, c: customizedByUser }
379 debugLogger('Will inject %O in URL query', queryParams)
381 const baseRoute = this.baseRouteBuilderFunction
382 ? this.baseRouteBuilderFunction(this.filters)
385 const pathname = window.location.pathname
387 const baseRouteChanged = baseRoute.length !== 0 &&
388 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
389 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
391 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
392 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
395 this.filtersChanged.emit(this.filters)
398 private hasBeenCustomizedByUser () {
399 return this.route.snapshot.queryParams['c'] === 'true'
402 private subscribeToAnonymousUpdate () {
403 this.userSub = this.userService.listenAnonymousUpdate()
404 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
406 if (this.loadUserVideoPreferences) {
407 this.loadUserSettings(user)
410 if (this.hasDoneFirstQuery) {
416 private subscribeToSearchChange () {
417 this.routeSub = this.route.queryParams.subscribe(param => {
418 if (!param['search']) return
420 this.filters.load({ search: param['search'] })
421 this.onFiltersChanged(true)