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'
16 export abstract class AbstractVideoList implements OnInit, OnDestroy {
17 private static LINES_PER_PAGE = 4
19 @ViewChild('videosElement') videosElement: ElementRef
20 @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
22 pagination: ComponentPagination = {
27 sort: VideoSortField = '-publishedAt'
28 categoryOneOf?: number
29 defaultSort: VideoSortField = '-publishedAt'
37 videoPages: Video[][] = []
38 ownerDisplayType: OwnerDisplayType = 'account'
39 firstLoadedPage: number
40 displayModerationBlock = false
42 protected baseVideoWidth = 215
43 protected baseVideoHeight = 205
45 protected abstract notificationsService: NotificationsService
46 protected abstract authService: AuthService
47 protected abstract router: Router
48 protected abstract route: ActivatedRoute
49 protected abstract screenService: ScreenService
50 protected abstract i18n: I18n
51 protected abstract location: Location
52 protected abstract currentRoute: string
53 abstract titlePage: string
55 protected loadedPages: { [ id: number ]: Video[] } = {}
56 protected loadingPage: { [ id: number ]: boolean } = {}
57 protected otherRouteParams = {}
59 private resizeSubscription: Subscription
61 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
62 abstract generateSyndicationList ()
65 return this.authService.getUser()
69 // Subscribe to route changes
70 const routeParams = this.route.snapshot.queryParams
71 this.loadRouteParams(routeParams)
73 this.resizeSubscription = fromEvent(window, 'resize')
74 .pipe(debounceTime(500))
75 .subscribe(() => this.calcPageSizes())
78 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
82 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
85 pageByVideoId (index: number, page: Video[]) {
86 // Video are unique in all pages
87 return page.length !== 0 ? page[0].id : 0
90 videoById (index: number, video: Video) {
99 if (this.hasMoreVideos()) {
104 onPageChanged (page: number) {
105 this.pagination.currentPage = page
106 this.setNewRouteParams()
110 this.loadedPages = {}
111 this.loadMoreVideos(this.pagination.currentPage)
114 loadMoreVideos (page: number, loadOnTop = false) {
115 this.adjustVideoPageHeight()
117 const currentY = window.scrollY
119 if (this.loadedPages[page] !== undefined) return
120 if (this.loadingPage[page] === true) return
122 this.loadingPage[page] = true
123 const observable = this.getVideosObservable(page)
125 observable.subscribe(
126 ({ videos, totalVideos }) => {
127 this.loadingPage[page] = false
129 if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
131 // Paging is too high, return to the first one
132 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
133 this.pagination.currentPage = 1
134 this.setNewRouteParams()
135 return this.reloadVideos()
138 this.loadedPages[page] = videos
139 this.buildVideoPages()
140 this.pagination.totalItems = totalVideos
142 // Initialize infinite scroller now we loaded the first page
143 if (Object.keys(this.loadedPages).length === 1) {
144 // Wait elements creation
146 this.infiniteScroller.initialize()
148 // At our first load, we did not load the first page
149 // Load the previous page so the user can move on the top (and browser previous pages)
150 if (this.pagination.currentPage > 1) this.loadMoreVideos(this.pagination.currentPage - 1, true)
154 // Insert elements on the top but keep the scroll in the previous position
155 if (loadOnTop) setTimeout(() => { window.scrollTo(0, currentY + this.pageHeight) }, 0)
158 this.loadingPage[page] = false
159 this.notificationsService.error(this.i18n('Error'), error.message)
164 toggleModerationDisplay () {
165 throw new Error('toggleModerationDisplay is not implemented')
168 protected hasMoreVideos () {
170 if (this.pagination.totalItems === 0) return false
173 if (!this.pagination.totalItems) return true
175 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
176 return maxPage > this.maxPageLoaded()
179 protected previousPage () {
180 const min = this.minPageLoaded()
183 this.loadMoreVideos(min - 1, true)
187 protected nextPage () {
188 this.loadMoreVideos(this.maxPageLoaded() + 1)
191 protected buildRouteParams () {
192 // There is always a sort and a current page
195 page: this.pagination.currentPage
198 return Object.assign(params, this.otherRouteParams)
201 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
202 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
203 this.categoryOneOf = routeParams['categoryOneOf']
204 if (routeParams['page'] !== undefined) {
205 this.pagination.currentPage = parseInt(routeParams['page'], 10)
207 this.pagination.currentPage = 1
211 protected setNewRouteParams () {
212 const paramsObject = this.buildRouteParams()
214 const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
215 this.location.replaceState(this.currentRoute, queryParams)
218 protected buildVideoPages () {
219 this.videoPages = Object.values(this.loadedPages)
222 protected adjustVideoPageHeight () {
223 const numberOfPagesLoaded = Object.keys(this.loadedPages).length
224 if (!numberOfPagesLoaded) return
226 this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
229 protected buildVideoHeight () {
230 // Same ratios than base width/height
231 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
234 private minPageLoaded () {
235 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
238 private maxPageLoaded () {
239 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
242 private calcPageSizes () {
243 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
244 this.pagination.itemsPerPage = 5
246 // Video takes all the width
248 this.videoHeight = this.buildVideoHeight()
249 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
251 this.videoWidth = this.baseVideoWidth
252 this.videoHeight = this.baseVideoHeight
254 const videosWidth = this.videosElement.nativeElement.offsetWidth
255 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
256 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
259 // Rebuild pages because maybe we modified the number of items per page
260 const videos = [].concat(...this.videoPages)
261 this.loadedPages = {}
264 // Don't include the last page if it not complete
265 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
266 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
270 // Re fetch the last page
271 if (videos.length !== 0) {
272 this.loadMoreVideos(i)
274 this.buildVideoPages()
277 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)