1 import { fromEvent, Observable, ReplaySubject, Subject, Subscription } from 'rxjs'
2 import { debounceTime, switchMap, tap } from 'rxjs/operators'
5 ComponentFactoryResolver,
13 } from '@angular/core'
14 import { ActivatedRoute, Params, Router } from '@angular/router'
17 ComponentPaginationLight,
25 import { DisableForReuseHook } from '@app/core/routing/disable-for-reuse-hook'
26 import { GlobalIconName } from '@app/shared/shared-icons'
27 import { isLastMonth, isLastWeek, isThisMonth, isToday, isYesterday } from '@shared/core-utils'
28 import { HTMLServerConfig, UserRight, VideoFilter, VideoSortField } from '@shared/models'
29 import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
30 import { Syndication, Video } from '../shared-main'
31 import { GenericHeaderComponent, VideoListHeaderComponent } from './video-list-header.component'
32 import { MiniatureDisplayOptions } from './video-miniature.component'
45 // eslint-disable-next-line @angular-eslint/directive-class-suffix
46 export abstract class AbstractVideoList implements OnInit, OnDestroy, AfterContentInit, DisableForReuseHook {
47 @ViewChild('videoListHeader', { static: true, read: ViewContainerRef }) videoListHeader: ViewContainerRef
49 HeaderComponent: Type<GenericHeaderComponent> = VideoListHeaderComponent
50 headerComponentInjector: Injector
52 pagination: ComponentPaginationLight = {
56 sort: VideoSortField = '-publishedAt'
58 categoryOneOf?: number[]
59 languageOneOf?: string[]
60 nsfwPolicy?: NSFWPolicyType
61 defaultSort: VideoSortField = '-publishedAt'
63 syndicationItems: Syndication[] = []
66 loadUserVideoPreferences = false
68 displayModerationBlock = false
70 displayVideoActions = true
74 hasDoneFirstQuery = false
77 displayOptions: MiniatureDisplayOptions = {
89 iconName: GlobalIconName
94 click?: (e: Event) => void
97 onDataSubject = new Subject<any[]>()
101 protected onUserLoadedSubject = new ReplaySubject<void>(1)
103 protected serverConfig: HTMLServerConfig
105 protected abstract notifier: Notifier
106 protected abstract authService: AuthService
107 protected abstract userService: UserService
108 protected abstract route: ActivatedRoute
109 protected abstract serverService: ServerService
110 protected abstract screenService: ScreenService
111 protected abstract storageService: LocalStorageService
112 protected abstract router: Router
113 protected abstract cfr: ComponentFactoryResolver
114 abstract titlePage: string
116 private resizeSubscription: Subscription
117 private angularState: number
119 private groupedDateLabels: { [id in GroupDate]: string }
120 private groupedDates: { [id: number]: GroupDate } = {}
122 private lastQueryLength: number
124 abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
126 abstract generateSyndicationList (): void
129 this.serverConfig = this.serverService.getHTMLConfig()
131 this.groupedDateLabels = {
132 [GroupDate.UNKNOWN]: null,
133 [GroupDate.TODAY]: $localize`Today`,
134 [GroupDate.YESTERDAY]: $localize`Yesterday`,
135 [GroupDate.THIS_WEEK]: $localize`This week`,
136 [GroupDate.THIS_MONTH]: $localize`This month`,
137 [GroupDate.LAST_MONTH]: $localize`Last month`,
138 [GroupDate.OLDER]: $localize`Older`
141 // Subscribe to route changes
142 const routeParams = this.route.snapshot.queryParams
143 this.loadRouteParams(routeParams)
145 this.resizeSubscription = fromEvent(window, 'resize')
146 .pipe(debounceTime(500))
147 .subscribe(() => this.calcPageSizes())
151 const loadUserObservable = this.loadUserAndSettings()
152 loadUserObservable.subscribe(() => {
153 this.onUserLoadedSubject.next()
155 if (this.loadOnInit === true) this.loadMoreVideos()
158 this.userService.listenAnonymousUpdate()
159 .pipe(switchMap(() => this.loadUserAndSettings()))
161 if (this.hasDoneFirstQuery) this.reloadVideos()
164 // Display avatar in mobile view
165 if (this.screenService.isInMobileView()) {
166 this.displayOptions.avatar = true
171 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
174 ngAfterContentInit () {
175 if (this.videoListHeader) {
176 // some components don't use the header: they use their own template, like my-history.component.html
177 this.setHeader(this.HeaderComponent, this.headerComponentInjector)
186 this.disabled = false
189 videoById (index: number, video: Video) {
194 if (this.disabled) return
197 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
199 this.pagination.currentPage += 1
201 this.setScrollRouteParams()
203 this.loadMoreVideos()
206 loadMoreVideos (reset = false) {
207 this.getVideosObservable(this.pagination.currentPage)
209 next: ({ data }) => {
210 this.hasDoneFirstQuery = true
211 this.lastQueryLength = data.length
213 if (reset) this.videos = []
214 this.videos = this.videos.concat(data)
216 if (this.groupByDate) this.buildGroupedDateLabels()
220 this.onDataSubject.next(data)
224 const message = $localize`Cannot load more videos. Try again later.`
226 console.error(message, { err })
227 this.notifier.error(message)
233 this.pagination.currentPage = 1
234 this.loadMoreVideos(true)
237 removeVideoFromArray (video: Video) {
238 this.videos = this.videos.filter(v => v.id !== video.id)
241 buildGroupedDateLabels () {
242 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
246 value: GroupDate.TODAY,
247 validator: (d: Date) => isToday(d)
250 value: GroupDate.YESTERDAY,
251 validator: (d: Date) => isYesterday(d)
254 value: GroupDate.THIS_WEEK,
255 validator: (d: Date) => isLastWeek(d)
258 value: GroupDate.THIS_MONTH,
259 validator: (d: Date) => isThisMonth(d)
262 value: GroupDate.LAST_MONTH,
263 validator: (d: Date) => isLastMonth(d)
266 value: GroupDate.OLDER,
267 validator: () => true
271 for (const video of this.videos) {
272 const publishedDate = video.publishedAt
274 for (let i = 0; i < periods.length; i++) {
275 const period = periods[i]
277 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
279 if (currentGroupedDate !== period.value) {
280 currentGroupedDate = period.value
281 this.groupedDates[video.id] = currentGroupedDate
290 getCurrentGroupedDateLabel (video: Video) {
291 if (this.groupByDate === false) return undefined
293 return this.groupedDateLabels[this.groupedDates[video.id]]
296 toggleModerationDisplay () {
297 throw new Error('toggleModerationDisplay ' + $localize`function is not implemented`)
301 t: Type<any> = this.HeaderComponent,
302 i: Injector = this.headerComponentInjector
304 const injector = i || Injector.create({
308 titlePage: this.titlePage,
309 titleTooltip: this.titleTooltip
313 const viewContainerRef = this.videoListHeader
314 viewContainerRef.clear()
316 const componentFactory = this.cfr.resolveComponentFactory(t)
317 viewContainerRef.createComponent(componentFactory, 0, injector)
320 // Can be redefined by child
325 // On videos hook for children that want to do something
326 protected onMoreVideos () { /* empty */ }
328 protected load () { /* empty */ }
330 // Hook if the page has custom route params
331 protected loadPageRouteParams (_queryParams: Params) { /* empty */ }
333 protected loadRouteParams (queryParams: Params) {
334 this.sort = queryParams['sort'] as VideoSortField || this.defaultSort
335 this.categoryOneOf = queryParams['categoryOneOf']
336 this.angularState = queryParams['a-state']
338 this.loadPageRouteParams(queryParams)
341 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
342 if (base === 'local') {
343 return existing === 'local'
344 ? 'all-local' as 'all-local'
348 return existing === 'all'
353 protected enableAllFilterIfPossible () {
354 if (!this.authService.isLoggedIn()) return
356 this.authService.userInformationLoaded
358 const user = this.authService.getUser()
359 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
363 private calcPageSizes () {
364 if (this.screenService.isInMobileView()) {
365 this.pagination.itemsPerPage = 5
369 private setScrollRouteParams () {
371 if (this.angularState) return
373 this.angularState = 42
375 const queryParams = {
376 'a-state': this.angularState,
377 categoryOneOf: this.categoryOneOf
380 let path = this.getUrlWithoutParams()
381 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
383 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
386 private loadUserAndSettings () {
387 return this.userService.getAnonymousOrLoggedUser()
389 this.userMiniature = user
391 if (!this.loadUserVideoPreferences) return
393 this.languageOneOf = user.videoLanguages
394 this.nsfwPolicy = user.nsfwPolicy
398 private getUrlWithoutParams () {
399 const urlTree = this.router.parseUrl(this.router.url)
400 urlTree.queryParams = {}
402 return urlTree.toString()