d74384293c0219112600a24e844cecc42fb829ef
[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 { 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'
16
17 export abstract class AbstractVideoList implements OnInit, OnDestroy {
18   private static LINES_PER_PAGE = 4
19
20   @ViewChild('videosElement') videosElement: ElementRef
21   @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
22
23   pagination: ComponentPagination = {
24     currentPage: 1,
25     itemsPerPage: 10,
26     totalItems: null
27   }
28   sort: VideoSortField = '-publishedAt'
29   categoryOneOf?: number
30   defaultSort: VideoSortField = '-publishedAt'
31   syndicationItems: Syndication[] = []
32
33   loadOnInit = true
34   marginContent = true
35   pageHeight: number
36   videoWidth: number
37   videoHeight: number
38   videoPages: Video[][] = []
39   ownerDisplayType: OwnerDisplayType = 'account'
40   firstLoadedPage: number
41   displayModerationBlock = false
42   trendingDays: number
43   titleTooltip: string
44
45   protected baseVideoWidth = 215
46   protected baseVideoHeight = 205
47
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
57
58   protected loadedPages: { [ id: number ]: Video[] } = {}
59   protected loadingPage: { [ id: number ]: boolean } = {}
60   protected otherRouteParams = {}
61
62   private resizeSubscription: Subscription
63
64   abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
65   abstract generateSyndicationList (): void
66
67   get user () {
68     return this.authService.getUser()
69   }
70
71   ngOnInit () {
72     // Subscribe to route changes
73     const routeParams = this.route.snapshot.queryParams
74     this.loadRouteParams(routeParams)
75
76     this.resizeSubscription = fromEvent(window, 'resize')
77       .pipe(debounceTime(500))
78       .subscribe(() => this.calcPageSizes())
79
80     this.calcPageSizes()
81     if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
82   }
83
84   ngOnDestroy () {
85     if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
86   }
87
88   pageByVideoId (index: number, page: Video[]) {
89     // Video are unique in all pages
90     return page.length !== 0 ? page[0].id : 0
91   }
92
93   videoById (index: number, video: Video) {
94     return video.id
95   }
96
97   onNearOfTop () {
98     this.previousPage()
99   }
100
101   onNearOfBottom () {
102     if (this.hasMoreVideos()) {
103       this.nextPage()
104     }
105   }
106
107   onPageChanged (page: number) {
108     this.pagination.currentPage = page
109     this.setNewRouteParams()
110   }
111
112   reloadVideos () {
113     this.loadedPages = {}
114     this.loadMoreVideos(this.pagination.currentPage)
115   }
116
117   loadMoreVideos (page: number, loadOnTop = false) {
118     this.adjustVideoPageHeight()
119
120     const currentY = window.scrollY
121
122     if (this.loadedPages[page] !== undefined) return
123     if (this.loadingPage[page] === true) return
124
125     this.loadingPage[page] = true
126     const observable = this.getVideosObservable(page)
127
128     observable.subscribe(
129       ({ videos, totalVideos }) => {
130         this.loadingPage[page] = false
131
132         if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
133
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()
139         }
140
141         this.loadedPages[page] = videos
142         this.buildVideoPages()
143         this.pagination.totalItems = totalVideos
144
145         // Initialize infinite scroller now we loaded the first page
146         if (Object.keys(this.loadedPages).length === 1) {
147           // Wait elements creation
148           setTimeout(() => {
149             this.infiniteScroller.initialize()
150
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)
154           }, 500)
155         }
156
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)
159       },
160       error => {
161         this.loadingPage[page] = false
162         this.notifier.error(error.message)
163       }
164     )
165   }
166
167   toggleModerationDisplay () {
168     throw new Error('toggleModerationDisplay is not implemented')
169   }
170
171   protected hasMoreVideos () {
172     // No results
173     if (this.pagination.totalItems === 0) return false
174
175     // Not loaded yet
176     if (!this.pagination.totalItems) return true
177
178     const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
179     return maxPage > this.maxPageLoaded()
180   }
181
182   protected previousPage () {
183     const min = this.minPageLoaded()
184
185     if (min > 1) {
186       this.loadMoreVideos(min - 1, true)
187     }
188   }
189
190   protected nextPage () {
191     this.loadMoreVideos(this.maxPageLoaded() + 1)
192   }
193
194   protected buildRouteParams () {
195     // There is always a sort and a current page
196     const params = {
197       sort: this.sort,
198       page: this.pagination.currentPage
199     }
200
201     return Object.assign(params, this.otherRouteParams)
202   }
203
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)
209     } else {
210       this.pagination.currentPage = 1
211     }
212   }
213
214   protected setNewRouteParams () {
215     const paramsObject = this.buildRouteParams()
216
217     const queryParams = Object.keys(paramsObject)
218                               .map(p => p + '=' + paramsObject[p])
219                               .join('&')
220     this.location.replaceState(this.currentRoute, queryParams)
221   }
222
223   protected buildVideoPages () {
224     this.videoPages = Object.values(this.loadedPages)
225   }
226
227   protected adjustVideoPageHeight () {
228     const numberOfPagesLoaded = Object.keys(this.loadedPages).length
229     if (!numberOfPagesLoaded) return
230
231     this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
232   }
233
234   protected buildVideoHeight () {
235     // Same ratios than base width/height
236     return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
237   }
238
239   private minPageLoaded () {
240     return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
241   }
242
243   private maxPageLoaded () {
244     return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
245   }
246
247   private calcPageSizes () {
248     if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
249       this.pagination.itemsPerPage = 5
250
251       // Video takes all the width
252       this.videoWidth = -1
253       this.videoHeight = this.buildVideoHeight()
254       this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
255     } else {
256       this.videoWidth = this.baseVideoWidth
257       this.videoHeight = this.baseVideoHeight
258
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
262     }
263
264     // Rebuild pages because maybe we modified the number of items per page
265     const videos = [].concat(...this.videoPages)
266     this.loadedPages = {}
267
268     let i = 1
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)
272       i++
273     }
274
275     // Re fetch the last page
276     if (videos.length !== 0) {
277       this.loadMoreVideos(i)
278     } else {
279       this.buildVideoPages()
280     }
281
282     console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)
283   }
284 }