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 { isLastMonth, isLastWeek, isThisMonth, isToday, isYesterday } from '@shared/core-utils'
18 import { ResultList, UserRight, VideoSortField } from '@shared/models'
19 import { Syndication, Video } from '../shared-main'
20 import { VideoFilters, VideoFilterScope } from './video-filters.model'
21 import { MiniatureDisplayOptions } from './video-miniature.component'
23 const logger = debug('peertube:videos:VideosListComponent')
25 export type HeaderAction = {
26 iconName: GlobalIconName
31 click?: (e: Event) => void
45 selector: 'my-videos-list',
46 templateUrl: './videos-list.component.html',
47 styleUrls: [ './videos-list.component.scss' ]
49 export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
50 @Input() getVideosObservableFunction: (pagination: ComponentPaginationLight, filters: VideoFilters) => Observable<ResultList<Video>>
51 @Input() getSyndicationItemsFunction: (filters: VideoFilters) => Promise<Syndication[]> | Syndication[]
52 @Input() baseRouteBuilderFunction: (filters: VideoFilters) => string[]
54 @Input() title: string
55 @Input() titleTooltip: string
56 @Input() displayTitle = true
58 @Input() defaultSort: VideoSortField
59 @Input() defaultScope: VideoFilterScope = 'federated'
60 @Input() displayFilters = false
61 @Input() displayModerationBlock = false
63 @Input() loadUserVideoPreferences = false
65 @Input() displayAsRow = false
66 @Input() displayVideoActions = true
67 @Input() groupByDate = false
69 @Input() headerActions: HeaderAction[] = []
71 @Input() hideScopeFilter = false
73 @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 defaultDisplayOptions: MiniatureDisplayOptions = {
98 private routeSub: Subscription
99 private userSub: Subscription
100 private resizeSub: Subscription
102 private pagination: ComponentPaginationLight = {
107 private groupedDateLabels: { [id in GroupDate]: string }
108 private groupedDates: { [id: number]: GroupDate } = {}
110 private lastQueryLength: number
113 private notifier: Notifier,
114 private authService: AuthService,
115 private userService: UserService,
116 private route: ActivatedRoute,
117 private screenService: ScreenService,
118 private peertubeRouter: PeerTubeRouterService,
119 private serverService: ServerService
125 const hiddenFilters = this.hideScopeFilter
129 this.filters = new VideoFilters(this.defaultSort, this.defaultScope, hiddenFilters)
130 this.filters.load({ ...this.route.snapshot.queryParams, scope: this.defaultScope })
132 this.groupedDateLabels = {
133 [GroupDate.UNKNOWN]: null,
134 [GroupDate.TODAY]: $localize`Today`,
135 [GroupDate.YESTERDAY]: $localize`Yesterday`,
136 [GroupDate.THIS_WEEK]: $localize`This week`,
137 [GroupDate.THIS_MONTH]: $localize`This month`,
138 [GroupDate.LAST_MONTH]: $localize`Last month`,
139 [GroupDate.OLDER]: $localize`Older`
142 this.resizeSub = fromEvent(window, 'resize')
143 .pipe(debounceTime(500))
144 .subscribe(() => this.calcPageSizes())
148 this.userService.getAnonymousOrLoggedUser()
150 this.userMiniature = user
152 if (this.loadUserVideoPreferences) {
153 this.loadUserSettings(user)
156 this.scheduleOnFiltersChanged(false)
158 this.subscribeToAnonymousUpdate()
159 this.subscribeToSearchChange()
162 // Display avatar in mobile view
163 if (this.screenService.isInMobileView()) {
164 this.displayOptions.avatar = true
169 if (this.resizeSub) this.resizeSub.unsubscribe()
170 if (this.routeSub) this.routeSub.unsubscribe()
171 if (this.userSub) this.userSub.unsubscribe()
174 ngOnChanges (changes: SimpleChanges) {
175 if (changes['displayOptions'] || !this.displayOptions) {
176 this.displayOptions = {
177 ...this.defaultDisplayOptions,
178 avatar: this.serverService.getHTMLConfig().client.videos.miniature.displayAuthorAvatar,
179 ...changes['displayOptions']
183 if (!this.filters) return
187 if (changes['defaultScope']) {
189 this.filters.setDefaultScope(this.defaultScope)
192 if (changes['defaultSort']) {
194 this.filters.setDefaultSort(this.defaultSort)
199 const customizedByUser = this.hasBeenCustomizedByUser()
201 if (!customizedByUser) {
202 if (this.loadUserVideoPreferences) {
203 this.loadUserSettings(this.userMiniature)
206 this.filters.reset('scope')
207 this.filters.reset('sort')
210 this.scheduleOnFiltersChanged(customizedByUser)
213 videoById (_index: number, video: Video) {
218 if (this.disabled) return
221 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
223 this.pagination.currentPage += 1
225 this.loadMoreVideos()
228 loadMoreVideos (reset = false) {
229 if (reset) this.hasDoneFirstQuery = false
231 this.getVideosObservableFunction(this.pagination, this.filters)
233 next: ({ data }) => {
234 this.hasDoneFirstQuery = true
235 this.lastQueryLength = data.length
237 if (reset) this.videos = []
238 this.videos = this.videos.concat(data)
240 if (this.groupByDate) this.buildGroupedDateLabels()
242 this.onDataSubject.next(data)
246 const message = $localize`Cannot load more videos. Try again later.`
248 console.error(message, { err })
249 this.notifier.error(message)
255 this.pagination.currentPage = 1
256 this.loadMoreVideos(true)
259 removeVideoFromArray (video: Video) {
260 this.videos = this.videos.filter(v => v.id !== video.id)
263 buildGroupedDateLabels () {
264 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
268 value: GroupDate.TODAY,
269 validator: (d: Date) => isToday(d)
272 value: GroupDate.YESTERDAY,
273 validator: (d: Date) => isYesterday(d)
276 value: GroupDate.THIS_WEEK,
277 validator: (d: Date) => isLastWeek(d)
280 value: GroupDate.THIS_MONTH,
281 validator: (d: Date) => isThisMonth(d)
284 value: GroupDate.LAST_MONTH,
285 validator: (d: Date) => isLastMonth(d)
288 value: GroupDate.OLDER,
289 validator: () => true
293 for (const video of this.videos) {
294 const publishedDate = video.publishedAt
296 for (let i = 0; i < periods.length; i++) {
297 const period = periods[i]
299 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
301 if (currentGroupedDate !== period.value) {
302 currentGroupedDate = period.value
303 this.groupedDates[video.id] = currentGroupedDate
312 getCurrentGroupedDateLabel (video: Video) {
313 if (this.groupByDate === false) return undefined
315 return this.groupedDateLabels[this.groupedDates[video.id]]
318 scheduleOnFiltersChanged (customizedByUser: boolean) {
319 // We'll reload videos, but avoid weird UI effect
322 setTimeout(() => this.onFiltersChanged(customizedByUser))
325 onFiltersChanged (customizedByUser: boolean) {
326 logger('Running on filters changed')
328 this.updateUrl(customizedByUser)
330 this.filters.triggerChange()
332 this.reloadSyndicationItems()
336 protected enableAllFilterIfPossible () {
337 if (!this.authService.isLoggedIn()) return
339 this.authService.userInformationLoaded
341 const user = this.authService.getUser()
342 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
346 private calcPageSizes () {
347 if (this.screenService.isInMobileView()) {
348 this.pagination.itemsPerPage = 5
352 private loadUserSettings (user: User) {
353 this.filters.setNSFWPolicy(user.nsfwPolicy)
355 // Don't reset language filter if we don't want to refresh the component
356 if (!this.hasBeenCustomizedByUser()) {
357 this.filters.load({ languageOneOf: user.videoLanguages })
361 private reloadSyndicationItems () {
362 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
364 if (!items || items.length === 0) this.syndicationItems = undefined
365 else this.syndicationItems = items
367 .catch(err => console.error('Cannot get syndication items.', err))
370 private updateUrl (customizedByUser: boolean) {
371 const baseQuery = this.filters.toUrlObject()
373 // Set or reset customized by user query param
374 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
375 ? { ...baseQuery, c: customizedByUser }
378 logger('Will inject %O in URL query', queryParams)
380 const baseRoute = this.baseRouteBuilderFunction
381 ? this.baseRouteBuilderFunction(this.filters)
384 const pathname = window.location.pathname
386 const baseRouteChanged = baseRoute.length !== 0 &&
387 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
388 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
390 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
391 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
394 this.filtersChanged.emit(this.filters)
397 private hasBeenCustomizedByUser () {
398 return this.route.snapshot.queryParams['c'] === 'true'
401 private subscribeToAnonymousUpdate () {
402 this.userSub = this.userService.listenAnonymousUpdate()
403 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
405 if (this.loadUserVideoPreferences) {
406 this.loadUserSettings(user)
409 if (this.hasDoneFirstQuery) {
415 private subscribeToSearchChange () {
416 this.routeSub = this.route.queryParams.subscribe(param => {
417 if (!param['search']) return
419 this.filters.load({ search: param['search'] })
420 this.onFiltersChanged(true)