9df4cfc22671f038772d6305a05f7985037b271c
[oweals/peertube.git] / client / src / app / shared / video / abstract-video-list.ts
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
16 export abstract class AbstractVideoList implements OnInit, OnDestroy {
17   private static LINES_PER_PAGE = 4
18
19   @ViewChild('videosElement') videosElement: ElementRef
20   @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
21
22   pagination: ComponentPagination = {
23     currentPage: 1,
24     itemsPerPage: 10,
25     totalItems: null
26   }
27   sort: VideoSortField = '-publishedAt'
28   categoryOneOf?: number
29   defaultSort: VideoSortField = '-publishedAt'
30   syndicationItems = []
31
32   loadOnInit = true
33   marginContent = true
34   pageHeight: number
35   videoWidth: number
36   videoHeight: number
37   videoPages: Video[][] = []
38   ownerDisplayType: OwnerDisplayType = 'account'
39
40   protected baseVideoWidth = 215
41   protected baseVideoHeight = 205
42
43   protected abstract notificationsService: NotificationsService
44   protected abstract authService: AuthService
45   protected abstract router: Router
46   protected abstract route: ActivatedRoute
47   protected abstract screenService: ScreenService
48   protected abstract i18n: I18n
49   protected abstract location: Location
50   protected abstract currentRoute: string
51   abstract titlePage: string
52
53   protected loadedPages: { [ id: number ]: Video[] } = {}
54   protected loadingPage: { [ id: number ]: boolean } = {}
55   protected otherRouteParams = {}
56
57   private resizeSubscription: Subscription
58   private firstLoadedPage: number
59
60   abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
61   abstract generateSyndicationList ()
62
63   get user () {
64     return this.authService.getUser()
65   }
66
67   ngOnInit () {
68     // Subscribe to route changes
69     const routeParams = this.route.snapshot.queryParams
70     this.loadRouteParams(routeParams)
71
72     this.resizeSubscription = fromEvent(window, 'resize')
73       .pipe(debounceTime(500))
74       .subscribe(() => this.calcPageSizes())
75
76     this.calcPageSizes()
77     if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
78   }
79
80   ngOnDestroy () {
81     if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
82   }
83
84   onNearOfTop () {
85     this.previousPage()
86   }
87
88   onNearOfBottom () {
89     if (this.hasMoreVideos()) {
90       this.nextPage()
91     }
92   }
93
94   onPageChanged (page: number) {
95     this.pagination.currentPage = page
96     this.setNewRouteParams()
97   }
98
99   reloadVideos () {
100     this.loadedPages = {}
101     this.loadMoreVideos(this.pagination.currentPage)
102   }
103
104   loadMoreVideos (page: number, loadOnTop = false) {
105     this.adjustVideoPageHeight()
106
107     const currentY = window.scrollY
108
109     if (this.loadedPages[page] !== undefined) return
110     if (this.loadingPage[page] === true) return
111
112     this.loadingPage[page] = true
113     const observable = this.getVideosObservable(page)
114
115     observable.subscribe(
116       ({ videos, totalVideos }) => {
117         this.loadingPage[page] = false
118
119         if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
120
121         // Paging is too high, return to the first one
122         if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
123           this.pagination.currentPage = 1
124           this.setNewRouteParams()
125           return this.reloadVideos()
126         }
127
128         this.loadedPages[page] = videos
129         this.buildVideoPages()
130         this.pagination.totalItems = totalVideos
131
132         // Initialize infinite scroller now we loaded the first page
133         if (Object.keys(this.loadedPages).length === 1) {
134           // Wait elements creation
135           setTimeout(() => {
136             this.infiniteScroller.initialize()
137
138             // At our first load, we did not load the first page
139             // Load the previous page so the user can move on the top (and browser previous pages)
140             if (this.pagination.currentPage > 1) this.loadMoreVideos(this.pagination.currentPage - 1, true)
141           }, 500)
142         }
143
144         // Insert elements on the top but keep the scroll in the previous position
145         if (loadOnTop) setTimeout(() => { window.scrollTo(0, currentY + this.pageHeight) }, 0)
146       },
147       error => {
148         this.loadingPage[page] = false
149         this.notificationsService.error(this.i18n('Error'), error.message)
150       }
151     )
152   }
153
154   protected hasMoreVideos () {
155     // No results
156     if (this.pagination.totalItems === 0) return false
157
158     // Not loaded yet
159     if (!this.pagination.totalItems) return true
160
161     const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
162     return maxPage > this.maxPageLoaded()
163   }
164
165   protected previousPage () {
166     const min = this.minPageLoaded()
167
168     if (min > 1) {
169       this.loadMoreVideos(min - 1)
170     }
171   }
172
173   protected nextPage () {
174     this.loadMoreVideos(this.maxPageLoaded() + 1)
175   }
176
177   protected buildRouteParams () {
178     // There is always a sort and a current page
179     const params = {
180       sort: this.sort,
181       page: this.pagination.currentPage
182     }
183
184     return Object.assign(params, this.otherRouteParams)
185   }
186
187   protected loadRouteParams (routeParams: { [ key: string ]: any }) {
188     this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
189     this.categoryOneOf = routeParams['categoryOneOf']
190     if (routeParams['page'] !== undefined) {
191       this.pagination.currentPage = parseInt(routeParams['page'], 10)
192     } else {
193       this.pagination.currentPage = 1
194     }
195   }
196
197   protected setNewRouteParams () {
198     const paramsObject = this.buildRouteParams()
199
200     const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
201     this.location.replaceState(this.currentRoute, queryParams)
202   }
203
204   protected buildVideoPages () {
205     this.videoPages = Object.values(this.loadedPages)
206   }
207
208   protected adjustVideoPageHeight () {
209     const numberOfPagesLoaded = Object.keys(this.loadedPages).length
210     if (!numberOfPagesLoaded) return
211
212     this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
213   }
214
215   protected buildVideoHeight () {
216     // Same ratios than base width/height
217     return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
218   }
219
220   private minPageLoaded () {
221     return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
222   }
223
224   private maxPageLoaded () {
225     return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
226   }
227
228   private calcPageSizes () {
229     if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
230       this.pagination.itemsPerPage = 5
231
232       // Video takes all the width
233       this.videoWidth = -1
234       this.videoHeight = this.buildVideoHeight()
235       this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
236     } else {
237       this.videoWidth = this.baseVideoWidth
238       this.videoHeight = this.baseVideoHeight
239
240       const videosWidth = this.videosElement.nativeElement.offsetWidth
241       this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
242       this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
243     }
244
245     // Rebuild pages because maybe we modified the number of items per page
246     const videos = [].concat(...this.videoPages)
247     this.loadedPages = {}
248
249     let i = 1
250     // Don't include the last page if it not complete
251     while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
252       this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
253       i++
254     }
255
256     // Re fetch the last page
257     if (videos.length !== 0) {
258       this.loadMoreVideos(i)
259     } else {
260       this.buildVideoPages()
261     }
262
263     console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)
264   }
265 }