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, 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 loadUserVideoPreferences = false
68 ownerDisplayType: OwnerDisplayType = 'account'
69 displayModerationBlock = false
71 displayVideoActions = true
75 hasDoneFirstQuery = false
78 displayOptions: MiniatureDisplayOptions = {
90 iconName: GlobalIconName
95 click?: (e: Event) => void
98 onDataSubject = new Subject<any[]>()
102 protected onUserLoadedSubject = new ReplaySubject<void>(1)
104 protected serverConfig: ServerConfig
106 protected abstract notifier: Notifier
107 protected abstract authService: AuthService
108 protected abstract userService: UserService
109 protected abstract route: ActivatedRoute
110 protected abstract serverService: ServerService
111 protected abstract screenService: ScreenService
112 protected abstract storageService: LocalStorageService
113 protected abstract router: Router
114 protected abstract cfr: ComponentFactoryResolver
115 abstract titlePage: string
117 private resizeSubscription: Subscription
118 private angularState: number
120 private groupedDateLabels: { [id in GroupDate]: string }
121 private groupedDates: { [id: number]: GroupDate } = {}
123 private lastQueryLength: number
125 abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
127 abstract generateSyndicationList (): void
130 this.serverConfig = this.serverService.getTmpConfig()
131 this.serverService.getConfig()
132 .subscribe(config => this.serverConfig = config)
134 this.groupedDateLabels = {
135 [GroupDate.UNKNOWN]: null,
136 [GroupDate.TODAY]: $localize`Today`,
137 [GroupDate.YESTERDAY]: $localize`Yesterday`,
138 [GroupDate.THIS_WEEK]: $localize`This week`,
139 [GroupDate.THIS_MONTH]: $localize`This month`,
140 [GroupDate.LAST_MONTH]: $localize`Last month`,
141 [GroupDate.OLDER]: $localize`Older`
144 // Subscribe to route changes
145 const routeParams = this.route.snapshot.queryParams
146 this.loadRouteParams(routeParams)
148 this.resizeSubscription = fromEvent(window, 'resize')
149 .pipe(debounceTime(500))
150 .subscribe(() => this.calcPageSizes())
154 const loadUserObservable = this.loadUserAndSettings()
155 loadUserObservable.subscribe(() => {
156 this.onUserLoadedSubject.next()
158 if (this.loadOnInit === true) this.loadMoreVideos()
161 this.userService.listenAnonymousUpdate()
162 .pipe(switchMap(() => this.loadUserAndSettings()))
164 if (this.hasDoneFirstQuery) this.reloadVideos()
167 // Display avatar in mobile view
168 if (this.screenService.isInMobileView()) {
169 this.displayOptions.avatar = true
174 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
177 ngAfterContentInit () {
178 if (this.videoListHeader) {
179 // some components don't use the header: they use their own template, like my-history.component.html
180 this.setHeader.apply(this, [ this.HeaderComponent, this.headerComponentInjector ])
189 this.disabled = false
192 videoById (index: number, video: Video) {
197 if (this.disabled) return
200 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
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 loadRouteParams (routeParams: { [ key: string ]: any }) {
326 this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
327 this.categoryOneOf = routeParams[ 'categoryOneOf' ]
328 this.angularState = routeParams[ 'a-state' ]
331 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
332 if (base === 'local') {
333 return existing === 'local'
334 ? 'all-local' as 'all-local'
338 return existing === 'all'
343 protected enableAllFilterIfPossible () {
344 if (!this.authService.isLoggedIn()) return
346 this.authService.userInformationLoaded
348 const user = this.authService.getUser()
349 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
353 private calcPageSizes () {
354 if (this.screenService.isInMobileView()) {
355 this.pagination.itemsPerPage = 5
359 private setScrollRouteParams () {
361 if (this.angularState) return
363 this.angularState = 42
365 const queryParams = {
366 'a-state': this.angularState,
367 categoryOneOf: this.categoryOneOf
370 let path = this.getUrlWithoutParams()
371 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
373 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
376 private loadUserAndSettings () {
377 return this.userService.getAnonymousOrLoggedUser()
379 this.userMiniature = user
381 if (!this.loadUserVideoPreferences) return
383 this.languageOneOf = user.videoLanguages
384 this.nsfwPolicy = user.nsfwPolicy
388 private getUrlWithoutParams () {
389 const urlTree = this.router.parseUrl(this.router.url)
390 urlTree.queryParams = {}
392 return urlTree.toString()