]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-miniature/abstract-video-list.ts
Fix NSFW policy on account/channel videos
[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, 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 { MiniatureDisplayOptions, OwnerDisplayType } from './video-miniature.component'
32 import { GenericHeaderComponent, VideoListHeaderComponent } from './video-list-header.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 ownerDisplayType: OwnerDisplayType = 'account'
69 displayModerationBlock = false
70 titleTooltip: string
71 displayVideoActions = true
72 groupByDate = false
73
74 videos: Video[] = []
75 hasDoneFirstQuery = false
76 disabled = false
77
78 displayOptions: MiniatureDisplayOptions = {
79 date: true,
80 views: true,
81 by: true,
82 avatar: false,
83 privacyLabel: true,
84 privacyText: false,
85 state: false,
86 blacklistInfo: false
87 }
88
89 actions: {
90 iconName: GlobalIconName
91 label: string
92 justIcon?: boolean
93 routerLink?: string
94 href?: string
95 click?: (e: Event) => void
96 }[] = []
97
98 onDataSubject = new Subject<any[]>()
99
100 userMiniature: User
101
102 protected onUserLoadedSubject = new ReplaySubject<void>(1)
103
104 protected serverConfig: ServerConfig
105
106 protected abstract notifier: Notifier
107 protected abstract authService: AuthService
108 protected abstract userService: UserService
109 protected abstract route: ActivatedRoute
110 protected abstract serverService: ServerService
111 protected abstract screenService: ScreenService
112 protected abstract storageService: LocalStorageService
113 protected abstract router: Router
114 protected abstract cfr: ComponentFactoryResolver
115 abstract titlePage: string
116
117 private resizeSubscription: Subscription
118 private angularState: number
119
120 private groupedDateLabels: { [id in GroupDate]: string }
121 private groupedDates: { [id: number]: GroupDate } = {}
122
123 private lastQueryLength: number
124
125 abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
126
127 abstract generateSyndicationList (): void
128
129 ngOnInit () {
130 this.serverConfig = this.serverService.getTmpConfig()
131 this.serverService.getConfig()
132 .subscribe(config => this.serverConfig = config)
133
134 this.groupedDateLabels = {
135 [GroupDate.UNKNOWN]: null,
136 [GroupDate.TODAY]: $localize`Today`,
137 [GroupDate.YESTERDAY]: $localize`Yesterday`,
138 [GroupDate.THIS_WEEK]: $localize`This week`,
139 [GroupDate.THIS_MONTH]: $localize`This month`,
140 [GroupDate.LAST_MONTH]: $localize`Last month`,
141 [GroupDate.OLDER]: $localize`Older`
142 }
143
144 // Subscribe to route changes
145 const routeParams = this.route.snapshot.queryParams
146 this.loadRouteParams(routeParams)
147
148 this.resizeSubscription = fromEvent(window, 'resize')
149 .pipe(debounceTime(500))
150 .subscribe(() => this.calcPageSizes())
151
152 this.calcPageSizes()
153
154 const loadUserObservable = this.loadUserAndSettings()
155 loadUserObservable.subscribe(() => {
156 this.onUserLoadedSubject.next()
157
158 if (this.loadOnInit === true) this.loadMoreVideos()
159 })
160
161 this.userService.listenAnonymousUpdate()
162 .pipe(switchMap(() => this.loadUserAndSettings()))
163 .subscribe(() => {
164 if (this.hasDoneFirstQuery) this.reloadVideos()
165 })
166
167 // Display avatar in mobile view
168 if (this.screenService.isInMobileView()) {
169 this.displayOptions.avatar = true
170 }
171 }
172
173 ngOnDestroy () {
174 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
175 }
176
177 ngAfterContentInit () {
178 if (this.videoListHeader) {
179 // some components don't use the header: they use their own template, like my-history.component.html
180 this.setHeader.apply(this, [ this.HeaderComponent, this.headerComponentInjector ])
181 }
182 }
183
184 disableForReuse () {
185 this.disabled = true
186 }
187
188 enabledForReuse () {
189 this.disabled = false
190 }
191
192 videoById (index: number, video: Video) {
193 return video.id
194 }
195
196 onNearOfBottom () {
197 if (this.disabled) return
198
199 // No more results
200 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
201
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 loadRouteParams (routeParams: { [ key: string ]: any }) {
326 this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
327 this.categoryOneOf = routeParams[ 'categoryOneOf' ]
328 this.angularState = routeParams[ 'a-state' ]
329 }
330
331 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
332 if (base === 'local') {
333 return existing === 'local'
334 ? 'all-local' as 'all-local'
335 : 'local' as 'local'
336 }
337
338 return existing === 'all'
339 ? null
340 : 'all'
341 }
342
343 protected enableAllFilterIfPossible () {
344 if (!this.authService.isLoggedIn()) return
345
346 this.authService.userInformationLoaded
347 .subscribe(() => {
348 const user = this.authService.getUser()
349 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
350 })
351 }
352
353 private calcPageSizes () {
354 if (this.screenService.isInMobileView()) {
355 this.pagination.itemsPerPage = 5
356 }
357 }
358
359 private setScrollRouteParams () {
360 // Already set
361 if (this.angularState) return
362
363 this.angularState = 42
364
365 const queryParams = {
366 'a-state': this.angularState,
367 categoryOneOf: this.categoryOneOf
368 }
369
370 let path = this.getUrlWithoutParams()
371 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
372
373 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
374 }
375
376 private loadUserAndSettings () {
377 return this.userService.getAnonymousOrLoggedUser()
378 .pipe(tap(user => {
379 this.userMiniature = user
380
381 if (!this.loadUserVideoPreferences) return
382
383 this.languageOneOf = user.videoLanguages
384 this.nsfwPolicy = user.nsfwPolicy
385 }))
386 }
387
388 private getUrlWithoutParams () {
389 const urlTree = this.router.parseUrl(this.router.url)
390 urlTree.queryParams = {}
391
392 return urlTree.toString()
393 }
394 }