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