]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-miniature/abstract-video-list.ts
Refactor video links builders
[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'
28 import { HTMLServerConfig, 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: HTMLServerConfig
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.getHTMLConfig()
130
131 this.groupedDateLabels = {
132 [GroupDate.UNKNOWN]: null,
133 [GroupDate.TODAY]: $localize`Today`,
134 [GroupDate.YESTERDAY]: $localize`Yesterday`,
135 [GroupDate.THIS_WEEK]: $localize`This week`,
136 [GroupDate.THIS_MONTH]: $localize`This month`,
137 [GroupDate.LAST_MONTH]: $localize`Last month`,
138 [GroupDate.OLDER]: $localize`Older`
139 }
140
141 // Subscribe to route changes
142 const routeParams = this.route.snapshot.queryParams
143 this.loadRouteParams(routeParams)
144
145 this.resizeSubscription = fromEvent(window, 'resize')
146 .pipe(debounceTime(500))
147 .subscribe(() => this.calcPageSizes())
148
149 this.calcPageSizes()
150
151 const loadUserObservable = this.loadUserAndSettings()
152 loadUserObservable.subscribe(() => {
153 this.onUserLoadedSubject.next()
154
155 if (this.loadOnInit === true) this.loadMoreVideos()
156 })
157
158 this.userService.listenAnonymousUpdate()
159 .pipe(switchMap(() => this.loadUserAndSettings()))
160 .subscribe(() => {
161 if (this.hasDoneFirstQuery) this.reloadVideos()
162 })
163
164 // Display avatar in mobile view
165 if (this.screenService.isInMobileView()) {
166 this.displayOptions.avatar = true
167 }
168 }
169
170 ngOnDestroy () {
171 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
172 }
173
174 ngAfterContentInit () {
175 if (this.videoListHeader) {
176 // some components don't use the header: they use their own template, like my-history.component.html
177 this.setHeader.apply(this, [ this.HeaderComponent, this.headerComponentInjector ])
178 }
179 }
180
181 disableForReuse () {
182 this.disabled = true
183 }
184
185 enabledForReuse () {
186 this.disabled = false
187 }
188
189 videoById (index: number, video: Video) {
190 return video.id
191 }
192
193 onNearOfBottom () {
194 if (this.disabled) return
195
196 // No more results
197 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
198
199 this.pagination.currentPage += 1
200
201 this.setScrollRouteParams()
202
203 this.loadMoreVideos()
204 }
205
206 loadMoreVideos (reset = false) {
207 this.getVideosObservable(this.pagination.currentPage).subscribe(
208 ({ data }) => {
209 this.hasDoneFirstQuery = true
210 this.lastQueryLength = data.length
211
212 if (reset) this.videos = []
213 this.videos = this.videos.concat(data)
214
215 if (this.groupByDate) this.buildGroupedDateLabels()
216
217 this.onMoreVideos()
218
219 this.onDataSubject.next(data)
220 },
221
222 error => {
223 const message = $localize`Cannot load more videos. Try again later.`
224
225 console.error(message, { error })
226 this.notifier.error(message)
227 }
228 )
229 }
230
231 reloadVideos () {
232 this.pagination.currentPage = 1
233 this.loadMoreVideos(true)
234 }
235
236 removeVideoFromArray (video: Video) {
237 this.videos = this.videos.filter(v => v.id !== video.id)
238 }
239
240 buildGroupedDateLabels () {
241 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
242
243 const periods = [
244 {
245 value: GroupDate.TODAY,
246 validator: (d: Date) => isToday(d)
247 },
248 {
249 value: GroupDate.YESTERDAY,
250 validator: (d: Date) => isYesterday(d)
251 },
252 {
253 value: GroupDate.THIS_WEEK,
254 validator: (d: Date) => isLastWeek(d)
255 },
256 {
257 value: GroupDate.THIS_MONTH,
258 validator: (d: Date) => isThisMonth(d)
259 },
260 {
261 value: GroupDate.LAST_MONTH,
262 validator: (d: Date) => isLastMonth(d)
263 },
264 {
265 value: GroupDate.OLDER,
266 validator: () => true
267 }
268 ]
269
270 for (const video of this.videos) {
271 const publishedDate = video.publishedAt
272
273 for (let i = 0; i < periods.length; i++) {
274 const period = periods[i]
275
276 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
277
278 if (currentGroupedDate !== period.value) {
279 currentGroupedDate = period.value
280 this.groupedDates[ video.id ] = currentGroupedDate
281 }
282
283 break
284 }
285 }
286 }
287 }
288
289 getCurrentGroupedDateLabel (video: Video) {
290 if (this.groupByDate === false) return undefined
291
292 return this.groupedDateLabels[this.groupedDates[video.id]]
293 }
294
295 toggleModerationDisplay () {
296 throw new Error('toggleModerationDisplay ' + $localize`function is not implemented`)
297 }
298
299 setHeader (
300 t: Type<any> = this.HeaderComponent,
301 i: Injector = this.headerComponentInjector
302 ) {
303 const injector = i || Injector.create({
304 providers: [{
305 provide: 'data',
306 useValue: {
307 titlePage: this.titlePage,
308 titleTooltip: this.titleTooltip
309 }
310 }]
311 })
312 const viewContainerRef = this.videoListHeader
313 viewContainerRef.clear()
314
315 const componentFactory = this.cfr.resolveComponentFactory(t)
316 viewContainerRef.createComponent(componentFactory, 0, injector)
317 }
318
319 // Can be redefined by child
320 displayAsRow () {
321 return false
322 }
323
324 // On videos hook for children that want to do something
325 protected onMoreVideos () { /* empty */ }
326
327 protected load () { /* empty */ }
328
329 // Hook if the page has custom route params
330 protected loadPageRouteParams (_queryParams: Params) { /* empty */ }
331
332 protected loadRouteParams (queryParams: Params) {
333 this.sort = queryParams[ 'sort' ] as VideoSortField || this.defaultSort
334 this.categoryOneOf = queryParams[ 'categoryOneOf' ]
335 this.angularState = queryParams[ 'a-state' ]
336
337 this.loadPageRouteParams(queryParams)
338 }
339
340 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
341 if (base === 'local') {
342 return existing === 'local'
343 ? 'all-local' as 'all-local'
344 : 'local' as 'local'
345 }
346
347 return existing === 'all'
348 ? null
349 : 'all'
350 }
351
352 protected enableAllFilterIfPossible () {
353 if (!this.authService.isLoggedIn()) return
354
355 this.authService.userInformationLoaded
356 .subscribe(() => {
357 const user = this.authService.getUser()
358 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
359 })
360 }
361
362 private calcPageSizes () {
363 if (this.screenService.isInMobileView()) {
364 this.pagination.itemsPerPage = 5
365 }
366 }
367
368 private setScrollRouteParams () {
369 // Already set
370 if (this.angularState) return
371
372 this.angularState = 42
373
374 const queryParams = {
375 'a-state': this.angularState,
376 categoryOneOf: this.categoryOneOf
377 }
378
379 let path = this.getUrlWithoutParams()
380 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
381
382 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
383 }
384
385 private loadUserAndSettings () {
386 return this.userService.getAnonymousOrLoggedUser()
387 .pipe(tap(user => {
388 this.userMiniature = user
389
390 if (!this.loadUserVideoPreferences) return
391
392 this.languageOneOf = user.videoLanguages
393 this.nsfwPolicy = user.nsfwPolicy
394 }))
395 }
396
397 private getUrlWithoutParams () {
398 const urlTree = this.router.parseUrl(this.router.url)
399 urlTree.queryParams = {}
400
401 return urlTree.toString()
402 }
403 }