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 // tslint:disable-next-line: 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.apply(this, [ 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).subscribe(
209 this.hasDoneFirstQuery = true
210 this.lastQueryLength = data.length
212 if (reset) this.videos = []
213 this.videos = this.videos.concat(data)
215 if (this.groupByDate) this.buildGroupedDateLabels()
219 this.onDataSubject.next(data)
223 const message = $localize`Cannot load more videos. Try again later.`
225 console.error(message, { error })
226 this.notifier.error(message)
232 this.pagination.currentPage = 1
233 this.loadMoreVideos(true)
236 removeVideoFromArray (video: Video) {
237 this.videos = this.videos.filter(v => v.id !== video.id)
240 buildGroupedDateLabels () {
241 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
245 value: GroupDate.TODAY,
246 validator: (d: Date) => isToday(d)
249 value: GroupDate.YESTERDAY,
250 validator: (d: Date) => isYesterday(d)
253 value: GroupDate.THIS_WEEK,
254 validator: (d: Date) => isLastWeek(d)
257 value: GroupDate.THIS_MONTH,
258 validator: (d: Date) => isThisMonth(d)
261 value: GroupDate.LAST_MONTH,
262 validator: (d: Date) => isLastMonth(d)
265 value: GroupDate.OLDER,
266 validator: () => true
270 for (const video of this.videos) {
271 const publishedDate = video.publishedAt
273 for (let i = 0; i < periods.length; i++) {
274 const period = periods[i]
276 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
278 if (currentGroupedDate !== period.value) {
279 currentGroupedDate = period.value
280 this.groupedDates[ video.id ] = currentGroupedDate
289 getCurrentGroupedDateLabel (video: Video) {
290 if (this.groupByDate === false) return undefined
292 return this.groupedDateLabels[this.groupedDates[video.id]]
295 toggleModerationDisplay () {
296 throw new Error('toggleModerationDisplay ' + $localize`function is not implemented`)
300 t: Type<any> = this.HeaderComponent,
301 i: Injector = this.headerComponentInjector
303 const injector = i || Injector.create({
307 titlePage: this.titlePage,
308 titleTooltip: this.titleTooltip
312 const viewContainerRef = this.videoListHeader
313 viewContainerRef.clear()
315 const componentFactory = this.cfr.resolveComponentFactory(t)
316 viewContainerRef.createComponent(componentFactory, 0, injector)
319 // Can be redefined by child
324 // On videos hook for children that want to do something
325 protected onMoreVideos () { /* empty */ }
327 protected load () { /* empty */ }
329 // Hook if the page has custom route params
330 protected loadPageRouteParams (_queryParams: Params) { /* empty */ }
332 protected loadRouteParams (queryParams: Params) {
333 this.sort = queryParams[ 'sort' ] as VideoSortField || this.defaultSort
334 this.categoryOneOf = queryParams[ 'categoryOneOf' ]
335 this.angularState = queryParams[ 'a-state' ]
337 this.loadPageRouteParams(queryParams)
340 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
341 if (base === 'local') {
342 return existing === 'local'
343 ? 'all-local' as 'all-local'
347 return existing === 'all'
352 protected enableAllFilterIfPossible () {
353 if (!this.authService.isLoggedIn()) return
355 this.authService.userInformationLoaded
357 const user = this.authService.getUser()
358 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
362 private calcPageSizes () {
363 if (this.screenService.isInMobileView()) {
364 this.pagination.itemsPerPage = 5
368 private setScrollRouteParams () {
370 if (this.angularState) return
372 this.angularState = 42
374 const queryParams = {
375 'a-state': this.angularState,
376 categoryOneOf: this.categoryOneOf
379 let path = this.getUrlWithoutParams()
380 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
382 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
385 private loadUserAndSettings () {
386 return this.userService.getAnonymousOrLoggedUser()
388 this.userMiniature = user
390 if (!this.loadUserVideoPreferences) return
392 this.languageOneOf = user.videoLanguages
393 this.nsfwPolicy = user.nsfwPolicy
397 private getUrlWithoutParams () {
398 const urlTree = this.router.parseUrl(this.router.url)
399 urlTree.queryParams = {}
401 return urlTree.toString()