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/miscs/date'
28 import { ServerConfig, 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: ServerConfig
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.getTmpConfig()
130 this.serverService.getConfig()
131 .subscribe(config => this.serverConfig = config)
133 this.groupedDateLabels = {
134 [GroupDate.UNKNOWN]: null,
135 [GroupDate.TODAY]: $localize`Today`,
136 [GroupDate.YESTERDAY]: $localize`Yesterday`,
137 [GroupDate.THIS_WEEK]: $localize`This week`,
138 [GroupDate.THIS_MONTH]: $localize`This month`,
139 [GroupDate.LAST_MONTH]: $localize`Last month`,
140 [GroupDate.OLDER]: $localize`Older`
143 // Subscribe to route changes
144 const routeParams = this.route.snapshot.queryParams
145 this.loadRouteParams(routeParams)
147 this.resizeSubscription = fromEvent(window, 'resize')
148 .pipe(debounceTime(500))
149 .subscribe(() => this.calcPageSizes())
153 const loadUserObservable = this.loadUserAndSettings()
154 loadUserObservable.subscribe(() => {
155 this.onUserLoadedSubject.next()
157 if (this.loadOnInit === true) this.loadMoreVideos()
160 this.userService.listenAnonymousUpdate()
161 .pipe(switchMap(() => this.loadUserAndSettings()))
163 if (this.hasDoneFirstQuery) this.reloadVideos()
166 // Display avatar in mobile view
167 if (this.screenService.isInMobileView()) {
168 this.displayOptions.avatar = true
173 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
176 ngAfterContentInit () {
177 if (this.videoListHeader) {
178 // some components don't use the header: they use their own template, like my-history.component.html
179 this.setHeader.apply(this, [ this.HeaderComponent, this.headerComponentInjector ])
188 this.disabled = false
191 videoById (index: number, video: Video) {
196 if (this.disabled) return
199 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
201 console.log('near of bottom')
202 this.pagination.currentPage += 1
204 this.setScrollRouteParams()
206 this.loadMoreVideos()
209 loadMoreVideos (reset = false) {
210 this.getVideosObservable(this.pagination.currentPage).subscribe(
212 this.hasDoneFirstQuery = true
213 this.lastQueryLength = data.length
215 if (reset) this.videos = []
216 this.videos = this.videos.concat(data)
218 if (this.groupByDate) this.buildGroupedDateLabels()
222 this.onDataSubject.next(data)
226 const message = $localize`Cannot load more videos. Try again later.`
228 console.error(message, { error })
229 this.notifier.error(message)
235 this.pagination.currentPage = 1
236 this.loadMoreVideos(true)
239 removeVideoFromArray (video: Video) {
240 this.videos = this.videos.filter(v => v.id !== video.id)
243 buildGroupedDateLabels () {
244 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
248 value: GroupDate.TODAY,
249 validator: (d: Date) => isToday(d)
252 value: GroupDate.YESTERDAY,
253 validator: (d: Date) => isYesterday(d)
256 value: GroupDate.THIS_WEEK,
257 validator: (d: Date) => isLastWeek(d)
260 value: GroupDate.THIS_MONTH,
261 validator: (d: Date) => isThisMonth(d)
264 value: GroupDate.LAST_MONTH,
265 validator: (d: Date) => isLastMonth(d)
268 value: GroupDate.OLDER,
269 validator: () => true
273 for (const video of this.videos) {
274 const publishedDate = video.publishedAt
276 for (let i = 0; i < periods.length; i++) {
277 const period = periods[i]
279 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
281 if (currentGroupedDate !== period.value) {
282 currentGroupedDate = period.value
283 this.groupedDates[ video.id ] = currentGroupedDate
292 getCurrentGroupedDateLabel (video: Video) {
293 if (this.groupByDate === false) return undefined
295 return this.groupedDateLabels[this.groupedDates[video.id]]
298 toggleModerationDisplay () {
299 throw new Error('toggleModerationDisplay ' + $localize`function is not implemented`)
303 t: Type<any> = this.HeaderComponent,
304 i: Injector = this.headerComponentInjector
306 const injector = i || Injector.create({
310 titlePage: this.titlePage,
311 titleTooltip: this.titleTooltip
315 const viewContainerRef = this.videoListHeader
316 viewContainerRef.clear()
318 const componentFactory = this.cfr.resolveComponentFactory(t)
319 viewContainerRef.createComponent(componentFactory, 0, injector)
322 // On videos hook for children that want to do something
323 protected onMoreVideos () { /* empty */ }
325 protected load () { /* empty */ }
327 // Hook if the page has custom route params
328 protected loadPageRouteParams (_queryParams: Params) { /* empty */ }
330 protected loadRouteParams (queryParams: Params) {
331 this.sort = queryParams[ 'sort' ] as VideoSortField || this.defaultSort
332 this.categoryOneOf = queryParams[ 'categoryOneOf' ]
333 this.angularState = queryParams[ 'a-state' ]
335 this.loadPageRouteParams(queryParams)
338 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
339 if (base === 'local') {
340 return existing === 'local'
341 ? 'all-local' as 'all-local'
345 return existing === 'all'
350 protected enableAllFilterIfPossible () {
351 if (!this.authService.isLoggedIn()) return
353 this.authService.userInformationLoaded
355 const user = this.authService.getUser()
356 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
360 private calcPageSizes () {
361 if (this.screenService.isInMobileView()) {
362 this.pagination.itemsPerPage = 5
366 private setScrollRouteParams () {
368 if (this.angularState) return
370 this.angularState = 42
372 const queryParams = {
373 'a-state': this.angularState,
374 categoryOneOf: this.categoryOneOf
377 let path = this.getUrlWithoutParams()
378 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
380 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
383 private loadUserAndSettings () {
384 return this.userService.getAnonymousOrLoggedUser()
386 this.userMiniature = user
388 if (!this.loadUserVideoPreferences) return
390 this.languageOneOf = user.videoLanguages
391 this.nsfwPolicy = user.nsfwPolicy
395 private getUrlWithoutParams () {
396 const urlTree = this.router.parseUrl(this.router.url)
397 urlTree.queryParams = {}
399 return urlTree.toString()