]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/video/abstract-video-list.ts
Fix AP tests
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / video / abstract-video-list.ts
CommitLineData
db400f44 1import { debounceTime } from 'rxjs/operators'
9af61e84 2import { ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'
fd45e8f4 3import { ActivatedRoute, Router } from '@angular/router'
2a2c19df 4import { Location } from '@angular/common'
0cd4344f 5import { InfiniteScrollerDirective } from '@app/shared/video/infinite-scroller.directive'
fd45e8f4 6import { NotificationsService } from 'angular2-notifications'
db400f44 7import { fromEvent, Observable, Subscription } from 'rxjs'
b2731bff 8import { AuthService } from '../../core/auth'
4635f59d 9import { ComponentPagination } from '../rest/component-pagination.model'
7b87d2d5 10import { VideoSortField } from './sort-field.type'
202f6b6c 11import { Video } from './video.model'
b1d40cff 12import { I18n } from '@ngx-translate/i18n-polyfill'
bbe0f064 13import { ScreenService } from '@app/shared/misc/screen.service'
22a16e36 14import { OwnerDisplayType } from '@app/shared/video/video-miniature.component'
c199c427 15import { Syndication } from '@app/shared/video/syndication.model'
fd45e8f4 16
9af61e84 17export abstract class AbstractVideoList implements OnInit, OnDestroy {
75236b98 18 private static LINES_PER_PAGE = 4
0cd4344f 19
1ff8d7d6 20 @ViewChild('videosElement') videosElement: ElementRef
0cd4344f
C
21 @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
22
4635f59d 23 pagination: ComponentPagination = {
fd45e8f4 24 currentPage: 1,
0cd4344f 25 itemsPerPage: 10,
fd45e8f4
C
26 totalItems: null
27 }
136cce4d 28 sort: VideoSortField = '-publishedAt'
d59cba29 29 categoryOneOf?: number
136cce4d 30 defaultSort: VideoSortField = '-publishedAt'
c199c427 31 syndicationItems: Syndication[] = []
244e76a5 32
f3aaa9a9 33 loadOnInit = true
0626e7af 34 marginContent = true
0cd4344f 35 pageHeight: number
caae7a06
C
36 videoWidth: number
37 videoHeight: number
38 videoPages: Video[][] = []
22a16e36 39 ownerDisplayType: OwnerDisplayType = 'account'
d5931e62 40 firstLoadedPage: number
017c3dca 41 displayModerationBlock = false
fd45e8f4 42
9af61e84 43 protected baseVideoWidth = 215
a8ecc6f6 44 protected baseVideoHeight = 205
9af61e84 45
b2731bff
C
46 protected abstract notificationsService: NotificationsService
47 protected abstract authService: AuthService
48 protected abstract router: Router
49 protected abstract route: ActivatedRoute
bbe0f064 50 protected abstract screenService: ScreenService
b1d40cff 51 protected abstract i18n: I18n
2a2c19df 52 protected abstract location: Location
2bbb3412 53 protected abstract currentRoute: string
9bf9d2a5 54 abstract titlePage: string
c88593f7 55
0cd4344f 56 protected loadedPages: { [ id: number ]: Video[] } = {}
5f73f5da 57 protected loadingPage: { [ id: number ]: boolean } = {}
0cd4344f 58 protected otherRouteParams = {}
2bbb3412 59
9af61e84
C
60 private resizeSubscription: Subscription
61
0cd4344f 62 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
c199c427 63 abstract generateSyndicationList (): void
fd45e8f4 64
b2731bff
C
65 get user () {
66 return this.authService.getUser()
67 }
68
fd45e8f4
C
69 ngOnInit () {
70 // Subscribe to route changes
5b5e333f 71 const routeParams = this.route.snapshot.queryParams
2bbb3412 72 this.loadRouteParams(routeParams)
a2b817d3 73
9af61e84 74 this.resizeSubscription = fromEvent(window, 'resize')
db400f44 75 .pipe(debounceTime(500))
6194c1b4 76 .subscribe(() => this.calcPageSizes())
3290f37c 77
6194c1b4 78 this.calcPageSizes()
0cd4344f 79 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
fd45e8f4
C
80 }
81
9af61e84
C
82 ngOnDestroy () {
83 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
84 }
85
89724816
C
86 pageByVideoId (index: number, page: Video[]) {
87 // Video are unique in all pages
35d50b7d 88 return page.length !== 0 ? page[0].id : 0
89724816
C
89 }
90
91 videoById (index: number, video: Video) {
92 return video.id
93 }
94
2bbb3412 95 onNearOfTop () {
0cd4344f 96 this.previousPage()
2bbb3412
C
97 }
98
99 onNearOfBottom () {
100 if (this.hasMoreVideos()) {
101 this.nextPage()
102 }
103 }
104
0cd4344f
C
105 onPageChanged (page: number) {
106 this.pagination.currentPage = page
107 this.setNewRouteParams()
108 }
109
f3aaa9a9 110 reloadVideos () {
f3aaa9a9 111 this.loadedPages = {}
0cd4344f 112 this.loadMoreVideos(this.pagination.currentPage)
f3aaa9a9
C
113 }
114
a8ecc6f6
C
115 loadMoreVideos (page: number, loadOnTop = false) {
116 this.adjustVideoPageHeight()
117
118 const currentY = window.scrollY
119
0cd4344f 120 if (this.loadedPages[page] !== undefined) return
5f73f5da 121 if (this.loadingPage[page] === true) return
fd45e8f4 122
5f73f5da 123 this.loadingPage[page] = true
0cd4344f 124 const observable = this.getVideosObservable(page)
fd45e8f4
C
125
126 observable.subscribe(
127 ({ videos, totalVideos }) => {
5f73f5da
C
128 this.loadingPage[page] = false
129
a8ecc6f6
C
130 if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
131
a2b817d3 132 // Paging is too high, return to the first one
f595d394 133 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
a2b817d3
C
134 this.pagination.currentPage = 1
135 this.setNewRouteParams()
136 return this.reloadVideos()
137 }
138
0cd4344f
C
139 this.loadedPages[page] = videos
140 this.buildVideoPages()
fd45e8f4 141 this.pagination.totalItems = totalVideos
2bbb3412 142
0cd4344f
C
143 // Initialize infinite scroller now we loaded the first page
144 if (Object.keys(this.loadedPages).length === 1) {
145 // Wait elements creation
a8ecc6f6
C
146 setTimeout(() => {
147 this.infiniteScroller.initialize()
148
149 // At our first load, we did not load the first page
150 // Load the previous page so the user can move on the top (and browser previous pages)
151 if (this.pagination.currentPage > 1) this.loadMoreVideos(this.pagination.currentPage - 1, true)
152 }, 500)
2bbb3412 153 }
a8ecc6f6
C
154
155 // Insert elements on the top but keep the scroll in the previous position
156 if (loadOnTop) setTimeout(() => { window.scrollTo(0, currentY + this.pageHeight) }, 0)
fd45e8f4 157 },
5f73f5da
C
158 error => {
159 this.loadingPage[page] = false
b1d40cff 160 this.notificationsService.error(this.i18n('Error'), error.message)
5f73f5da 161 }
fd45e8f4
C
162 )
163 }
164
017c3dca
C
165 toggleModerationDisplay () {
166 throw new Error('toggleModerationDisplay is not implemented')
167 }
168
2bbb3412 169 protected hasMoreVideos () {
f595d394
C
170 // No results
171 if (this.pagination.totalItems === 0) return false
172
173 // Not loaded yet
2bbb3412
C
174 if (!this.pagination.totalItems) return true
175
202f6b6c 176 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
6a6d92b1 177 return maxPage > this.maxPageLoaded()
2bbb3412
C
178 }
179
180 protected previousPage () {
0cd4344f 181 const min = this.minPageLoaded()
2bbb3412 182
0cd4344f 183 if (min > 1) {
89724816 184 this.loadMoreVideos(min - 1, true)
0cd4344f 185 }
2bbb3412
C
186 }
187
188 protected nextPage () {
0cd4344f 189 this.loadMoreVideos(this.maxPageLoaded() + 1)
fd45e8f4
C
190 }
191
fd45e8f4
C
192 protected buildRouteParams () {
193 // There is always a sort and a current page
194 const params = {
195 sort: this.sort,
196 page: this.pagination.currentPage
197 }
198
0cd4344f 199 return Object.assign(params, this.otherRouteParams)
fd45e8f4
C
200 }
201
202 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
7b87d2d5 203 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
d59cba29 204 this.categoryOneOf = routeParams['categoryOneOf']
fd45e8f4
C
205 if (routeParams['page'] !== undefined) {
206 this.pagination.currentPage = parseInt(routeParams['page'], 10)
207 } else {
208 this.pagination.currentPage = 1
209 }
210 }
211
2bbb3412 212 protected setNewRouteParams () {
c199c427 213 const paramsObject = this.buildRouteParams()
2a2c19df 214
c199c427
C
215 const queryParams = Object.keys(paramsObject)
216 .map(p => p + '=' + paramsObject[p])
217 .join('&')
2a2c19df 218 this.location.replaceState(this.currentRoute, queryParams)
fd45e8f4 219 }
0cd4344f
C
220
221 protected buildVideoPages () {
222 this.videoPages = Object.values(this.loadedPages)
223 }
224
a8ecc6f6
C
225 protected adjustVideoPageHeight () {
226 const numberOfPagesLoaded = Object.keys(this.loadedPages).length
227 if (!numberOfPagesLoaded) return
228
229 this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
230 }
231
a86887a4
C
232 protected buildVideoHeight () {
233 // Same ratios than base width/height
234 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
235 }
236
0cd4344f
C
237 private minPageLoaded () {
238 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
239 }
240
241 private maxPageLoaded () {
242 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
243 }
6194c1b4
C
244
245 private calcPageSizes () {
bbe0f064 246 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
6194c1b4
C
247 this.pagination.itemsPerPage = 5
248
249 // Video takes all the width
250 this.videoWidth = -1
a86887a4 251 this.videoHeight = this.buildVideoHeight()
6194c1b4
C
252 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
253 } else {
9af61e84
C
254 this.videoWidth = this.baseVideoWidth
255 this.videoHeight = this.baseVideoHeight
caae7a06 256
6194c1b4
C
257 const videosWidth = this.videosElement.nativeElement.offsetWidth
258 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
259 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
260 }
261
262 // Rebuild pages because maybe we modified the number of items per page
caae7a06 263 const videos = [].concat(...this.videoPages)
6194c1b4
C
264 this.loadedPages = {}
265
caae7a06
C
266 let i = 1
267 // Don't include the last page if it not complete
268 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
269 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
270 i++
6194c1b4
C
271 }
272
9af61e84
C
273 // Re fetch the last page
274 if (videos.length !== 0) {
275 this.loadMoreVideos(i)
276 } else {
277 this.buildVideoPages()
278 }
6194c1b4 279
caae7a06 280 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)
6194c1b4 281 }
fd45e8f4 282}