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