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