8a247a9af726c87fac3c3970216c355ba2ff4063
[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, 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 } 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   protected abstract notifier: Notifier
63   protected abstract authService: AuthService
64   protected abstract route: ActivatedRoute
65   protected abstract serverService: ServerService
66   protected abstract screenService: ScreenService
67   protected abstract router: Router
68   protected abstract i18n: I18n
69   abstract titlePage: string
70
71   private resizeSubscription: Subscription
72   private angularState: number
73
74   private groupedDateLabels: { [id in GroupDate]: string }
75   private groupedDates: { [id: number]: GroupDate } = {}
76
77   abstract getVideosObservable (page: number): Observable<ResultList<Video>>
78
79   abstract generateSyndicationList (): void
80
81   get user () {
82     return this.authService.getUser()
83   }
84
85   ngOnInit () {
86     this.groupedDateLabels = {
87       [GroupDate.UNKNOWN]: null,
88       [GroupDate.TODAY]: this.i18n('Today'),
89       [GroupDate.YESTERDAY]: this.i18n('Yesterday'),
90       [GroupDate.LAST_WEEK]: this.i18n('Last week'),
91       [GroupDate.LAST_MONTH]: this.i18n('Last month'),
92       [GroupDate.OLDER]: this.i18n('Older')
93     }
94
95     // Subscribe to route changes
96     const routeParams = this.route.snapshot.queryParams
97     this.loadRouteParams(routeParams)
98
99     this.resizeSubscription = fromEvent(window, 'resize')
100       .pipe(debounceTime(500))
101       .subscribe(() => this.calcPageSizes())
102
103     this.calcPageSizes()
104
105     const loadUserObservable = this.loadUserVideoLanguagesIfNeeded()
106
107     if (this.loadOnInit === true) {
108       loadUserObservable.subscribe(() => this.loadMoreVideos())
109     }
110   }
111
112   ngOnDestroy () {
113     if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
114   }
115
116   disableForReuse () {
117     this.disabled = true
118   }
119
120   enabledForReuse () {
121     this.disabled = false
122   }
123
124   videoById (index: number, video: Video) {
125     return video.id
126   }
127
128   onNearOfBottom () {
129     if (this.disabled) return
130
131     // Last page
132     if (this.pagination.totalItems <= (this.pagination.currentPage * this.pagination.itemsPerPage)) return
133
134     this.pagination.currentPage += 1
135
136     this.setScrollRouteParams()
137
138     this.loadMoreVideos()
139   }
140
141   loadMoreVideos () {
142     this.getVideosObservable(this.pagination.currentPage).subscribe(
143       ({ data, total }) => {
144         this.pagination.totalItems = total
145         this.videos = this.videos.concat(data)
146
147         if (this.groupByDate) this.buildGroupedDateLabels()
148
149         this.onMoreVideos()
150       },
151
152       error => this.notifier.error(error.message)
153     )
154   }
155
156   reloadVideos () {
157     this.pagination.currentPage = 1
158     this.videos = []
159     this.loadMoreVideos()
160   }
161
162   toggleModerationDisplay () {
163     throw new Error('toggleModerationDisplay is not implemented')
164   }
165
166   removeVideoFromArray (video: Video) {
167     this.videos = this.videos.filter(v => v.id !== video.id)
168   }
169
170   buildGroupedDateLabels () {
171     let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
172
173     for (const video of this.videos) {
174       const publishedDate = video.publishedAt
175
176       if (currentGroupedDate <= GroupDate.TODAY && isToday(publishedDate)) {
177         if (currentGroupedDate === GroupDate.TODAY) continue
178
179         currentGroupedDate = GroupDate.TODAY
180         this.groupedDates[ video.id ] = currentGroupedDate
181         continue
182       }
183
184       if (currentGroupedDate <= GroupDate.YESTERDAY && isYesterday(publishedDate)) {
185         if (currentGroupedDate === GroupDate.YESTERDAY) continue
186
187         currentGroupedDate = GroupDate.YESTERDAY
188         this.groupedDates[ video.id ] = currentGroupedDate
189         continue
190       }
191
192       if (currentGroupedDate <= GroupDate.LAST_WEEK && isLastWeek(publishedDate)) {
193         if (currentGroupedDate === GroupDate.LAST_WEEK) continue
194
195         currentGroupedDate = GroupDate.LAST_WEEK
196         this.groupedDates[ video.id ] = currentGroupedDate
197         continue
198       }
199
200       if (currentGroupedDate <= GroupDate.LAST_MONTH && isLastMonth(publishedDate)) {
201         if (currentGroupedDate === GroupDate.LAST_MONTH) continue
202
203         currentGroupedDate = GroupDate.LAST_MONTH
204         this.groupedDates[ video.id ] = currentGroupedDate
205         continue
206       }
207
208       if (currentGroupedDate <= GroupDate.OLDER) {
209         if (currentGroupedDate === GroupDate.OLDER) continue
210
211         currentGroupedDate = GroupDate.OLDER
212         this.groupedDates[ video.id ] = currentGroupedDate
213       }
214     }
215   }
216
217   getCurrentGroupedDateLabel (video: Video) {
218     if (this.groupByDate === false) return undefined
219
220     return this.groupedDateLabels[this.groupedDates[video.id]]
221   }
222
223   // On videos hook for children that want to do something
224   protected onMoreVideos () { /* empty */ }
225
226   protected loadRouteParams (routeParams: { [ key: string ]: any }) {
227     this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
228     this.categoryOneOf = routeParams[ 'categoryOneOf' ]
229     this.angularState = routeParams[ 'a-state' ]
230   }
231
232   private calcPageSizes () {
233     if (this.screenService.isInMobileView()) {
234       this.pagination.itemsPerPage = 5
235     }
236   }
237
238   private setScrollRouteParams () {
239     // Already set
240     if (this.angularState) return
241
242     this.angularState = 42
243
244     const queryParams = {
245       'a-state': this.angularState,
246       categoryOneOf: this.categoryOneOf
247     }
248
249     let path = this.router.url
250     if (!path || path === '/') path = this.serverService.getConfig().instance.defaultClientRoute
251
252     this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
253   }
254
255   private loadUserVideoLanguagesIfNeeded () {
256     if (!this.authService.isLoggedIn() || !this.useUserVideoLanguagePreferences) {
257       return of(true)
258     }
259
260     return this.authService.userInformationLoaded
261         .pipe(
262           first(),
263           tap(() => this.languageOneOf = this.user.videoLanguages)
264         )
265   }
266 }