06d4ed43d5cd705c782d277037e47171edbfaf70
[oweals/peertube.git] / client / src / app / shared / video / abstract-video-list.ts
1 import { debounceTime, first, tap } from 'rxjs/operators'
2 import { OnDestroy, OnInit } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { fromEvent, Observable, of, Subject, Subscription } from 'rxjs'
5 import { AuthService } from '../../core/auth'
6 import { ComponentPagination } from '../rest/component-pagination.model'
7 import { VideoSortField } from './sort-field.type'
8 import { Video } from './video.model'
9 import { ScreenService } from '@app/shared/misc/screen.service'
10 import { MiniatureDisplayOptions, OwnerDisplayType } from '@app/shared/video/video-miniature.component'
11 import { Syndication } from '@app/shared/video/syndication.model'
12 import { Notifier, ServerService } from '@app/core'
13 import { DisableForReuseHook } from '@app/core/routing/disable-for-reuse-hook'
14 import { I18n } from '@ngx-translate/i18n-polyfill'
15 import { isLastMonth, isLastWeek, isToday, isYesterday } from '@shared/core-utils/miscs/date'
16 import { ResultList, ServerConfig } from '@shared/models'
17
18 enum GroupDate {
19   UNKNOWN = 0,
20   TODAY = 1,
21   YESTERDAY = 2,
22   LAST_WEEK = 3,
23   LAST_MONTH = 4,
24   OLDER = 5
25 }
26
27 export abstract class AbstractVideoList implements OnInit, OnDestroy, DisableForReuseHook {
28   pagination: ComponentPagination = {
29     currentPage: 1,
30     itemsPerPage: 25,
31     totalItems: null
32   }
33   sort: VideoSortField = '-publishedAt'
34
35   categoryOneOf?: number
36   languageOneOf?: string[]
37   defaultSort: VideoSortField = '-publishedAt'
38
39   syndicationItems: Syndication[] = []
40
41   loadOnInit = true
42   useUserVideoLanguagePreferences = false
43   ownerDisplayType: OwnerDisplayType = 'account'
44   displayModerationBlock = false
45   titleTooltip: string
46   displayVideoActions = true
47   groupByDate = false
48
49   videos: Video[] = []
50   disabled = false
51
52   displayOptions: MiniatureDisplayOptions = {
53     date: true,
54     views: true,
55     by: true,
56     privacyLabel: true,
57     privacyText: false,
58     state: false,
59     blacklistInfo: false
60   }
61
62   actions: {
63     routerLink: string
64     iconName: string
65     label: string
66   }[] = []
67
68   onDataSubject = new Subject<any[]>()
69
70   protected serverConfig: ServerConfig
71
72   protected abstract notifier: Notifier
73   protected abstract authService: AuthService
74   protected abstract route: ActivatedRoute
75   protected abstract serverService: ServerService
76   protected abstract screenService: ScreenService
77   protected abstract router: Router
78   protected abstract i18n: I18n
79   abstract titlePage: string
80
81   private resizeSubscription: Subscription
82   private angularState: number
83
84   private groupedDateLabels: { [id in GroupDate]: string }
85   private groupedDates: { [id: number]: GroupDate } = {}
86
87   abstract getVideosObservable (page: number): Observable<ResultList<Video>>
88
89   abstract generateSyndicationList (): void
90
91   get user () {
92     return this.authService.getUser()
93   }
94
95   ngOnInit () {
96     this.serverConfig = this.serverService.getTmpConfig()
97     this.serverService.getConfig()
98       .subscribe(config => this.serverConfig = config)
99
100     this.groupedDateLabels = {
101       [GroupDate.UNKNOWN]: null,
102       [GroupDate.TODAY]: this.i18n('Today'),
103       [GroupDate.YESTERDAY]: this.i18n('Yesterday'),
104       [GroupDate.LAST_WEEK]: this.i18n('Last week'),
105       [GroupDate.LAST_MONTH]: this.i18n('Last month'),
106       [GroupDate.OLDER]: this.i18n('Older')
107     }
108
109     // Subscribe to route changes
110     const routeParams = this.route.snapshot.queryParams
111     this.loadRouteParams(routeParams)
112
113     this.resizeSubscription = fromEvent(window, 'resize')
114       .pipe(debounceTime(500))
115       .subscribe(() => this.calcPageSizes())
116
117     this.calcPageSizes()
118
119     const loadUserObservable = this.loadUserVideoLanguagesIfNeeded()
120
121     if (this.loadOnInit === true) {
122       loadUserObservable.subscribe(() => this.loadMoreVideos())
123     }
124   }
125
126   ngOnDestroy () {
127     if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
128   }
129
130   disableForReuse () {
131     this.disabled = true
132   }
133
134   enabledForReuse () {
135     this.disabled = false
136   }
137
138   videoById (index: number, video: Video) {
139     return video.id
140   }
141
142   onNearOfBottom () {
143     if (this.disabled) return
144
145     // Last page
146     if (this.pagination.totalItems <= (this.pagination.currentPage * this.pagination.itemsPerPage)) return
147
148     this.pagination.currentPage += 1
149
150     this.setScrollRouteParams()
151
152     this.loadMoreVideos()
153   }
154
155   loadMoreVideos (reset = false) {
156     this.getVideosObservable(this.pagination.currentPage).subscribe(
157       ({ data, total }) => {
158         this.pagination.totalItems = total
159         if (reset) this.videos = []
160         this.videos = this.videos.concat(data)
161
162         if (this.groupByDate) this.buildGroupedDateLabels()
163
164         this.onMoreVideos()
165
166         this.onDataSubject.next(data)
167       },
168
169       error => {
170         const message = this.i18n('Cannot load more videos. Try again later.')
171
172         console.error(message, { error })
173         this.notifier.error(message)
174       }
175     )
176   }
177
178   reloadVideos () {
179     this.pagination.currentPage = 1
180     this.loadMoreVideos(true)
181   }
182
183   toggleModerationDisplay () {
184     throw new Error('toggleModerationDisplay is not implemented')
185   }
186
187   removeVideoFromArray (video: Video) {
188     this.videos = this.videos.filter(v => v.id !== video.id)
189   }
190
191   buildGroupedDateLabels () {
192     let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
193
194     for (const video of this.videos) {
195       const publishedDate = video.publishedAt
196
197       if (currentGroupedDate <= GroupDate.TODAY && isToday(publishedDate)) {
198         if (currentGroupedDate === GroupDate.TODAY) continue
199
200         currentGroupedDate = GroupDate.TODAY
201         this.groupedDates[ video.id ] = currentGroupedDate
202         continue
203       }
204
205       if (currentGroupedDate <= GroupDate.YESTERDAY && isYesterday(publishedDate)) {
206         if (currentGroupedDate === GroupDate.YESTERDAY) continue
207
208         currentGroupedDate = GroupDate.YESTERDAY
209         this.groupedDates[ video.id ] = currentGroupedDate
210         continue
211       }
212
213       if (currentGroupedDate <= GroupDate.LAST_WEEK && isLastWeek(publishedDate)) {
214         if (currentGroupedDate === GroupDate.LAST_WEEK) continue
215
216         currentGroupedDate = GroupDate.LAST_WEEK
217         this.groupedDates[ video.id ] = currentGroupedDate
218         continue
219       }
220
221       if (currentGroupedDate <= GroupDate.LAST_MONTH && isLastMonth(publishedDate)) {
222         if (currentGroupedDate === GroupDate.LAST_MONTH) continue
223
224         currentGroupedDate = GroupDate.LAST_MONTH
225         this.groupedDates[ video.id ] = currentGroupedDate
226         continue
227       }
228
229       if (currentGroupedDate <= GroupDate.OLDER) {
230         if (currentGroupedDate === GroupDate.OLDER) continue
231
232         currentGroupedDate = GroupDate.OLDER
233         this.groupedDates[ video.id ] = currentGroupedDate
234       }
235     }
236   }
237
238   getCurrentGroupedDateLabel (video: Video) {
239     if (this.groupByDate === false) return undefined
240
241     return this.groupedDateLabels[this.groupedDates[video.id]]
242   }
243
244   // On videos hook for children that want to do something
245   protected onMoreVideos () { /* empty */ }
246
247   protected loadRouteParams (routeParams: { [ key: string ]: any }) {
248     this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
249     this.categoryOneOf = routeParams[ 'categoryOneOf' ]
250     this.angularState = routeParams[ 'a-state' ]
251   }
252
253   private calcPageSizes () {
254     if (this.screenService.isInMobileView()) {
255       this.pagination.itemsPerPage = 5
256     }
257   }
258
259   private setScrollRouteParams () {
260     // Already set
261     if (this.angularState) return
262
263     this.angularState = 42
264
265     const queryParams = {
266       'a-state': this.angularState,
267       categoryOneOf: this.categoryOneOf
268     }
269
270     let path = this.router.url
271     if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
272
273     this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
274   }
275
276   private loadUserVideoLanguagesIfNeeded () {
277     if (!this.authService.isLoggedIn() || !this.useUserVideoLanguagePreferences) {
278       return of(true)
279     }
280
281     return this.authService.userInformationLoaded
282         .pipe(
283           first(),
284           tap(() => this.languageOneOf = this.user.videoLanguages)
285         )
286   }
287 }