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
45 protected baseVideoWidth = 215
46 protected baseVideoHeight = 205
48 protected abstract notifier: Notifier
49 protected abstract authService: AuthService
50 protected abstract router: Router
51 protected abstract route: ActivatedRoute
52 protected abstract screenService: ScreenService
53 protected abstract i18n: I18n
54 protected abstract location: Location
55 protected abstract currentRoute: string
56 abstract titlePage: string
58 protected loadedPages: { [ id: number ]: Video[] } = {}
59 protected loadingPage: { [ id: number ]: boolean } = {}
60 protected otherRouteParams = {}
62 private resizeSubscription: Subscription
64 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
65 abstract generateSyndicationList (): void
68 return this.authService.getUser()
72 // Subscribe to route changes
73 const routeParams = this.route.snapshot.queryParams
74 this.loadRouteParams(routeParams)
76 this.resizeSubscription = fromEvent(window, 'resize')
77 .pipe(debounceTime(500))
78 .subscribe(() => this.calcPageSizes())
81 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
85 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
88 pageByVideoId (index: number, page: Video[]) {
89 // Video are unique in all pages
90 return page.length !== 0 ? page[0].id : 0
93 videoById (index: number, video: Video) {
102 if (this.hasMoreVideos()) {
107 onPageChanged (page: number) {
108 this.pagination.currentPage = page
109 this.setNewRouteParams()
113 this.loadedPages = {}
114 this.loadMoreVideos(this.pagination.currentPage)
117 loadMoreVideos (page: number, loadOnTop = false) {
118 this.adjustVideoPageHeight()
120 const currentY = window.scrollY
122 if (this.loadedPages[page] !== undefined) return
123 if (this.loadingPage[page] === true) return
125 this.loadingPage[page] = true
126 const observable = this.getVideosObservable(page)
128 observable.subscribe(
129 ({ videos, totalVideos }) => {
130 this.loadingPage[page] = false
132 if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
134 // Paging is too high, return to the first one
135 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
136 this.pagination.currentPage = 1
137 this.setNewRouteParams()
138 return this.reloadVideos()
141 this.loadedPages[page] = videos
142 this.buildVideoPages()
143 this.pagination.totalItems = totalVideos
145 // Initialize infinite scroller now we loaded the first page
146 if (Object.keys(this.loadedPages).length === 1) {
147 // Wait elements creation
149 this.infiniteScroller.initialize()
151 // At our first load, we did not load the first page
152 // Load the previous page so the user can move on the top (and browser previous pages)
153 if (this.pagination.currentPage > 1) this.loadMoreVideos(this.pagination.currentPage - 1, true)
157 // Insert elements on the top but keep the scroll in the previous position
158 if (loadOnTop) setTimeout(() => { window.scrollTo(0, currentY + this.pageHeight) }, 0)
161 this.loadingPage[page] = false
162 this.notifier.error(error.message)
167 toggleModerationDisplay () {
168 throw new Error('toggleModerationDisplay is not implemented')
171 protected hasMoreVideos () {
173 if (this.pagination.totalItems === 0) return false
176 if (!this.pagination.totalItems) return true
178 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
179 return maxPage > this.maxPageLoaded()
182 protected previousPage () {
183 const min = this.minPageLoaded()
186 this.loadMoreVideos(min - 1, true)
190 protected nextPage () {
191 this.loadMoreVideos(this.maxPageLoaded() + 1)
194 protected buildRouteParams () {
195 // There is always a sort and a current page
198 page: this.pagination.currentPage
201 return Object.assign(params, this.otherRouteParams)
204 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
205 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
206 this.categoryOneOf = routeParams['categoryOneOf']
207 if (routeParams['page'] !== undefined) {
208 this.pagination.currentPage = parseInt(routeParams['page'], 10)
210 this.pagination.currentPage = 1
214 protected setNewRouteParams () {
215 const paramsObject = this.buildRouteParams()
217 const queryParams = Object.keys(paramsObject)
218 .map(p => p + '=' + paramsObject[p])
220 this.location.replaceState(this.currentRoute, queryParams)
223 protected buildVideoPages () {
224 this.videoPages = Object.values(this.loadedPages)
227 protected adjustVideoPageHeight () {
228 const numberOfPagesLoaded = Object.keys(this.loadedPages).length
229 if (!numberOfPagesLoaded) return
231 this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
234 protected buildVideoHeight () {
235 // Same ratios than base width/height
236 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
239 private minPageLoaded () {
240 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
243 private maxPageLoaded () {
244 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
247 private calcPageSizes () {
248 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
249 this.pagination.itemsPerPage = 5
251 // Video takes all the width
253 this.videoHeight = this.buildVideoHeight()
254 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
256 this.videoWidth = this.baseVideoWidth
257 this.videoHeight = this.baseVideoHeight
259 const videosWidth = this.videosElement.nativeElement.offsetWidth
260 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
261 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
264 // Rebuild pages because maybe we modified the number of items per page
265 const videos = [].concat(...this.videoPages)
266 this.loadedPages = {}
269 // Don't include the last page if it not complete
270 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
271 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
275 // Re fetch the last page
276 if (videos.length !== 0) {
277 this.loadMoreVideos(i)
279 this.buildVideoPages()
282 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)