-import { debounceTime } from 'rxjs/operators'
-import { ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { debounceTime, first, tap, throttleTime } from 'rxjs/operators'
+import { OnDestroy, OnInit } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
-import { Location } from '@angular/common'
-import { InfiniteScrollerDirective } from '@app/shared/video/infinite-scroller.directive'
-import { NotificationsService } from 'angular2-notifications'
-import { fromEvent, Observable, Subscription } from 'rxjs'
+import { fromEvent, Observable, of, Subject, Subscription } from 'rxjs'
import { AuthService } from '../../core/auth'
-import { ComponentPagination } from '../rest/component-pagination.model'
+import { ComponentPaginationLight } from '../rest/component-pagination.model'
import { VideoSortField } from './sort-field.type'
import { Video } from './video.model'
-import { I18n } from '@ngx-translate/i18n-polyfill'
import { ScreenService } from '@app/shared/misc/screen.service'
+import { MiniatureDisplayOptions, OwnerDisplayType } from '@app/shared/video/video-miniature.component'
+import { Syndication } from '@app/shared/video/syndication.model'
+import { Notifier, ServerService } from '@app/core'
+import { DisableForReuseHook } from '@app/core/routing/disable-for-reuse-hook'
+import { I18n } from '@ngx-translate/i18n-polyfill'
+import { isLastMonth, isLastWeek, isToday, isYesterday } from '@shared/core-utils/miscs/date'
+import { ServerConfig } from '@shared/models'
+import { GlobalIconName } from '@app/shared/images/global-icon.component'
+import { UserService, User } from '../users'
+import { LocalStorageService } from '../misc/storage.service'
+
+enum GroupDate {
+ UNKNOWN = 0,
+ TODAY = 1,
+ YESTERDAY = 2,
+ LAST_WEEK = 3,
+ LAST_MONTH = 4,
+ OLDER = 5
+}
-export abstract class AbstractVideoList implements OnInit, OnDestroy {
- private static LINES_PER_PAGE = 4
-
- @ViewChild('videosElement') videosElement: ElementRef
- @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
-
- pagination: ComponentPagination = {
+export abstract class AbstractVideoList implements OnInit, OnDestroy, DisableForReuseHook {
+ pagination: ComponentPaginationLight = {
currentPage: 1,
- itemsPerPage: 10,
- totalItems: null
+ itemsPerPage: 25
}
sort: VideoSortField = '-publishedAt'
+
+ categoryOneOf?: number
+ languageOneOf?: string[]
defaultSort: VideoSortField = '-publishedAt'
- syndicationItems = []
+
+ syndicationItems: Syndication[] = []
loadOnInit = true
- marginContent = true
- pageHeight: number
- videoWidth: number
- videoHeight: number
- videoPages: Video[][] = []
+ useUserVideoLanguagePreferences = false
+ ownerDisplayType: OwnerDisplayType = 'account'
+ displayModerationBlock = false
+ titleTooltip: string
+ displayVideoActions = true
+ groupByDate = false
+
+ videos: Video[] = []
+ hasDoneFirstQuery = false
+ disabled = false
+
+ displayOptions: MiniatureDisplayOptions = {
+ date: true,
+ views: true,
+ by: true,
+ privacyLabel: true,
+ privacyText: false,
+ state: false,
+ blacklistInfo: false
+ }
- protected baseVideoWidth = 215
- protected baseVideoHeight = 230
+ actions: {
+ routerLink: string
+ iconName: GlobalIconName
+ label: string
+ }[] = []
- protected abstract notificationsService: NotificationsService
+ onDataSubject = new Subject<any[]>()
+
+ protected serverConfig: ServerConfig
+
+ protected abstract notifier: Notifier
protected abstract authService: AuthService
- protected abstract router: Router
+ protected abstract userService: UserService
protected abstract route: ActivatedRoute
+ protected abstract serverService: ServerService
protected abstract screenService: ScreenService
+ protected abstract storageService: LocalStorageService
+ protected abstract router: Router
protected abstract i18n: I18n
- protected abstract location: Location
- protected abstract currentRoute: string
abstract titlePage: string
- protected loadedPages: { [ id: number ]: Video[] } = {}
- protected loadingPage: { [ id: number ]: boolean } = {}
- protected otherRouteParams = {}
-
private resizeSubscription: Subscription
+ private angularState: number
+
+ private groupedDateLabels: { [id in GroupDate]: string }
+ private groupedDates: { [id: number]: GroupDate } = {}
+
+ private lastQueryLength: number
+
+ abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
- abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
- abstract generateSyndicationList ()
+ abstract generateSyndicationList (): void
get user () {
return this.authService.getUser()
}
ngOnInit () {
+ this.serverConfig = this.serverService.getTmpConfig()
+ this.serverService.getConfig()
+ .subscribe(config => this.serverConfig = config)
+
+ this.groupedDateLabels = {
+ [GroupDate.UNKNOWN]: null,
+ [GroupDate.TODAY]: this.i18n('Today'),
+ [GroupDate.YESTERDAY]: this.i18n('Yesterday'),
+ [GroupDate.LAST_WEEK]: this.i18n('Last week'),
+ [GroupDate.LAST_MONTH]: this.i18n('Last month'),
+ [GroupDate.OLDER]: this.i18n('Older')
+ }
+
// Subscribe to route changes
const routeParams = this.route.snapshot.queryParams
this.loadRouteParams(routeParams)
.subscribe(() => this.calcPageSizes())
this.calcPageSizes()
- if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
+
+ const loadUserObservable = this.loadUserVideoLanguagesIfNeeded()
+
+ if (this.loadOnInit === true) {
+ loadUserObservable.subscribe(() => this.loadMoreVideos())
+ }
+
+ this.storageService.watch([
+ User.KEYS.NSFW_POLICY,
+ User.KEYS.VIDEO_LANGUAGES
+ ]).pipe(throttleTime(200)).subscribe(
+ () => {
+ this.loadUserVideoLanguagesIfNeeded()
+ if (this.hasDoneFirstQuery) this.reloadVideos()
+ }
+ )
}
ngOnDestroy () {
if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
}
- onNearOfTop () {
- this.previousPage()
+ disableForReuse () {
+ this.disabled = true
}
- onNearOfBottom () {
- if (this.hasMoreVideos()) {
- this.nextPage()
- }
+ enabledForReuse () {
+ this.disabled = false
}
- onPageChanged (page: number) {
- this.pagination.currentPage = page
- this.setNewRouteParams()
+ videoById (index: number, video: Video) {
+ return video.id
}
- reloadVideos () {
- this.loadedPages = {}
- this.loadMoreVideos(this.pagination.currentPage)
- }
+ onNearOfBottom () {
+ if (this.disabled) return
+
+ // No more results
+ if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
+
+ this.pagination.currentPage += 1
+
+ this.setScrollRouteParams()
- loadMoreVideos (page: number) {
- if (this.loadedPages[page] !== undefined) return
- if (this.loadingPage[page] === true) return
+ this.loadMoreVideos()
+ }
- this.loadingPage[page] = true
- const observable = this.getVideosObservable(page)
+ loadMoreVideos (reset = false) {
+ this.getVideosObservable(this.pagination.currentPage).subscribe(
+ ({ data }) => {
+ this.hasDoneFirstQuery = true
+ this.lastQueryLength = data.length
- observable.subscribe(
- ({ videos, totalVideos }) => {
- this.loadingPage[page] = false
+ if (reset) this.videos = []
+ this.videos = this.videos.concat(data)
- // Paging is too high, return to the first one
- if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
- this.pagination.currentPage = 1
- this.setNewRouteParams()
- return this.reloadVideos()
- }
+ if (this.groupByDate) this.buildGroupedDateLabels()
- this.loadedPages[page] = videos
- this.buildVideoPages()
- this.pagination.totalItems = totalVideos
+ this.onMoreVideos()
- // Initialize infinite scroller now we loaded the first page
- if (Object.keys(this.loadedPages).length === 1) {
- // Wait elements creation
- setTimeout(() => this.infiniteScroller.initialize(), 500)
- }
+ this.onDataSubject.next(data)
},
+
error => {
- this.loadingPage[page] = false
- this.notificationsService.error(this.i18n('Error'), error.message)
+ const message = this.i18n('Cannot load more videos. Try again later.')
+
+ console.error(message, { error })
+ this.notifier.error(message)
}
)
}
- protected hasMoreVideos () {
- // No results
- if (this.pagination.totalItems === 0) return false
+ reloadVideos () {
+ this.pagination.currentPage = 1
+ this.loadMoreVideos(true)
+ }
- // Not loaded yet
- if (!this.pagination.totalItems) return true
+ toggleModerationDisplay () {
+ throw new Error('toggleModerationDisplay is not implemented')
+ }
- const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
- return maxPage > this.maxPageLoaded()
+ removeVideoFromArray (video: Video) {
+ this.videos = this.videos.filter(v => v.id !== video.id)
}
- protected previousPage () {
- const min = this.minPageLoaded()
+ buildGroupedDateLabels () {
+ let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
- if (min > 1) {
- this.loadMoreVideos(min - 1)
- }
- }
+ for (const video of this.videos) {
+ const publishedDate = video.publishedAt
- protected nextPage () {
- this.loadMoreVideos(this.maxPageLoaded() + 1)
- }
+ if (currentGroupedDate <= GroupDate.TODAY && isToday(publishedDate)) {
+ if (currentGroupedDate === GroupDate.TODAY) continue
- protected buildRouteParams () {
- // There is always a sort and a current page
- const params = {
- sort: this.sort,
- page: this.pagination.currentPage
- }
+ currentGroupedDate = GroupDate.TODAY
+ this.groupedDates[ video.id ] = currentGroupedDate
+ continue
+ }
- return Object.assign(params, this.otherRouteParams)
- }
+ if (currentGroupedDate <= GroupDate.YESTERDAY && isYesterday(publishedDate)) {
+ if (currentGroupedDate === GroupDate.YESTERDAY) continue
- protected loadRouteParams (routeParams: { [ key: string ]: any }) {
- this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
+ currentGroupedDate = GroupDate.YESTERDAY
+ this.groupedDates[ video.id ] = currentGroupedDate
+ continue
+ }
- if (routeParams['page'] !== undefined) {
- this.pagination.currentPage = parseInt(routeParams['page'], 10)
- } else {
- this.pagination.currentPage = 1
- }
- }
+ if (currentGroupedDate <= GroupDate.LAST_WEEK && isLastWeek(publishedDate)) {
+ if (currentGroupedDate === GroupDate.LAST_WEEK) continue
- protected setNewRouteParams () {
- const paramsObject = this.buildRouteParams()
+ currentGroupedDate = GroupDate.LAST_WEEK
+ this.groupedDates[ video.id ] = currentGroupedDate
+ continue
+ }
- const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
- this.location.replaceState(this.currentRoute, queryParams)
- }
+ if (currentGroupedDate <= GroupDate.LAST_MONTH && isLastMonth(publishedDate)) {
+ if (currentGroupedDate === GroupDate.LAST_MONTH) continue
- protected buildVideoPages () {
- this.videoPages = Object.values(this.loadedPages)
- }
+ currentGroupedDate = GroupDate.LAST_MONTH
+ this.groupedDates[ video.id ] = currentGroupedDate
+ continue
+ }
- protected buildVideoHeight () {
- // Same ratios than base width/height
- return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
+ if (currentGroupedDate <= GroupDate.OLDER) {
+ if (currentGroupedDate === GroupDate.OLDER) continue
+
+ currentGroupedDate = GroupDate.OLDER
+ this.groupedDates[ video.id ] = currentGroupedDate
+ }
+ }
}
- private minPageLoaded () {
- return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
+ getCurrentGroupedDateLabel (video: Video) {
+ if (this.groupByDate === false) return undefined
+
+ return this.groupedDateLabels[this.groupedDates[video.id]]
}
- private maxPageLoaded () {
- return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
+ // On videos hook for children that want to do something
+ protected onMoreVideos () { /* empty */ }
+
+ protected loadRouteParams (routeParams: { [ key: string ]: any }) {
+ this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
+ this.categoryOneOf = routeParams[ 'categoryOneOf' ]
+ this.angularState = routeParams[ 'a-state' ]
}
private calcPageSizes () {
- if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
+ if (this.screenService.isInMobileView()) {
this.pagination.itemsPerPage = 5
+ }
+ }
- // Video takes all the width
- this.videoWidth = -1
- this.videoHeight = this.buildVideoHeight()
- this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
- } else {
- this.videoWidth = this.baseVideoWidth
- this.videoHeight = this.baseVideoHeight
-
- const videosWidth = this.videosElement.nativeElement.offsetWidth
- this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
- this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
+ private setScrollRouteParams () {
+ // Already set
+ if (this.angularState) return
+
+ this.angularState = 42
+
+ const queryParams = {
+ 'a-state': this.angularState,
+ categoryOneOf: this.categoryOneOf
}
- // Rebuild pages because maybe we modified the number of items per page
- const videos = [].concat(...this.videoPages)
- this.loadedPages = {}
+ let path = this.router.url
+ if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
+
+ this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
+ }
- let i = 1
- // Don't include the last page if it not complete
- while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
- this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
- i++
+ private loadUserVideoLanguagesIfNeeded () {
+ if (!this.useUserVideoLanguagePreferences) {
+ return of(true)
}
- // Re fetch the last page
- if (videos.length !== 0) {
- this.loadMoreVideos(i)
- } else {
- this.buildVideoPages()
+ if (!this.authService.isLoggedIn()) {
+ this.languageOneOf = this.userService.getAnonymousUser().videoLanguages
+ return of(true)
}
- console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)
+ return this.authService.userInformationLoaded
+ .pipe(
+ first(),
+ tap(() => this.languageOneOf = this.user.videoLanguages)
+ )
}
}