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