1 import { debounceTime } from 'rxjs/operators'
2 import { ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { Location } from '@angular/common'
5 import { InfiniteScrollerDirective } from '@app/shared/video/infinite-scroller.directive'
6 import { fromEvent, Observable, Subscription } from 'rxjs'
7 import { AuthService } from '../../core/auth'
8 import { ComponentPagination } from '../rest/component-pagination.model'
9 import { VideoSortField } from './sort-field.type'
10 import { Video } from './video.model'
11 import { I18n } from '@ngx-translate/i18n-polyfill'
12 import { ScreenService } from '@app/shared/misc/screen.service'
13 import { OwnerDisplayType } from '@app/shared/video/video-miniature.component'
14 import { Syndication } from '@app/shared/video/syndication.model'
15 import { Notifier } from '@app/core'
17 export abstract class AbstractVideoList implements OnInit, OnDestroy {
18 private static LINES_PER_PAGE = 4
20 @ViewChild('videosElement') videosElement: ElementRef
21 @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
23 pagination: ComponentPagination = {
28 sort: VideoSortField = '-publishedAt'
29 categoryOneOf?: number
30 defaultSort: VideoSortField = '-publishedAt'
31 syndicationItems: Syndication[] = []
38 videoPages: Video[][] = []
39 ownerDisplayType: OwnerDisplayType = 'account'
40 firstLoadedPage: number
41 displayModerationBlock = false
44 protected baseVideoWidth = 215
45 protected baseVideoHeight = 205
47 protected abstract notifier: Notifier
48 protected abstract authService: AuthService
49 protected abstract router: Router
50 protected abstract route: ActivatedRoute
51 protected abstract screenService: ScreenService
52 protected abstract i18n: I18n
53 protected abstract location: Location
54 protected abstract currentRoute: string
55 abstract titlePage: string
57 protected loadedPages: { [ id: number ]: Video[] } = {}
58 protected loadingPage: { [ id: number ]: boolean } = {}
59 protected otherRouteParams = {}
61 private resizeSubscription: Subscription
63 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
64 abstract generateSyndicationList (): void
67 return this.authService.getUser()
71 // Subscribe to route changes
72 const routeParams = this.route.snapshot.queryParams
73 this.loadRouteParams(routeParams)
75 this.resizeSubscription = fromEvent(window, 'resize')
76 .pipe(debounceTime(500))
77 .subscribe(() => this.calcPageSizes())
80 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
84 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
87 pageByVideoId (index: number, page: Video[]) {
88 // Video are unique in all pages
89 return page.length !== 0 ? page[0].id : 0
92 videoById (index: number, video: Video) {
101 if (this.hasMoreVideos()) {
106 onPageChanged (page: number) {
107 this.pagination.currentPage = page
108 this.setNewRouteParams()
112 this.loadedPages = {}
113 this.loadMoreVideos(this.pagination.currentPage)
116 loadMoreVideos (page: number, loadOnTop = false) {
117 this.adjustVideoPageHeight()
119 const currentY = window.scrollY
121 if (this.loadedPages[page] !== undefined) return
122 if (this.loadingPage[page] === true) return
124 this.loadingPage[page] = true
125 const observable = this.getVideosObservable(page)
127 observable.subscribe(
128 ({ videos, totalVideos }) => {
129 this.loadingPage[page] = false
131 if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
133 // Paging is too high, return to the first one
134 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
135 this.pagination.currentPage = 1
136 this.setNewRouteParams()
137 return this.reloadVideos()
140 this.loadedPages[page] = videos
141 this.buildVideoPages()
142 this.pagination.totalItems = totalVideos
144 // Initialize infinite scroller now we loaded the first page
145 if (Object.keys(this.loadedPages).length === 1) {
146 // Wait elements creation
148 this.infiniteScroller.initialize()
150 // At our first load, we did not load the first page
151 // Load the previous page so the user can move on the top (and browser previous pages)
152 if (this.pagination.currentPage > 1) this.loadMoreVideos(this.pagination.currentPage - 1, true)
156 // Insert elements on the top but keep the scroll in the previous position
157 if (loadOnTop) setTimeout(() => { window.scrollTo(0, currentY + this.pageHeight) }, 0)
160 this.loadingPage[page] = false
161 this.notifier.error(error.message)
166 toggleModerationDisplay () {
167 throw new Error('toggleModerationDisplay is not implemented')
170 protected hasMoreVideos () {
172 if (this.pagination.totalItems === 0) return false
175 if (!this.pagination.totalItems) return true
177 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
178 return maxPage > this.maxPageLoaded()
181 protected previousPage () {
182 const min = this.minPageLoaded()
185 this.loadMoreVideos(min - 1, true)
189 protected nextPage () {
190 this.loadMoreVideos(this.maxPageLoaded() + 1)
193 protected buildRouteParams () {
194 // There is always a sort and a current page
197 page: this.pagination.currentPage
200 return Object.assign(params, this.otherRouteParams)
203 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
204 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
205 this.categoryOneOf = routeParams['categoryOneOf']
206 if (routeParams['page'] !== undefined) {
207 this.pagination.currentPage = parseInt(routeParams['page'], 10)
209 this.pagination.currentPage = 1
213 protected setNewRouteParams () {
214 const paramsObject = this.buildRouteParams()
216 const queryParams = Object.keys(paramsObject)
217 .map(p => p + '=' + paramsObject[p])
219 this.location.replaceState(this.currentRoute, queryParams)
222 protected buildVideoPages () {
223 this.videoPages = Object.values(this.loadedPages)
226 protected adjustVideoPageHeight () {
227 const numberOfPagesLoaded = Object.keys(this.loadedPages).length
228 if (!numberOfPagesLoaded) return
230 this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
233 protected buildVideoHeight () {
234 // Same ratios than base width/height
235 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
238 private minPageLoaded () {
239 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
242 private maxPageLoaded () {
243 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
246 private calcPageSizes () {
247 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
248 this.pagination.itemsPerPage = 5
250 // Video takes all the width
252 this.videoHeight = this.buildVideoHeight()
253 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
255 this.videoWidth = this.baseVideoWidth
256 this.videoHeight = this.baseVideoHeight
258 const videosWidth = this.videosElement.nativeElement.offsetWidth
259 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
260 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
263 // Rebuild pages because maybe we modified the number of items per page
264 const videos = [].concat(...this.videoPages)
265 this.loadedPages = {}
268 // Don't include the last page if it not complete
269 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
270 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
274 // Re fetch the last page
275 if (videos.length !== 0) {
276 this.loadMoreVideos(i)
278 this.buildVideoPages()
281 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)