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