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 { NotificationsService } from 'angular2-notifications'
7 import { fromEvent, Observable, Subscription } from 'rxjs'
8 import { AuthService } from '../../core/auth'
9 import { ComponentPagination } from '../rest/component-pagination.model'
10 import { VideoSortField } from './sort-field.type'
11 import { Video } from './video.model'
12 import { I18n } from '@ngx-translate/i18n-polyfill'
13 import { ScreenService } from '@app/shared/misc/screen.service'
15 export abstract class AbstractVideoList implements OnInit, OnDestroy {
16 private static LINES_PER_PAGE = 4
18 @ViewChild('videosElement') videosElement: ElementRef
19 @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
21 pagination: ComponentPagination = {
26 sort: VideoSortField = '-publishedAt'
27 defaultSort: VideoSortField = '-publishedAt'
35 videoPages: Video[][] = []
37 protected baseVideoWidth = 215
38 protected baseVideoHeight = 230
40 protected abstract notificationsService: NotificationsService
41 protected abstract authService: AuthService
42 protected abstract router: Router
43 protected abstract route: ActivatedRoute
44 protected abstract screenService: ScreenService
45 protected abstract i18n: I18n
46 protected abstract location: Location
47 protected abstract currentRoute: string
48 abstract titlePage: string
50 protected loadedPages: { [ id: number ]: Video[] } = {}
51 protected loadingPage: { [ id: number ]: boolean } = {}
52 protected otherRouteParams = {}
54 private resizeSubscription: Subscription
56 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
57 abstract generateSyndicationList ()
60 return this.authService.getUser()
64 // Subscribe to route changes
65 const routeParams = this.route.snapshot.queryParams
66 this.loadRouteParams(routeParams)
68 this.resizeSubscription = fromEvent(window, 'resize')
69 .pipe(debounceTime(500))
70 .subscribe(() => this.calcPageSizes())
73 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
77 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
85 if (this.hasMoreVideos()) {
90 onPageChanged (page: number) {
91 this.pagination.currentPage = page
92 this.setNewRouteParams()
97 this.loadMoreVideos(this.pagination.currentPage)
100 loadMoreVideos (page: number) {
101 if (this.loadedPages[page] !== undefined) return
102 if (this.loadingPage[page] === true) return
104 this.loadingPage[page] = true
105 const observable = this.getVideosObservable(page)
107 observable.subscribe(
108 ({ videos, totalVideos }) => {
109 this.loadingPage[page] = false
111 // Paging is too high, return to the first one
112 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
113 this.pagination.currentPage = 1
114 this.setNewRouteParams()
115 return this.reloadVideos()
118 this.loadedPages[page] = videos
119 this.buildVideoPages()
120 this.pagination.totalItems = totalVideos
122 // Initialize infinite scroller now we loaded the first page
123 if (Object.keys(this.loadedPages).length === 1) {
124 // Wait elements creation
125 setTimeout(() => this.infiniteScroller.initialize(), 500)
129 this.loadingPage[page] = false
130 this.notificationsService.error(this.i18n('Error'), error.message)
135 protected hasMoreVideos () {
137 if (this.pagination.totalItems === 0) return false
140 if (!this.pagination.totalItems) return true
142 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
143 return maxPage > this.maxPageLoaded()
146 protected previousPage () {
147 const min = this.minPageLoaded()
150 this.loadMoreVideos(min - 1)
154 protected nextPage () {
155 this.loadMoreVideos(this.maxPageLoaded() + 1)
158 protected buildRouteParams () {
159 // There is always a sort and a current page
162 page: this.pagination.currentPage
165 return Object.assign(params, this.otherRouteParams)
168 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
169 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
171 if (routeParams['page'] !== undefined) {
172 this.pagination.currentPage = parseInt(routeParams['page'], 10)
174 this.pagination.currentPage = 1
178 protected setNewRouteParams () {
179 const paramsObject = this.buildRouteParams()
181 const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
182 this.location.replaceState(this.currentRoute, queryParams)
185 protected buildVideoPages () {
186 this.videoPages = Object.values(this.loadedPages)
189 protected buildVideoHeight () {
190 // Same ratios than base width/height
191 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
194 private minPageLoaded () {
195 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
198 private maxPageLoaded () {
199 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
202 private calcPageSizes () {
203 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
204 this.pagination.itemsPerPage = 5
206 // Video takes all the width
208 this.videoHeight = this.buildVideoHeight()
209 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
211 this.videoWidth = this.baseVideoWidth
212 this.videoHeight = this.baseVideoHeight
214 const videosWidth = this.videosElement.nativeElement.offsetWidth
215 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
216 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
219 // Rebuild pages because maybe we modified the number of items per page
220 const videos = [].concat(...this.videoPages)
221 this.loadedPages = {}
224 // Don't include the last page if it not complete
225 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
226 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
230 // Re fetch the last page
231 if (videos.length !== 0) {
232 this.loadMoreVideos(i)
234 this.buildVideoPages()
237 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)