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'
14 import { OwnerDisplayType } from '@app/shared/video/video-miniature.component'
15 import { Syndication } from '@app/shared/video/syndication.model'
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
43 protected baseVideoWidth = 215
44 protected baseVideoHeight = 205
46 protected abstract notificationsService: NotificationsService
47 protected abstract authService: AuthService
48 protected abstract router: Router
49 protected abstract route: ActivatedRoute
50 protected abstract screenService: ScreenService
51 protected abstract i18n: I18n
52 protected abstract location: Location
53 protected abstract currentRoute: string
54 abstract titlePage: string
56 protected loadedPages: { [ id: number ]: Video[] } = {}
57 protected loadingPage: { [ id: number ]: boolean } = {}
58 protected otherRouteParams = {}
60 private resizeSubscription: Subscription
62 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
63 abstract generateSyndicationList (): void
66 return this.authService.getUser()
70 // Subscribe to route changes
71 const routeParams = this.route.snapshot.queryParams
72 this.loadRouteParams(routeParams)
74 this.resizeSubscription = fromEvent(window, 'resize')
75 .pipe(debounceTime(500))
76 .subscribe(() => this.calcPageSizes())
79 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
83 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
86 pageByVideoId (index: number, page: Video[]) {
87 // Video are unique in all pages
88 return page.length !== 0 ? page[0].id : 0
91 videoById (index: number, video: Video) {
100 if (this.hasMoreVideos()) {
105 onPageChanged (page: number) {
106 this.pagination.currentPage = page
107 this.setNewRouteParams()
111 this.loadedPages = {}
112 this.loadMoreVideos(this.pagination.currentPage)
115 loadMoreVideos (page: number, loadOnTop = false) {
116 this.adjustVideoPageHeight()
118 const currentY = window.scrollY
120 if (this.loadedPages[page] !== undefined) return
121 if (this.loadingPage[page] === true) return
123 this.loadingPage[page] = true
124 const observable = this.getVideosObservable(page)
126 observable.subscribe(
127 ({ videos, totalVideos }) => {
128 this.loadingPage[page] = false
130 if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
132 // Paging is too high, return to the first one
133 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
134 this.pagination.currentPage = 1
135 this.setNewRouteParams()
136 return this.reloadVideos()
139 this.loadedPages[page] = videos
140 this.buildVideoPages()
141 this.pagination.totalItems = totalVideos
143 // Initialize infinite scroller now we loaded the first page
144 if (Object.keys(this.loadedPages).length === 1) {
145 // Wait elements creation
147 this.infiniteScroller.initialize()
149 // At our first load, we did not load the first page
150 // Load the previous page so the user can move on the top (and browser previous pages)
151 if (this.pagination.currentPage > 1) this.loadMoreVideos(this.pagination.currentPage - 1, true)
155 // Insert elements on the top but keep the scroll in the previous position
156 if (loadOnTop) setTimeout(() => { window.scrollTo(0, currentY + this.pageHeight) }, 0)
159 this.loadingPage[page] = false
160 this.notificationsService.error(this.i18n('Error'), error.message)
165 toggleModerationDisplay () {
166 throw new Error('toggleModerationDisplay is not implemented')
169 protected hasMoreVideos () {
171 if (this.pagination.totalItems === 0) return false
174 if (!this.pagination.totalItems) return true
176 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
177 return maxPage > this.maxPageLoaded()
180 protected previousPage () {
181 const min = this.minPageLoaded()
184 this.loadMoreVideos(min - 1, true)
188 protected nextPage () {
189 this.loadMoreVideos(this.maxPageLoaded() + 1)
192 protected buildRouteParams () {
193 // There is always a sort and a current page
196 page: this.pagination.currentPage
199 return Object.assign(params, this.otherRouteParams)
202 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
203 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
204 this.categoryOneOf = routeParams['categoryOneOf']
205 if (routeParams['page'] !== undefined) {
206 this.pagination.currentPage = parseInt(routeParams['page'], 10)
208 this.pagination.currentPage = 1
212 protected setNewRouteParams () {
213 const paramsObject = this.buildRouteParams()
215 const queryParams = Object.keys(paramsObject)
216 .map(p => p + '=' + paramsObject[p])
218 this.location.replaceState(this.currentRoute, queryParams)
221 protected buildVideoPages () {
222 this.videoPages = Object.values(this.loadedPages)
225 protected adjustVideoPageHeight () {
226 const numberOfPagesLoaded = Object.keys(this.loadedPages).length
227 if (!numberOfPagesLoaded) return
229 this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
232 protected buildVideoHeight () {
233 // Same ratios than base width/height
234 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
237 private minPageLoaded () {
238 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
241 private maxPageLoaded () {
242 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
245 private calcPageSizes () {
246 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
247 this.pagination.itemsPerPage = 5
249 // Video takes all the width
251 this.videoHeight = this.buildVideoHeight()
252 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
254 this.videoWidth = this.baseVideoWidth
255 this.videoHeight = this.baseVideoHeight
257 const videosWidth = this.videosElement.nativeElement.offsetWidth
258 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
259 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
262 // Rebuild pages because maybe we modified the number of items per page
263 const videos = [].concat(...this.videoPages)
264 this.loadedPages = {}
267 // Don't include the last page if it not complete
268 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
269 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
273 // Re fetch the last page
274 if (videos.length !== 0) {
275 this.loadMoreVideos(i)
277 this.buildVideoPages()
280 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)