]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-video-miniature/abstract-video-list.ts
Merge branch 'develop' into shorter-URLs-channels-accounts
[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'
0aa52e17 28import { ServerConfig, 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
ba430d75
C
103 protected serverConfig: ServerConfig
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 () {
ba430d75
C
129 this.serverConfig = this.serverService.getTmpConfig()
130 this.serverService.getConfig()
131 .subscribe(config => this.serverConfig = config)
132
34c7f429
C
133 this.groupedDateLabels = {
134 [GroupDate.UNKNOWN]: null,
66357162
C
135 [GroupDate.TODAY]: $localize`Today`,
136 [GroupDate.YESTERDAY]: $localize`Yesterday`,
4166caab
C
137 [GroupDate.THIS_WEEK]: $localize`This week`,
138 [GroupDate.THIS_MONTH]: $localize`This month`,
66357162
C
139 [GroupDate.LAST_MONTH]: $localize`Last month`,
140 [GroupDate.OLDER]: $localize`Older`
34c7f429
C
141 }
142
fd45e8f4 143 // Subscribe to route changes
5b5e333f 144 const routeParams = this.route.snapshot.queryParams
2bbb3412 145 this.loadRouteParams(routeParams)
a2b817d3 146
9af61e84 147 this.resizeSubscription = fromEvent(window, 'resize')
db400f44 148 .pipe(debounceTime(500))
6194c1b4 149 .subscribe(() => this.calcPageSizes())
3290f37c 150
6194c1b4 151 this.calcPageSizes()
3caf77d3 152
5c20a455 153 const loadUserObservable = this.loadUserAndSettings()
07f81d9d
C
154 loadUserObservable.subscribe(() => {
155 this.onUserLoadedSubject.next()
3caf77d3 156
07f81d9d
C
157 if (this.loadOnInit === true) this.loadMoreVideos()
158 })
d3217560 159
5c20a455
C
160 this.userService.listenAnonymousUpdate()
161 .pipe(switchMap(() => this.loadUserAndSettings()))
162 .subscribe(() => {
d3217560 163 if (this.hasDoneFirstQuery) this.reloadVideos()
5c20a455 164 })
cf78883c
C
165
166 // Display avatar in mobile view
167 if (this.screenService.isInMobileView()) {
168 this.displayOptions.avatar = true
169 }
fd45e8f4
C
170 }
171
9af61e84
C
172 ngOnDestroy () {
173 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
174 }
175
5bcbcbe3
RK
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
489290b8
C
183 disableForReuse () {
184 this.disabled = true
89724816
C
185 }
186
489290b8
C
187 enabledForReuse () {
188 this.disabled = false
89724816
C
189 }
190
489290b8
C
191 videoById (index: number, video: Video) {
192 return video.id
2bbb3412
C
193 }
194
195 onNearOfBottom () {
489290b8 196 if (this.disabled) return
2bbb3412 197
440d39c5
C
198 // No more results
199 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
0cd4344f 200
15bedeeb 201 console.log('near of bottom')
489290b8 202 this.pagination.currentPage += 1
a8ecc6f6 203
489290b8 204 this.setScrollRouteParams()
a8ecc6f6 205
489290b8
C
206 this.loadMoreVideos()
207 }
fd45e8f4 208
9d45db29 209 loadMoreVideos (reset = false) {
93cae479 210 this.getVideosObservable(this.pagination.currentPage).subscribe(
440d39c5
C
211 ({ data }) => {
212 this.hasDoneFirstQuery = true
213 this.lastQueryLength = data.length
214
9d45db29 215 if (reset) this.videos = []
93cae479 216 this.videos = this.videos.concat(data)
693263e9 217
34c7f429
C
218 if (this.groupByDate) this.buildGroupedDateLabels()
219
693263e9 220 this.onMoreVideos()
ad453580
C
221
222 this.onDataSubject.next(data)
fd45e8f4 223 },
017c3dca 224
f27a885a 225 error => {
66357162 226 const message = $localize`Cannot load more videos. Try again later.`
f27a885a
C
227
228 console.error(message, { error })
229 this.notifier.error(message)
230 }
489290b8 231 )
2bbb3412
C
232 }
233
489290b8
C
234 reloadVideos () {
235 this.pagination.currentPage = 1
9d45db29 236 this.loadMoreVideos(true)
fd45e8f4
C
237 }
238
3a0fb65c
C
239 removeVideoFromArray (video: Video) {
240 this.videos = this.videos.filter(v => v.id !== video.id)
241 }
242
34c7f429
C
243 buildGroupedDateLabels () {
244 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
245
4166caab
C
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
34c7f429 270 }
4166caab 271 ]
34c7f429 272
4166caab
C
273 for (const video of this.videos) {
274 const publishedDate = video.publishedAt
34c7f429 275
4166caab
C
276 for (let i = 0; i < periods.length; i++) {
277 const period = periods[i]
4e0c1793 278
4166caab 279 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
34c7f429 280
4166caab
C
281 if (currentGroupedDate !== period.value) {
282 currentGroupedDate = period.value
283 this.groupedDates[ video.id ] = currentGroupedDate
284 }
4e0c1793 285
4166caab
C
286 break
287 }
34c7f429
C
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
0aa52e17 298 toggleModerationDisplay () {
5bcbcbe3
RK
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)
0aa52e17
C
320 }
321
4d5e572f
C
322 // Can be redefined by child
323 displayAsRow () {
324 return false
325 }
326
693263e9
C
327 // On videos hook for children that want to do something
328 protected onMoreVideos () { /* empty */ }
329
15bedeeb
C
330 protected load () { /* empty */ }
331
332 // Hook if the page has custom route params
333 protected loadPageRouteParams (_queryParams: Params) { /* empty */ }
334
335 protected loadRouteParams (queryParams: Params) {
336 this.sort = queryParams[ 'sort' ] as VideoSortField || this.defaultSort
337 this.categoryOneOf = queryParams[ 'categoryOneOf' ]
338 this.angularState = queryParams[ 'a-state' ]
339
340 this.loadPageRouteParams(queryParams)
0cd4344f 341 }
6194c1b4 342
0aa52e17
C
343 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
344 if (base === 'local') {
345 return existing === 'local'
346 ? 'all-local' as 'all-local'
347 : 'local' as 'local'
348 }
349
350 return existing === 'all'
351 ? null
352 : 'all'
353 }
354
355 protected enableAllFilterIfPossible () {
356 if (!this.authService.isLoggedIn()) return
357
358 this.authService.userInformationLoaded
359 .subscribe(() => {
360 const user = this.authService.getUser()
361 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
362 })
363 }
364
6194c1b4 365 private calcPageSizes () {
489290b8 366 if (this.screenService.isInMobileView()) {
6194c1b4 367 this.pagination.itemsPerPage = 5
6194c1b4 368 }
489290b8 369 }
6194c1b4 370
489290b8
C
371 private setScrollRouteParams () {
372 // Already set
373 if (this.angularState) return
6194c1b4 374
489290b8 375 this.angularState = 42
6194c1b4 376
489290b8
C
377 const queryParams = {
378 'a-state': this.angularState,
379 categoryOneOf: this.categoryOneOf
9af61e84 380 }
6194c1b4 381
fb7b009d 382 let path = this.getUrlWithoutParams()
ba430d75 383 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
489290b8
C
384
385 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
6194c1b4 386 }
3caf77d3 387
5c20a455
C
388 private loadUserAndSettings () {
389 return this.userService.getAnonymousOrLoggedUser()
390 .pipe(tap(user => {
391 this.userMiniature = user
d3217560 392
07f81d9d 393 if (!this.loadUserVideoPreferences) return
3caf77d3 394
5c20a455
C
395 this.languageOneOf = user.videoLanguages
396 this.nsfwPolicy = user.nsfwPolicy
397 }))
3caf77d3 398 }
fb7b009d
RK
399
400 private getUrlWithoutParams () {
40930fda 401 const urlTree = this.router.parseUrl(this.router.url)
fb7b009d 402 urlTree.queryParams = {}
40930fda 403
fb7b009d
RK
404 return urlTree.toString()
405 }
fd45e8f4 406}