1 import * as debug from 'debug'
2 import { fromEvent, Observable, Subject, Subscription } from 'rxjs'
3 import { concatMap, debounceTime, map, 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
114 private videoRequests = new Subject<{ reset: boolean, obs: Observable<ResultList<Video>> }>()
117 private notifier: Notifier,
118 private authService: AuthService,
119 private userService: UserService,
120 private route: ActivatedRoute,
121 private screenService: ScreenService,
122 private peertubeRouter: PeerTubeRouterService,
123 private serverService: ServerService
129 this.subscribeToVideoRequests()
131 const hiddenFilters = this.hideScopeFilter
135 this.filters = new VideoFilters(this.defaultSort, this.defaultScope, hiddenFilters)
136 this.filters.load({ ...this.route.snapshot.queryParams, scope: this.defaultScope })
138 this.groupedDateLabels = {
139 [GroupDate.UNKNOWN]: null,
140 [GroupDate.TODAY]: $localize`Today`,
141 [GroupDate.YESTERDAY]: $localize`Yesterday`,
142 [GroupDate.THIS_WEEK]: $localize`This week`,
143 [GroupDate.THIS_MONTH]: $localize`This month`,
144 [GroupDate.LAST_MONTH]: $localize`Last month`,
145 [GroupDate.OLDER]: $localize`Older`
148 this.resizeSub = fromEvent(window, 'resize')
149 .pipe(debounceTime(500))
150 .subscribe(() => this.calcPageSizes())
154 this.userService.getAnonymousOrLoggedUser()
156 this.userMiniature = user
158 if (this.loadUserVideoPreferences) {
159 this.loadUserSettings(user)
162 this.scheduleOnFiltersChanged(false)
164 this.subscribeToAnonymousUpdate()
165 this.subscribeToSearchChange()
168 // Display avatar in mobile view
169 if (this.screenService.isInMobileView()) {
170 this.displayOptions.avatar = true
175 if (this.resizeSub) this.resizeSub.unsubscribe()
176 if (this.routeSub) this.routeSub.unsubscribe()
177 if (this.userSub) this.userSub.unsubscribe()
180 ngOnChanges (changes: SimpleChanges) {
181 if (changes['displayOptions'] || !this.displayOptions) {
182 this.displayOptions = {
183 ...this.defaultDisplayOptions,
184 avatar: this.serverService.getHTMLConfig().client.videos.miniature.displayAuthorAvatar,
185 ...changes['displayOptions']
189 if (!this.filters) return
193 if (changes['defaultScope']) {
195 this.filters.setDefaultScope(this.defaultScope)
198 if (changes['defaultSort']) {
200 this.filters.setDefaultSort(this.defaultSort)
205 const customizedByUser = this.hasBeenCustomizedByUser()
207 if (!customizedByUser) {
208 if (this.loadUserVideoPreferences) {
209 this.loadUserSettings(this.userMiniature)
212 this.filters.reset('scope')
213 this.filters.reset('sort')
216 this.scheduleOnFiltersChanged(customizedByUser)
219 videoById (_index: number, video: Video) {
224 if (this.disabled) return
227 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
229 this.pagination.currentPage += 1
231 this.loadMoreVideos()
234 loadMoreVideos (reset = false) {
236 this.hasDoneFirstQuery = false
240 this.videoRequests.next({ reset, obs: this.getVideosObservableFunction(this.pagination, this.filters) })
244 this.pagination.currentPage = 1
245 this.loadMoreVideos(true)
248 removeVideoFromArray (video: Video) {
249 this.videos = this.videos.filter(v => v.id !== video.id)
252 buildGroupedDateLabels () {
253 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
257 value: GroupDate.TODAY,
258 validator: (d: Date) => isToday(d)
261 value: GroupDate.YESTERDAY,
262 validator: (d: Date) => isYesterday(d)
265 value: GroupDate.THIS_WEEK,
266 validator: (d: Date) => isLastWeek(d)
269 value: GroupDate.THIS_MONTH,
270 validator: (d: Date) => isThisMonth(d)
273 value: GroupDate.LAST_MONTH,
274 validator: (d: Date) => isLastMonth(d)
277 value: GroupDate.OLDER,
278 validator: () => true
282 for (const video of this.videos) {
283 const publishedDate = video.publishedAt
285 for (let i = 0; i < periods.length; i++) {
286 const period = periods[i]
288 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
290 if (currentGroupedDate !== period.value) {
291 currentGroupedDate = period.value
292 this.groupedDates[video.id] = currentGroupedDate
301 getCurrentGroupedDateLabel (video: Video) {
302 if (this.groupByDate === false) return undefined
304 return this.groupedDateLabels[this.groupedDates[video.id]]
307 scheduleOnFiltersChanged (customizedByUser: boolean) {
308 // We'll reload videos, but avoid weird UI effect
311 setTimeout(() => this.onFiltersChanged(customizedByUser))
314 onFiltersChanged (customizedByUser: boolean) {
315 debugLogger('Running on filters changed')
317 this.updateUrl(customizedByUser)
319 this.filters.triggerChange()
321 this.reloadSyndicationItems()
325 protected enableAllFilterIfPossible () {
326 if (!this.authService.isLoggedIn()) return
328 this.authService.userInformationLoaded
330 const user = this.authService.getUser()
331 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
335 private calcPageSizes () {
336 if (this.screenService.isInMobileView()) {
337 this.pagination.itemsPerPage = 5
341 private loadUserSettings (user: User) {
342 this.filters.setNSFWPolicy(user.nsfwPolicy)
344 // Don't reset language filter if we don't want to refresh the component
345 if (!this.hasBeenCustomizedByUser()) {
346 this.filters.load({ languageOneOf: user.videoLanguages })
350 private reloadSyndicationItems () {
351 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
353 if (!items || items.length === 0) this.syndicationItems = undefined
354 else this.syndicationItems = items
356 .catch(err => logger.error('Cannot get syndication items.', err))
359 private updateUrl (customizedByUser: boolean) {
360 const baseQuery = this.filters.toUrlObject()
362 // Set or reset customized by user query param
363 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
364 ? { ...baseQuery, c: customizedByUser }
367 debugLogger('Will inject %O in URL query', queryParams)
369 const baseRoute = this.baseRouteBuilderFunction
370 ? this.baseRouteBuilderFunction(this.filters)
373 const pathname = window.location.pathname
375 const baseRouteChanged = baseRoute.length !== 0 &&
376 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
377 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
379 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
380 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
383 this.filtersChanged.emit(this.filters)
386 private hasBeenCustomizedByUser () {
387 return this.route.snapshot.queryParams['c'] === 'true'
390 private subscribeToAnonymousUpdate () {
391 this.userSub = this.userService.listenAnonymousUpdate()
392 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
394 if (this.loadUserVideoPreferences) {
395 this.loadUserSettings(user)
398 if (this.hasDoneFirstQuery) {
404 private subscribeToSearchChange () {
405 this.routeSub = this.route.queryParams.subscribe(param => {
406 if (!param['search']) return
408 this.filters.load({ search: param['search'] })
409 this.onFiltersChanged(true)
413 private subscribeToVideoRequests () {
415 .pipe(concatMap(({ reset, obs }) => obs.pipe(map(({ data }) => ({ data, reset })))))
417 next: ({ data, reset }) => {
418 this.hasDoneFirstQuery = true
419 this.lastQueryLength = data.length
421 if (reset) this.videos = []
422 this.videos = this.videos.concat(data)
424 if (this.groupByDate) this.buildGroupedDateLabels()
426 this.onDataSubject.next(data)
427 this.videosLoaded.emit(this.videos)
431 const message = $localize`Cannot load more videos. Try again later.`
433 logger.error(message, err)
434 this.notifier.error(message)