]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-miniature/abstract-video-list.ts
Refactor video miniature
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-miniature / abstract-video-list.ts
1 import { fromEvent, Observable, ReplaySubject, Subject, Subscription } from 'rxjs'
2 import { debounceTime, switchMap, tap } from 'rxjs/operators'
3 import {
4 AfterContentInit,
5 ComponentFactoryResolver,
6 Directive,
7 Injector,
8 OnDestroy,
9 OnInit,
10 Type,
11 ViewChild,
12 ViewContainerRef
13 } from '@angular/core'
14 import { ActivatedRoute, Params, Router } from '@angular/router'
15 import {
16 AuthService,
17 ComponentPaginationLight,
18 LocalStorageService,
19 Notifier,
20 ScreenService,
21 ServerService,
22 User,
23 UserService
24 } from '@app/core'
25 import { DisableForReuseHook } from '@app/core/routing/disable-for-reuse-hook'
26 import { GlobalIconName } from '@app/shared/shared-icons'
27 import { isLastMonth, isLastWeek, isThisMonth, isToday, isYesterday } from '@shared/core-utils/miscs/date'
28 import { ServerConfig, UserRight, VideoFilter, VideoSortField } from '@shared/models'
29 import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
30 import { Syndication, Video } from '../shared-main'
31 import { GenericHeaderComponent, VideoListHeaderComponent } from './video-list-header.component'
32 import { MiniatureDisplayOptions } from './video-miniature.component'
33
34 enum GroupDate {
35 UNKNOWN = 0,
36 TODAY = 1,
37 YESTERDAY = 2,
38 THIS_WEEK = 3,
39 THIS_MONTH = 4,
40 LAST_MONTH = 5,
41 OLDER = 6
42 }
43
44 @Directive()
45 // tslint:disable-next-line: directive-class-suffix
46 export abstract class AbstractVideoList implements OnInit, OnDestroy, AfterContentInit, DisableForReuseHook {
47 @ViewChild('videoListHeader', { static: true, read: ViewContainerRef }) videoListHeader: ViewContainerRef
48
49 HeaderComponent: Type<GenericHeaderComponent> = VideoListHeaderComponent
50 headerComponentInjector: Injector
51
52 pagination: ComponentPaginationLight = {
53 currentPage: 1,
54 itemsPerPage: 25
55 }
56 sort: VideoSortField = '-publishedAt'
57
58 categoryOneOf?: number[]
59 languageOneOf?: string[]
60 nsfwPolicy?: NSFWPolicyType
61 defaultSort: VideoSortField = '-publishedAt'
62
63 syndicationItems: Syndication[] = []
64
65 loadOnInit = true
66 loadUserVideoPreferences = false
67
68 displayModerationBlock = false
69 titleTooltip: string
70 displayVideoActions = true
71 groupByDate = false
72
73 videos: Video[] = []
74 hasDoneFirstQuery = false
75 disabled = false
76
77 displayOptions: MiniatureDisplayOptions = {
78 date: true,
79 views: true,
80 by: true,
81 avatar: false,
82 privacyLabel: true,
83 privacyText: false,
84 state: false,
85 blacklistInfo: false
86 }
87
88 actions: {
89 iconName: GlobalIconName
90 label: string
91 justIcon?: boolean
92 routerLink?: string
93 href?: string
94 click?: (e: Event) => void
95 }[] = []
96
97 onDataSubject = new Subject<any[]>()
98
99 userMiniature: User
100
101 protected onUserLoadedSubject = new ReplaySubject<void>(1)
102
103 protected serverConfig: ServerConfig
104
105 protected abstract notifier: Notifier
106 protected abstract authService: AuthService
107 protected abstract userService: UserService
108 protected abstract route: ActivatedRoute
109 protected abstract serverService: ServerService
110 protected abstract screenService: ScreenService
111 protected abstract storageService: LocalStorageService
112 protected abstract router: Router
113 protected abstract cfr: ComponentFactoryResolver
114 abstract titlePage: string
115
116 private resizeSubscription: Subscription
117 private angularState: number
118
119 private groupedDateLabels: { [id in GroupDate]: string }
120 private groupedDates: { [id: number]: GroupDate } = {}
121
122 private lastQueryLength: number
123
124 abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
125
126 abstract generateSyndicationList (): void
127
128 ngOnInit () {
129 this.serverConfig = this.serverService.getTmpConfig()
130 this.serverService.getConfig()
131 .subscribe(config => this.serverConfig = config)
132
133 this.groupedDateLabels = {
134 [GroupDate.UNKNOWN]: null,
135 [GroupDate.TODAY]: $localize`Today`,
136 [GroupDate.YESTERDAY]: $localize`Yesterday`,
137 [GroupDate.THIS_WEEK]: $localize`This week`,
138 [GroupDate.THIS_MONTH]: $localize`This month`,
139 [GroupDate.LAST_MONTH]: $localize`Last month`,
140 [GroupDate.OLDER]: $localize`Older`
141 }
142
143 // Subscribe to route changes
144 const routeParams = this.route.snapshot.queryParams
145 this.loadRouteParams(routeParams)
146
147 this.resizeSubscription = fromEvent(window, 'resize')
148 .pipe(debounceTime(500))
149 .subscribe(() => this.calcPageSizes())
150
151 this.calcPageSizes()
152
153 const loadUserObservable = this.loadUserAndSettings()
154 loadUserObservable.subscribe(() => {
155 this.onUserLoadedSubject.next()
156
157 if (this.loadOnInit === true) this.loadMoreVideos()
158 })
159
160 this.userService.listenAnonymousUpdate()
161 .pipe(switchMap(() => this.loadUserAndSettings()))
162 .subscribe(() => {
163 if (this.hasDoneFirstQuery) this.reloadVideos()
164 })
165
166 // Display avatar in mobile view
167 if (this.screenService.isInMobileView()) {
168 this.displayOptions.avatar = true
169 }
170 }
171
172 ngOnDestroy () {
173 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
174 }
175
176 ngAfterContentInit () {
177 if (this.videoListHeader) {
178 // some components don't use the header: they use their own template, like my-history.component.html
179 this.setHeader.apply(this, [ this.HeaderComponent, this.headerComponentInjector ])
180 }
181 }
182
183 disableForReuse () {
184 this.disabled = true
185 }
186
187 enabledForReuse () {
188 this.disabled = false
189 }
190
191 videoById (index: number, video: Video) {
192 return video.id
193 }
194
195 onNearOfBottom () {
196 if (this.disabled) return
197
198 // No more results
199 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
200
201 console.log('near of bottom')
202 this.pagination.currentPage += 1
203
204 this.setScrollRouteParams()
205
206 this.loadMoreVideos()
207 }
208
209 loadMoreVideos (reset = false) {
210 this.getVideosObservable(this.pagination.currentPage).subscribe(
211 ({ data }) => {
212 this.hasDoneFirstQuery = true
213 this.lastQueryLength = data.length
214
215 if (reset) this.videos = []
216 this.videos = this.videos.concat(data)
217
218 if (this.groupByDate) this.buildGroupedDateLabels()
219
220 this.onMoreVideos()
221
222 this.onDataSubject.next(data)
223 },
224
225 error => {
226 const message = $localize`Cannot load more videos. Try again later.`
227
228 console.error(message, { error })
229 this.notifier.error(message)
230 }
231 )
232 }
233
234 reloadVideos () {
235 this.pagination.currentPage = 1
236 this.loadMoreVideos(true)
237 }
238
239 removeVideoFromArray (video: Video) {
240 this.videos = this.videos.filter(v => v.id !== video.id)
241 }
242
243 buildGroupedDateLabels () {
244 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
245
246 const periods = [
247 {
248 value: GroupDate.TODAY,
249 validator: (d: Date) => isToday(d)
250 },
251 {
252 value: GroupDate.YESTERDAY,
253 validator: (d: Date) => isYesterday(d)
254 },
255 {
256 value: GroupDate.THIS_WEEK,
257 validator: (d: Date) => isLastWeek(d)
258 },
259 {
260 value: GroupDate.THIS_MONTH,
261 validator: (d: Date) => isThisMonth(d)
262 },
263 {
264 value: GroupDate.LAST_MONTH,
265 validator: (d: Date) => isLastMonth(d)
266 },
267 {
268 value: GroupDate.OLDER,
269 validator: () => true
270 }
271 ]
272
273 for (const video of this.videos) {
274 const publishedDate = video.publishedAt
275
276 for (let i = 0; i < periods.length; i++) {
277 const period = periods[i]
278
279 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
280
281 if (currentGroupedDate !== period.value) {
282 currentGroupedDate = period.value
283 this.groupedDates[ video.id ] = currentGroupedDate
284 }
285
286 break
287 }
288 }
289 }
290 }
291
292 getCurrentGroupedDateLabel (video: Video) {
293 if (this.groupByDate === false) return undefined
294
295 return this.groupedDateLabels[this.groupedDates[video.id]]
296 }
297
298 toggleModerationDisplay () {
299 throw new Error('toggleModerationDisplay ' + $localize`function is not implemented`)
300 }
301
302 setHeader (
303 t: Type<any> = this.HeaderComponent,
304 i: Injector = this.headerComponentInjector
305 ) {
306 const injector = i || Injector.create({
307 providers: [{
308 provide: 'data',
309 useValue: {
310 titlePage: this.titlePage,
311 titleTooltip: this.titleTooltip
312 }
313 }]
314 })
315 const viewContainerRef = this.videoListHeader
316 viewContainerRef.clear()
317
318 const componentFactory = this.cfr.resolveComponentFactory(t)
319 viewContainerRef.createComponent(componentFactory, 0, injector)
320 }
321
322 // On videos hook for children that want to do something
323 protected onMoreVideos () { /* empty */ }
324
325 protected load () { /* empty */ }
326
327 // Hook if the page has custom route params
328 protected loadPageRouteParams (_queryParams: Params) { /* empty */ }
329
330 protected loadRouteParams (queryParams: Params) {
331 this.sort = queryParams[ 'sort' ] as VideoSortField || this.defaultSort
332 this.categoryOneOf = queryParams[ 'categoryOneOf' ]
333 this.angularState = queryParams[ 'a-state' ]
334
335 this.loadPageRouteParams(queryParams)
336 }
337
338 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
339 if (base === 'local') {
340 return existing === 'local'
341 ? 'all-local' as 'all-local'
342 : 'local' as 'local'
343 }
344
345 return existing === 'all'
346 ? null
347 : 'all'
348 }
349
350 protected enableAllFilterIfPossible () {
351 if (!this.authService.isLoggedIn()) return
352
353 this.authService.userInformationLoaded
354 .subscribe(() => {
355 const user = this.authService.getUser()
356 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
357 })
358 }
359
360 private calcPageSizes () {
361 if (this.screenService.isInMobileView()) {
362 this.pagination.itemsPerPage = 5
363 }
364 }
365
366 private setScrollRouteParams () {
367 // Already set
368 if (this.angularState) return
369
370 this.angularState = 42
371
372 const queryParams = {
373 'a-state': this.angularState,
374 categoryOneOf: this.categoryOneOf
375 }
376
377 let path = this.getUrlWithoutParams()
378 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
379
380 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
381 }
382
383 private loadUserAndSettings () {
384 return this.userService.getAnonymousOrLoggedUser()
385 .pipe(tap(user => {
386 this.userMiniature = user
387
388 if (!this.loadUserVideoPreferences) return
389
390 this.languageOneOf = user.videoLanguages
391 this.nsfwPolicy = user.nsfwPolicy
392 }))
393 }
394
395 private getUrlWithoutParams () {
396 const urlTree = this.router.parseUrl(this.router.url)
397 urlTree.queryParams = {}
398
399 return urlTree.toString()
400 }
401 }