-import { debounceTime } from 'rxjs/operators'
-import { ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'
+import { debounceTime, first, tap } from 'rxjs/operators'
+import { OnDestroy, OnInit } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
-import { Location } from '@angular/common'
-import { isInMobileView } from '@app/shared/misc/utils'
-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 { VideoSortField } from './sort-field.type'
import { Video } from './video.model'
+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 { ResultList, ServerConfig } from '@shared/models'
+
+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
-
+export abstract class AbstractVideoList implements OnInit, OnDestroy, DisableForReuseHook {
pagination: ComponentPagination = {
currentPage: 1,
- itemsPerPage: 10,
+ itemsPerPage: 25,
totalItems: null
}
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[] = []
+ disabled = false
+
+ displayOptions: MiniatureDisplayOptions = {
+ date: true,
+ views: true,
+ by: true,
+ privacyLabel: true,
+ privacyText: false,
+ state: false,
+ blacklistInfo: false
+ }
+
+ onDataSubject = new Subject<any[]>()
- protected baseVideoWidth = 215
- protected baseVideoHeight = 230
+ protected serverConfig: ServerConfig
- protected abstract notificationsService: NotificationsService
+ protected abstract notifier: Notifier
protected abstract authService: AuthService
- protected abstract router: Router
protected abstract route: ActivatedRoute
+ protected abstract serverService: ServerService
+ protected abstract screenService: ScreenService
+ 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 } = {}
- abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
- abstract generateSyndicationList ()
+ abstract getVideosObservable (page: number): Observable<ResultList<Video>>
+
+ 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())
+ }
}
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
+
+ // Last page
+ if (this.pagination.totalItems <= (this.pagination.currentPage * this.pagination.itemsPerPage)) return
- loadMoreVideos (page: number) {
- if (this.loadedPages[page] !== undefined) return
- if (this.loadingPage[page] === true) return
+ this.pagination.currentPage += 1
- this.loadingPage[page] = true
- const observable = this.getVideosObservable(page)
+ this.setScrollRouteParams()
+
+ this.loadMoreVideos()
+ }
- observable.subscribe(
- ({ videos, totalVideos }) => {
- this.loadingPage[page] = false
+ loadMoreVideos () {
+ this.getVideosObservable(this.pagination.currentPage).subscribe(
+ ({ data, total }) => {
+ this.pagination.totalItems = total
+ 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()
+ }
- // 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 (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
- // Rebuild pages because maybe we modified the number of items per page
- const videos = [].concat(...this.videoPages)
- this.loadedPages = {}
+ this.angularState = 42
- 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++
+ const queryParams = {
+ 'a-state': this.angularState,
+ categoryOneOf: this.categoryOneOf
}
- // Re fetch the last page
- if (videos.length !== 0) {
- this.loadMoreVideos(i)
- } else {
- this.buildVideoPages()
+ let path = this.router.url
+ if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
+
+ this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
+ }
+
+ private loadUserVideoLanguagesIfNeeded () {
+ if (!this.authService.isLoggedIn() || !this.useUserVideoLanguagePreferences) {
+ 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)
+ )
}
}