1 import { fromEvent, Observable, Subject, Subscription } from 'rxjs'
2 import { debounceTime, switchMap, tap } from 'rxjs/operators'
5 ComponentFactoryResolver,
13 } from '@angular/core'
14 import { ActivatedRoute, 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 { MiniatureDisplayOptions, OwnerDisplayType } from './video-miniature.component'
32 import { GenericHeaderComponent, VideoListHeaderComponent } from './video-list-header.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 useUserVideoPreferences = false
67 ownerDisplayType: OwnerDisplayType = 'account'
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 serverConfig: ServerConfig
103 protected abstract notifier: Notifier
104 protected abstract authService: AuthService
105 protected abstract userService: UserService
106 protected abstract route: ActivatedRoute
107 protected abstract serverService: ServerService
108 protected abstract screenService: ScreenService
109 protected abstract storageService: LocalStorageService
110 protected abstract router: Router
111 protected abstract cfr: ComponentFactoryResolver
112 abstract titlePage: string
114 private resizeSubscription: Subscription
115 private angularState: number
117 private groupedDateLabels: { [id in GroupDate]: string }
118 private groupedDates: { [id: number]: GroupDate } = {}
120 private lastQueryLength: number
122 abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
124 abstract generateSyndicationList (): void
127 this.serverConfig = this.serverService.getTmpConfig()
128 this.serverService.getConfig()
129 .subscribe(config => this.serverConfig = config)
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()
153 if (this.loadOnInit === true) {
154 loadUserObservable.subscribe(() => this.loadMoreVideos())
157 this.userService.listenAnonymousUpdate()
158 .pipe(switchMap(() => this.loadUserAndSettings()))
160 if (this.hasDoneFirstQuery) this.reloadVideos()
163 // Display avatar in mobile view
164 if (this.screenService.isInMobileView()) {
165 this.displayOptions.avatar = true
170 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
173 ngAfterContentInit () {
174 if (this.videoListHeader) {
175 // some components don't use the header: they use their own template, like my-history.component.html
176 this.setHeader.apply(this, [ this.HeaderComponent, this.headerComponentInjector ])
185 this.disabled = false
188 videoById (index: number, video: Video) {
193 if (this.disabled) return
196 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
198 this.pagination.currentPage += 1
200 this.setScrollRouteParams()
202 this.loadMoreVideos()
205 loadMoreVideos (reset = false) {
206 this.getVideosObservable(this.pagination.currentPage).subscribe(
208 this.hasDoneFirstQuery = true
209 this.lastQueryLength = data.length
211 if (reset) this.videos = []
212 this.videos = this.videos.concat(data)
214 if (this.groupByDate) this.buildGroupedDateLabels()
218 this.onDataSubject.next(data)
222 const message = $localize`Cannot load more videos. Try again later.`
224 console.error(message, { error })
225 this.notifier.error(message)
231 this.pagination.currentPage = 1
232 this.loadMoreVideos(true)
235 removeVideoFromArray (video: Video) {
236 this.videos = this.videos.filter(v => v.id !== video.id)
239 buildGroupedDateLabels () {
240 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
244 value: GroupDate.TODAY,
245 validator: (d: Date) => isToday(d)
248 value: GroupDate.YESTERDAY,
249 validator: (d: Date) => isYesterday(d)
252 value: GroupDate.THIS_WEEK,
253 validator: (d: Date) => isLastWeek(d)
256 value: GroupDate.THIS_MONTH,
257 validator: (d: Date) => isThisMonth(d)
260 value: GroupDate.LAST_MONTH,
261 validator: (d: Date) => isLastMonth(d)
264 value: GroupDate.OLDER,
265 validator: () => true
269 for (const video of this.videos) {
270 const publishedDate = video.publishedAt
272 for (let i = 0; i < periods.length; i++) {
273 const period = periods[i]
275 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
277 if (currentGroupedDate !== period.value) {
278 currentGroupedDate = period.value
279 this.groupedDates[ video.id ] = currentGroupedDate
288 getCurrentGroupedDateLabel (video: Video) {
289 if (this.groupByDate === false) return undefined
291 return this.groupedDateLabels[this.groupedDates[video.id]]
294 toggleModerationDisplay () {
295 throw new Error('toggleModerationDisplay ' + $localize`function is not implemented`)
299 t: Type<any> = this.HeaderComponent,
300 i: Injector = this.headerComponentInjector
302 const injector = i || Injector.create({
306 titlePage: this.titlePage,
307 titleTooltip: this.titleTooltip
311 const viewContainerRef = this.videoListHeader
312 viewContainerRef.clear()
314 const componentFactory = this.cfr.resolveComponentFactory(t)
315 viewContainerRef.createComponent(componentFactory, 0, injector)
318 // On videos hook for children that want to do something
319 protected onMoreVideos () { /* empty */ }
321 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
322 this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
323 this.categoryOneOf = routeParams[ 'categoryOneOf' ]
324 this.angularState = routeParams[ 'a-state' ]
327 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
328 if (base === 'local') {
329 return existing === 'local'
330 ? 'all-local' as 'all-local'
334 return existing === 'all'
339 protected enableAllFilterIfPossible () {
340 if (!this.authService.isLoggedIn()) return
342 this.authService.userInformationLoaded
344 const user = this.authService.getUser()
345 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
349 private calcPageSizes () {
350 if (this.screenService.isInMobileView()) {
351 this.pagination.itemsPerPage = 5
355 private setScrollRouteParams () {
357 if (this.angularState) return
359 this.angularState = 42
361 const queryParams = {
362 'a-state': this.angularState,
363 categoryOneOf: this.categoryOneOf
366 let path = this.getUrlWithoutParams()
367 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
369 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
372 private loadUserAndSettings () {
373 return this.userService.getAnonymousOrLoggedUser()
375 this.userMiniature = user
377 if (!this.useUserVideoPreferences) return
379 this.languageOneOf = user.videoLanguages
380 this.nsfwPolicy = user.nsfwPolicy
384 private getUrlWithoutParams () {
385 const urlTree = this.router.parseUrl(this.router.url)
386 urlTree.queryParams = {}
388 return urlTree.toString()