]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/video/abstract-video-list.ts
Refractor notification service
[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
43 protected baseVideoWidth = 215
44 protected baseVideoHeight = 205
45
46 protected abstract notifier: Notifier
47 protected abstract authService: AuthService
48 protected abstract router: Router
49 protected abstract route: ActivatedRoute
50 protected abstract screenService: ScreenService
51 protected abstract i18n: I18n
52 protected abstract location: Location
53 protected abstract currentRoute: string
54 abstract titlePage: string
55
56 protected loadedPages: { [ id: number ]: Video[] } = {}
57 protected loadingPage: { [ id: number ]: boolean } = {}
58 protected otherRouteParams = {}
59
60 private resizeSubscription: Subscription
61
62 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
63 abstract generateSyndicationList (): void
64
65 get user () {
66 return this.authService.getUser()
67 }
68
69 ngOnInit () {
70 // Subscribe to route changes
71 const routeParams = this.route.snapshot.queryParams
72 this.loadRouteParams(routeParams)
73
74 this.resizeSubscription = fromEvent(window, 'resize')
75 .pipe(debounceTime(500))
76 .subscribe(() => this.calcPageSizes())
77
78 this.calcPageSizes()
79 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
80 }
81
82 ngOnDestroy () {
83 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
84 }
85
86 pageByVideoId (index: number, page: Video[]) {
87 // Video are unique in all pages
88 return page.length !== 0 ? page[0].id : 0
89 }
90
91 videoById (index: number, video: Video) {
92 return video.id
93 }
94
95 onNearOfTop () {
96 this.previousPage()
97 }
98
99 onNearOfBottom () {
100 if (this.hasMoreVideos()) {
101 this.nextPage()
102 }
103 }
104
105 onPageChanged (page: number) {
106 this.pagination.currentPage = page
107 this.setNewRouteParams()
108 }
109
110 reloadVideos () {
111 this.loadedPages = {}
112 this.loadMoreVideos(this.pagination.currentPage)
113 }
114
115 loadMoreVideos (page: number, loadOnTop = false) {
116 this.adjustVideoPageHeight()
117
118 const currentY = window.scrollY
119
120 if (this.loadedPages[page] !== undefined) return
121 if (this.loadingPage[page] === true) return
122
123 this.loadingPage[page] = true
124 const observable = this.getVideosObservable(page)
125
126 observable.subscribe(
127 ({ videos, totalVideos }) => {
128 this.loadingPage[page] = false
129
130 if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
131
132 // Paging is too high, return to the first one
133 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
134 this.pagination.currentPage = 1
135 this.setNewRouteParams()
136 return this.reloadVideos()
137 }
138
139 this.loadedPages[page] = videos
140 this.buildVideoPages()
141 this.pagination.totalItems = totalVideos
142
143 // Initialize infinite scroller now we loaded the first page
144 if (Object.keys(this.loadedPages).length === 1) {
145 // Wait elements creation
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)
153 }
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)
157 },
158 error => {
159 this.loadingPage[page] = false
160 this.notifier.error(error.message)
161 }
162 )
163 }
164
165 toggleModerationDisplay () {
166 throw new Error('toggleModerationDisplay is not implemented')
167 }
168
169 protected hasMoreVideos () {
170 // No results
171 if (this.pagination.totalItems === 0) return false
172
173 // Not loaded yet
174 if (!this.pagination.totalItems) return true
175
176 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
177 return maxPage > this.maxPageLoaded()
178 }
179
180 protected previousPage () {
181 const min = this.minPageLoaded()
182
183 if (min > 1) {
184 this.loadMoreVideos(min - 1, true)
185 }
186 }
187
188 protected nextPage () {
189 this.loadMoreVideos(this.maxPageLoaded() + 1)
190 }
191
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
199 return Object.assign(params, this.otherRouteParams)
200 }
201
202 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
203 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
204 this.categoryOneOf = routeParams['categoryOneOf']
205 if (routeParams['page'] !== undefined) {
206 this.pagination.currentPage = parseInt(routeParams['page'], 10)
207 } else {
208 this.pagination.currentPage = 1
209 }
210 }
211
212 protected setNewRouteParams () {
213 const paramsObject = this.buildRouteParams()
214
215 const queryParams = Object.keys(paramsObject)
216 .map(p => p + '=' + paramsObject[p])
217 .join('&')
218 this.location.replaceState(this.currentRoute, queryParams)
219 }
220
221 protected buildVideoPages () {
222 this.videoPages = Object.values(this.loadedPages)
223 }
224
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
232 protected buildVideoHeight () {
233 // Same ratios than base width/height
234 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
235 }
236
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 }
244
245 private calcPageSizes () {
246 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
247 this.pagination.itemsPerPage = 5
248
249 // Video takes all the width
250 this.videoWidth = -1
251 this.videoHeight = this.buildVideoHeight()
252 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
253 } else {
254 this.videoWidth = this.baseVideoWidth
255 this.videoHeight = this.baseVideoHeight
256
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
263 const videos = [].concat(...this.videoPages)
264 this.loadedPages = {}
265
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++
271 }
272
273 // Re fetch the last page
274 if (videos.length !== 0) {
275 this.loadMoreVideos(i)
276 } else {
277 this.buildVideoPages()
278 }
279
280 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)
281 }
282 }