1f43f974c372f7446557755fed44343847097f70
[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   firstLoadedPage: number
40   displayModerationBlock = false
41
42   protected baseVideoWidth = 215
43   protected baseVideoHeight = 205
44
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
54
55   protected loadedPages: { [ id: number ]: Video[] } = {}
56   protected loadingPage: { [ id: number ]: boolean } = {}
57   protected otherRouteParams = {}
58
59   private resizeSubscription: Subscription
60
61   abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
62   abstract generateSyndicationList ()
63
64   get user () {
65     return this.authService.getUser()
66   }
67
68   ngOnInit () {
69     // Subscribe to route changes
70     const routeParams = this.route.snapshot.queryParams
71     this.loadRouteParams(routeParams)
72
73     this.resizeSubscription = fromEvent(window, 'resize')
74       .pipe(debounceTime(500))
75       .subscribe(() => this.calcPageSizes())
76
77     this.calcPageSizes()
78     if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
79   }
80
81   ngOnDestroy () {
82     if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
83   }
84
85   pageByVideoId (index: number, page: Video[]) {
86     // Video are unique in all pages
87     return page.length !== 0 ? page[0].id : 0
88   }
89
90   videoById (index: number, video: Video) {
91     return video.id
92   }
93
94   onNearOfTop () {
95     this.previousPage()
96   }
97
98   onNearOfBottom () {
99     if (this.hasMoreVideos()) {
100       this.nextPage()
101     }
102   }
103
104   onPageChanged (page: number) {
105     this.pagination.currentPage = page
106     this.setNewRouteParams()
107   }
108
109   reloadVideos () {
110     this.loadedPages = {}
111     this.loadMoreVideos(this.pagination.currentPage)
112   }
113
114   loadMoreVideos (page: number, loadOnTop = false) {
115     this.adjustVideoPageHeight()
116
117     const currentY = window.scrollY
118
119     if (this.loadedPages[page] !== undefined) return
120     if (this.loadingPage[page] === true) return
121
122     this.loadingPage[page] = true
123     const observable = this.getVideosObservable(page)
124
125     observable.subscribe(
126       ({ videos, totalVideos }) => {
127         this.loadingPage[page] = false
128
129         if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
130
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()
136         }
137
138         this.loadedPages[page] = videos
139         this.buildVideoPages()
140         this.pagination.totalItems = totalVideos
141
142         // Initialize infinite scroller now we loaded the first page
143         if (Object.keys(this.loadedPages).length === 1) {
144           // Wait elements creation
145           setTimeout(() => {
146             this.infiniteScroller.initialize()
147
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)
151           }, 500)
152         }
153
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)
156       },
157       error => {
158         this.loadingPage[page] = false
159         this.notificationsService.error(this.i18n('Error'), error.message)
160       }
161     )
162   }
163
164   toggleModerationDisplay () {
165     throw new Error('toggleModerationDisplay is not implemented')
166   }
167
168   protected hasMoreVideos () {
169     // No results
170     if (this.pagination.totalItems === 0) return false
171
172     // Not loaded yet
173     if (!this.pagination.totalItems) return true
174
175     const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
176     return maxPage > this.maxPageLoaded()
177   }
178
179   protected previousPage () {
180     const min = this.minPageLoaded()
181
182     if (min > 1) {
183       this.loadMoreVideos(min - 1, true)
184     }
185   }
186
187   protected nextPage () {
188     this.loadMoreVideos(this.maxPageLoaded() + 1)
189   }
190
191   protected buildRouteParams () {
192     // There is always a sort and a current page
193     const params = {
194       sort: this.sort,
195       page: this.pagination.currentPage
196     }
197
198     return Object.assign(params, this.otherRouteParams)
199   }
200
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)
206     } else {
207       this.pagination.currentPage = 1
208     }
209   }
210
211   protected setNewRouteParams () {
212     const paramsObject = this.buildRouteParams()
213
214     const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
215     this.location.replaceState(this.currentRoute, queryParams)
216   }
217
218   protected buildVideoPages () {
219     this.videoPages = Object.values(this.loadedPages)
220   }
221
222   protected adjustVideoPageHeight () {
223     const numberOfPagesLoaded = Object.keys(this.loadedPages).length
224     if (!numberOfPagesLoaded) return
225
226     this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
227   }
228
229   protected buildVideoHeight () {
230     // Same ratios than base width/height
231     return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
232   }
233
234   private minPageLoaded () {
235     return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
236   }
237
238   private maxPageLoaded () {
239     return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
240   }
241
242   private calcPageSizes () {
243     if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
244       this.pagination.itemsPerPage = 5
245
246       // Video takes all the width
247       this.videoWidth = -1
248       this.videoHeight = this.buildVideoHeight()
249       this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
250     } else {
251       this.videoWidth = this.baseVideoWidth
252       this.videoHeight = this.baseVideoHeight
253
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
257     }
258
259     // Rebuild pages because maybe we modified the number of items per page
260     const videos = [].concat(...this.videoPages)
261     this.loadedPages = {}
262
263     let i = 1
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)
267       i++
268     }
269
270     // Re fetch the last page
271     if (videos.length !== 0) {
272       this.loadMoreVideos(i)
273     } else {
274       this.buildVideoPages()
275     }
276
277     console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)
278   }
279 }