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