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() displayOptions: MiniatureDisplayOptions = {
73 @Input() disabled = false
75 @Output() filtersChanged = new EventEmitter<VideoFilters>()
79 syndicationItems: Syndication[]
81 onDataSubject = new Subject<any[]>()
82 hasDoneFirstQuery = false
86 private routeSub: Subscription
87 private userSub: Subscription
88 private resizeSub: Subscription
90 private pagination: ComponentPaginationLight = {
95 private groupedDateLabels: { [id in GroupDate]: string }
96 private groupedDates: { [id: number]: GroupDate } = {}
98 private lastQueryLength: number
101 private notifier: Notifier,
102 private authService: AuthService,
103 private userService: UserService,
104 private route: ActivatedRoute,
105 private screenService: ScreenService,
106 private peertubeRouter: PeerTubeRouterService
112 this.filters = new VideoFilters(this.defaultSort, this.defaultScope)
113 this.filters.load({ ...this.route.snapshot.queryParams, scope: this.defaultScope })
115 this.groupedDateLabels = {
116 [GroupDate.UNKNOWN]: null,
117 [GroupDate.TODAY]: $localize`Today`,
118 [GroupDate.YESTERDAY]: $localize`Yesterday`,
119 [GroupDate.THIS_WEEK]: $localize`This week`,
120 [GroupDate.THIS_MONTH]: $localize`This month`,
121 [GroupDate.LAST_MONTH]: $localize`Last month`,
122 [GroupDate.OLDER]: $localize`Older`
125 this.resizeSub = fromEvent(window, 'resize')
126 .pipe(debounceTime(500))
127 .subscribe(() => this.calcPageSizes())
131 this.userService.getAnonymousOrLoggedUser()
133 this.userMiniature = user
135 if (this.loadUserVideoPreferences) {
136 this.loadUserSettings(user)
139 this.scheduleOnFiltersChanged(false)
141 this.subscribeToAnonymousUpdate()
142 this.subscribeToSearchChange()
145 // Display avatar in mobile view
146 if (this.screenService.isInMobileView()) {
147 this.displayOptions.avatar = true
152 if (this.resizeSub) this.resizeSub.unsubscribe()
153 if (this.routeSub) this.routeSub.unsubscribe()
154 if (this.userSub) this.userSub.unsubscribe()
157 ngOnChanges (changes: SimpleChanges) {
158 if (!this.filters) return
162 if (changes['defaultScope']) {
164 this.filters.setDefaultScope(this.defaultScope)
167 if (changes['defaultSort']) {
169 this.filters.setDefaultSort(this.defaultSort)
174 const customizedByUser = this.hasBeenCustomizedByUser()
176 if (!customizedByUser) {
177 if (this.loadUserVideoPreferences) {
178 this.loadUserSettings(this.userMiniature)
181 this.filters.reset('scope')
182 this.filters.reset('sort')
185 this.scheduleOnFiltersChanged(customizedByUser)
188 videoById (_index: number, video: Video) {
193 if (this.disabled) return
196 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
198 this.pagination.currentPage += 1
200 this.loadMoreVideos()
203 loadMoreVideos (reset = false) {
204 this.getVideosObservableFunction(this.pagination, this.filters)
206 next: ({ data }) => {
207 this.hasDoneFirstQuery = true
208 this.lastQueryLength = data.length
210 if (reset) this.videos = []
211 this.videos = this.videos.concat(data)
213 if (this.groupByDate) this.buildGroupedDateLabels()
215 this.onDataSubject.next(data)
219 const message = $localize`Cannot load more videos. Try again later.`
221 console.error(message, { err })
222 this.notifier.error(message)
228 this.pagination.currentPage = 1
229 this.loadMoreVideos(true)
232 removeVideoFromArray (video: Video) {
233 this.videos = this.videos.filter(v => v.id !== video.id)
236 buildGroupedDateLabels () {
237 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
241 value: GroupDate.TODAY,
242 validator: (d: Date) => isToday(d)
245 value: GroupDate.YESTERDAY,
246 validator: (d: Date) => isYesterday(d)
249 value: GroupDate.THIS_WEEK,
250 validator: (d: Date) => isLastWeek(d)
253 value: GroupDate.THIS_MONTH,
254 validator: (d: Date) => isThisMonth(d)
257 value: GroupDate.LAST_MONTH,
258 validator: (d: Date) => isLastMonth(d)
261 value: GroupDate.OLDER,
262 validator: () => true
266 for (const video of this.videos) {
267 const publishedDate = video.publishedAt
269 for (let i = 0; i < periods.length; i++) {
270 const period = periods[i]
272 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
274 if (currentGroupedDate !== period.value) {
275 currentGroupedDate = period.value
276 this.groupedDates[video.id] = currentGroupedDate
285 getCurrentGroupedDateLabel (video: Video) {
286 if (this.groupByDate === false) return undefined
288 return this.groupedDateLabels[this.groupedDates[video.id]]
291 scheduleOnFiltersChanged (customizedByUser: boolean) {
292 // We'll reload videos, but avoid weird UI effect
295 setTimeout(() => this.onFiltersChanged(customizedByUser))
298 onFiltersChanged (customizedByUser: boolean) {
299 logger('Running on filters changed')
301 this.updateUrl(customizedByUser)
303 this.filters.triggerChange()
305 this.reloadSyndicationItems()
309 protected enableAllFilterIfPossible () {
310 if (!this.authService.isLoggedIn()) return
312 this.authService.userInformationLoaded
314 const user = this.authService.getUser()
315 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
319 private calcPageSizes () {
320 if (this.screenService.isInMobileView()) {
321 this.pagination.itemsPerPage = 5
325 private loadUserSettings (user: User) {
326 this.filters.setNSFWPolicy(user.nsfwPolicy)
328 // Don't reset language filter if we don't want to refresh the component
329 if (!this.hasBeenCustomizedByUser()) {
330 this.filters.load({ languageOneOf: user.videoLanguages })
334 private reloadSyndicationItems () {
335 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
337 if (!items || items.length === 0) this.syndicationItems = undefined
338 else this.syndicationItems = items
340 .catch(err => console.error('Cannot get syndication items.', err))
343 private updateUrl (customizedByUser: boolean) {
344 const baseQuery = this.filters.toUrlObject()
346 // Set or reset customized by user query param
347 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
348 ? { ...baseQuery, c: customizedByUser }
351 logger('Will inject %O in URL query', queryParams)
353 const baseRoute = this.baseRouteBuilderFunction
354 ? this.baseRouteBuilderFunction(this.filters)
357 const pathname = window.location.pathname
359 const baseRouteChanged = baseRoute.length !== 0 &&
360 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
361 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
363 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
364 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
367 this.filtersChanged.emit(this.filters)
370 private hasBeenCustomizedByUser () {
371 return this.route.snapshot.queryParams['c'] === 'true'
374 private subscribeToAnonymousUpdate () {
375 this.userSub = this.userService.listenAnonymousUpdate()
376 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
378 if (this.loadUserVideoPreferences) {
379 this.loadUserSettings(user)
382 if (this.hasDoneFirstQuery) {
388 private subscribeToSearchChange () {
389 this.routeSub = this.route.queryParams.subscribe(param => {
390 if (!param['search']) return
392 this.filters.load({ search: param['search'] })
393 this.onFiltersChanged(true)