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