]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-video-miniature/abstract-video-list.ts
Move to sass module
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-miniature / abstract-video-list.ts
CommitLineData
07f81d9d 1import { fromEvent, Observable, ReplaySubject, Subject, Subscription } from 'rxjs'
67ed6552 2import { debounceTime, switchMap, tap } from 'rxjs/operators'
5bcbcbe3
RK
3import {
4 AfterContentInit,
5 ComponentFactoryResolver,
6 Directive,
7 Injector,
8 OnDestroy,
9 OnInit,
10 Type,
11 ViewChild,
12 ViewContainerRef
13} from '@angular/core'
15bedeeb 14import { ActivatedRoute, Params, Router } from '@angular/router'
67ed6552
C
15import {
16 AuthService,
17 ComponentPaginationLight,
18 LocalStorageService,
19 Notifier,
20 ScreenService,
21 ServerService,
22 User,
23 UserService
24} from '@app/core'
489290b8 25import { DisableForReuseHook } from '@app/core/routing/disable-for-reuse-hook'
67ed6552 26import { GlobalIconName } from '@app/shared/shared-icons'
4166caab 27import { isLastMonth, isLastWeek, isThisMonth, isToday, isYesterday } from '@shared/core-utils/miscs/date'
2989628b 28import { HTMLServerConfig, UserRight, VideoFilter, VideoSortField } from '@shared/models'
5c20a455 29import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
67ed6552 30import { Syndication, Video } from '../shared-main'
5bcbcbe3 31import { GenericHeaderComponent, VideoListHeaderComponent } from './video-list-header.component'
733dbc53 32import { MiniatureDisplayOptions } from './video-miniature.component'
34c7f429
C
33
34enum GroupDate {
35 UNKNOWN = 0,
36 TODAY = 1,
37 YESTERDAY = 2,
4166caab
C
38 THIS_WEEK = 3,
39 THIS_MONTH = 4,
40 LAST_MONTH = 5,
41 OLDER = 6
34c7f429 42}
0cd4344f 43
583eb04b 44@Directive()
a02b93ce 45// tslint:disable-next-line: directive-class-suffix
5bcbcbe3
RK
46export 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
440d39c5 52 pagination: ComponentPaginationLight = {
fd45e8f4 53 currentPage: 1,
440d39c5 54 itemsPerPage: 25
fd45e8f4 55 }
136cce4d 56 sort: VideoSortField = '-publishedAt'
489290b8 57
5c20a455 58 categoryOneOf?: number[]
3caf77d3 59 languageOneOf?: string[]
5c20a455 60 nsfwPolicy?: NSFWPolicyType
136cce4d 61 defaultSort: VideoSortField = '-publishedAt'
489290b8 62
c199c427 63 syndicationItems: Syndication[] = []
244e76a5 64
f3aaa9a9 65 loadOnInit = true
07f81d9d
C
66 loadUserVideoPreferences = false
67
017c3dca 68 displayModerationBlock = false
9b4b15f9 69 titleTooltip: string
3a0fb65c 70 displayVideoActions = true
34c7f429 71 groupByDate = false
fd45e8f4 72
3caf77d3 73 videos: Video[] = []
440d39c5 74 hasDoneFirstQuery = false
489290b8 75 disabled = false
9af61e84 76
abf325b4
C
77 displayOptions: MiniatureDisplayOptions = {
78 date: true,
79 views: true,
80 by: true,
cf78883c 81 avatar: false,
abf325b4
C
82 privacyLabel: true,
83 privacyText: false,
84 state: false,
85 blacklistInfo: false
86 }
87
13adf228 88 actions: {
be27ef3b 89 iconName: GlobalIconName
13adf228 90 label: string
afff310e
RK
91 justIcon?: boolean
92 routerLink?: string
7af5ded4
C
93 href?: string
94 click?: (e: Event) => void
13adf228
RK
95 }[] = []
96
ad453580
C
97 onDataSubject = new Subject<any[]>()
98
5c20a455
C
99 userMiniature: User
100
07f81d9d
C
101 protected onUserLoadedSubject = new ReplaySubject<void>(1)
102
2989628b 103 protected serverConfig: HTMLServerConfig
ba430d75 104
f8b2c1b4 105 protected abstract notifier: Notifier
b2731bff 106 protected abstract authService: AuthService
d3217560 107 protected abstract userService: UserService
b2731bff 108 protected abstract route: ActivatedRoute
489290b8 109 protected abstract serverService: ServerService
bbe0f064 110 protected abstract screenService: ScreenService
d3217560 111 protected abstract storageService: LocalStorageService
489290b8 112 protected abstract router: Router
5bcbcbe3 113 protected abstract cfr: ComponentFactoryResolver
9bf9d2a5 114 abstract titlePage: string
c88593f7 115
9af61e84 116 private resizeSubscription: Subscription
489290b8
C
117 private angularState: number
118
34c7f429
C
119 private groupedDateLabels: { [id in GroupDate]: string }
120 private groupedDates: { [id: number]: GroupDate } = {}
121
440d39c5
C
122 private lastQueryLength: number
123
124 abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
9af61e84 125
c199c427 126 abstract generateSyndicationList (): void
fd45e8f4
C
127
128 ngOnInit () {
2989628b 129 this.serverConfig = this.serverService.getHTMLConfig()
ba430d75 130
34c7f429
C
131 this.groupedDateLabels = {
132 [GroupDate.UNKNOWN]: null,
66357162
C
133 [GroupDate.TODAY]: $localize`Today`,
134 [GroupDate.YESTERDAY]: $localize`Yesterday`,
4166caab
C
135 [GroupDate.THIS_WEEK]: $localize`This week`,
136 [GroupDate.THIS_MONTH]: $localize`This month`,
66357162
C
137 [GroupDate.LAST_MONTH]: $localize`Last month`,
138 [GroupDate.OLDER]: $localize`Older`
34c7f429
C
139 }
140
fd45e8f4 141 // Subscribe to route changes
5b5e333f 142 const routeParams = this.route.snapshot.queryParams
2bbb3412 143 this.loadRouteParams(routeParams)
a2b817d3 144
9af61e84 145 this.resizeSubscription = fromEvent(window, 'resize')
db400f44 146 .pipe(debounceTime(500))
6194c1b4 147 .subscribe(() => this.calcPageSizes())
3290f37c 148
6194c1b4 149 this.calcPageSizes()
3caf77d3 150
5c20a455 151 const loadUserObservable = this.loadUserAndSettings()
07f81d9d
C
152 loadUserObservable.subscribe(() => {
153 this.onUserLoadedSubject.next()
3caf77d3 154
07f81d9d
C
155 if (this.loadOnInit === true) this.loadMoreVideos()
156 })
d3217560 157
5c20a455
C
158 this.userService.listenAnonymousUpdate()
159 .pipe(switchMap(() => this.loadUserAndSettings()))
160 .subscribe(() => {
d3217560 161 if (this.hasDoneFirstQuery) this.reloadVideos()
5c20a455 162 })
cf78883c
C
163
164 // Display avatar in mobile view
165 if (this.screenService.isInMobileView()) {
166 this.displayOptions.avatar = true
167 }
fd45e8f4
C
168 }
169
9af61e84
C
170 ngOnDestroy () {
171 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
172 }
173
5bcbcbe3
RK
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
489290b8
C
181 disableForReuse () {
182 this.disabled = true
89724816
C
183 }
184
489290b8
C
185 enabledForReuse () {
186 this.disabled = false
89724816
C
187 }
188
489290b8
C
189 videoById (index: number, video: Video) {
190 return video.id
2bbb3412
C
191 }
192
193 onNearOfBottom () {
489290b8 194 if (this.disabled) return
2bbb3412 195
440d39c5
C
196 // No more results
197 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
0cd4344f 198
489290b8 199 this.pagination.currentPage += 1
a8ecc6f6 200
489290b8 201 this.setScrollRouteParams()
a8ecc6f6 202
489290b8
C
203 this.loadMoreVideos()
204 }
fd45e8f4 205
9d45db29 206 loadMoreVideos (reset = false) {
93cae479 207 this.getVideosObservable(this.pagination.currentPage).subscribe(
440d39c5
C
208 ({ data }) => {
209 this.hasDoneFirstQuery = true
210 this.lastQueryLength = data.length
211
9d45db29 212 if (reset) this.videos = []
93cae479 213 this.videos = this.videos.concat(data)
693263e9 214
34c7f429
C
215 if (this.groupByDate) this.buildGroupedDateLabels()
216
693263e9 217 this.onMoreVideos()
ad453580
C
218
219 this.onDataSubject.next(data)
fd45e8f4 220 },
017c3dca 221
f27a885a 222 error => {
66357162 223 const message = $localize`Cannot load more videos. Try again later.`
f27a885a
C
224
225 console.error(message, { error })
226 this.notifier.error(message)
227 }
489290b8 228 )
2bbb3412
C
229 }
230
489290b8
C
231 reloadVideos () {
232 this.pagination.currentPage = 1
9d45db29 233 this.loadMoreVideos(true)
fd45e8f4
C
234 }
235
3a0fb65c
C
236 removeVideoFromArray (video: Video) {
237 this.videos = this.videos.filter(v => v.id !== video.id)
238 }
239
34c7f429
C
240 buildGroupedDateLabels () {
241 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
242
4166caab
C
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
34c7f429 267 }
4166caab 268 ]
34c7f429 269
4166caab
C
270 for (const video of this.videos) {
271 const publishedDate = video.publishedAt
34c7f429 272
4166caab
C
273 for (let i = 0; i < periods.length; i++) {
274 const period = periods[i]
4e0c1793 275
4166caab 276 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
34c7f429 277
4166caab
C
278 if (currentGroupedDate !== period.value) {
279 currentGroupedDate = period.value
280 this.groupedDates[ video.id ] = currentGroupedDate
281 }
4e0c1793 282
4166caab
C
283 break
284 }
34c7f429
C
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
0aa52e17 295 toggleModerationDisplay () {
5bcbcbe3
RK
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)
0aa52e17
C
317 }
318
4d5e572f
C
319 // Can be redefined by child
320 displayAsRow () {
321 return false
322 }
323
693263e9
C
324 // On videos hook for children that want to do something
325 protected onMoreVideos () { /* empty */ }
326
15bedeeb
C
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)
0cd4344f 338 }
6194c1b4 339
0aa52e17
C
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
6194c1b4 362 private calcPageSizes () {
489290b8 363 if (this.screenService.isInMobileView()) {
6194c1b4 364 this.pagination.itemsPerPage = 5
6194c1b4 365 }
489290b8 366 }
6194c1b4 367
489290b8
C
368 private setScrollRouteParams () {
369 // Already set
370 if (this.angularState) return
6194c1b4 371
489290b8 372 this.angularState = 42
6194c1b4 373
489290b8
C
374 const queryParams = {
375 'a-state': this.angularState,
376 categoryOneOf: this.categoryOneOf
9af61e84 377 }
6194c1b4 378
fb7b009d 379 let path = this.getUrlWithoutParams()
ba430d75 380 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
489290b8
C
381
382 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
6194c1b4 383 }
3caf77d3 384
5c20a455
C
385 private loadUserAndSettings () {
386 return this.userService.getAnonymousOrLoggedUser()
387 .pipe(tap(user => {
388 this.userMiniature = user
d3217560 389
07f81d9d 390 if (!this.loadUserVideoPreferences) return
3caf77d3 391
5c20a455
C
392 this.languageOneOf = user.videoLanguages
393 this.nsfwPolicy = user.nsfwPolicy
394 }))
3caf77d3 395 }
fb7b009d
RK
396
397 private getUrlWithoutParams () {
40930fda 398 const urlTree = this.router.parseUrl(this.router.url)
fb7b009d 399 urlTree.queryParams = {}
40930fda 400
fb7b009d
RK
401 return urlTree.toString()
402 }
fd45e8f4 403}