]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-miniature/abstract-video-list.ts
Fix live/upload redirection
[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 // eslint-disable-next-line @angular-eslint/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(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)
208 .subscribe({
209 next: ({ data }) => {
210 this.hasDoneFirstQuery = true
211 this.lastQueryLength = data.length
212
213 if (reset) this.videos = []
214 this.videos = this.videos.concat(data)
215
216 if (this.groupByDate) this.buildGroupedDateLabels()
217
218 this.onMoreVideos()
219
220 this.onDataSubject.next(data)
221 },
222
223 error: err => {
224 const message = $localize`Cannot load more videos. Try again later.`
225
226 console.error(message, { err })
227 this.notifier.error(message)
228 }
229 })
230 }
231
232 reloadVideos () {
233 this.pagination.currentPage = 1
234 this.loadMoreVideos(true)
235 }
236
237 removeVideoFromArray (video: Video) {
238 this.videos = this.videos.filter(v => v.id !== video.id)
239 }
240
241 buildGroupedDateLabels () {
242 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
243
244 const periods = [
245 {
246 value: GroupDate.TODAY,
247 validator: (d: Date) => isToday(d)
248 },
249 {
250 value: GroupDate.YESTERDAY,
251 validator: (d: Date) => isYesterday(d)
252 },
253 {
254 value: GroupDate.THIS_WEEK,
255 validator: (d: Date) => isLastWeek(d)
256 },
257 {
258 value: GroupDate.THIS_MONTH,
259 validator: (d: Date) => isThisMonth(d)
260 },
261 {
262 value: GroupDate.LAST_MONTH,
263 validator: (d: Date) => isLastMonth(d)
264 },
265 {
266 value: GroupDate.OLDER,
267 validator: () => true
268 }
269 ]
270
271 for (const video of this.videos) {
272 const publishedDate = video.publishedAt
273
274 for (let i = 0; i < periods.length; i++) {
275 const period = periods[i]
276
277 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
278
279 if (currentGroupedDate !== period.value) {
280 currentGroupedDate = period.value
281 this.groupedDates[video.id] = currentGroupedDate
282 }
283
284 break
285 }
286 }
287 }
288 }
289
290 getCurrentGroupedDateLabel (video: Video) {
291 if (this.groupByDate === false) return undefined
292
293 return this.groupedDateLabels[this.groupedDates[video.id]]
294 }
295
296 toggleModerationDisplay () {
297 throw new Error('toggleModerationDisplay ' + $localize`function is not implemented`)
298 }
299
300 setHeader (
301 t: Type<any> = this.HeaderComponent,
302 i: Injector = this.headerComponentInjector
303 ) {
304 const injector = i || Injector.create({
305 providers: [ {
306 provide: 'data',
307 useValue: {
308 titlePage: this.titlePage,
309 titleTooltip: this.titleTooltip
310 }
311 } ]
312 })
313 const viewContainerRef = this.videoListHeader
314 viewContainerRef.clear()
315
316 const componentFactory = this.cfr.resolveComponentFactory(t)
317 viewContainerRef.createComponent(componentFactory, 0, injector)
318 }
319
320 // Can be redefined by child
321 displayAsRow () {
322 return false
323 }
324
325 // On videos hook for children that want to do something
326 protected onMoreVideos () { /* empty */ }
327
328 protected load () { /* empty */ }
329
330 // Hook if the page has custom route params
331 protected loadPageRouteParams (_queryParams: Params) { /* empty */ }
332
333 protected loadRouteParams (queryParams: Params) {
334 this.sort = queryParams['sort'] as VideoSortField || this.defaultSort
335 this.categoryOneOf = queryParams['categoryOneOf']
336 this.angularState = queryParams['a-state']
337
338 this.loadPageRouteParams(queryParams)
339 }
340
341 protected buildLocalFilter (existing: VideoFilter, base: VideoFilter) {
342 if (base === 'local') {
343 return existing === 'local'
344 ? 'all-local' as 'all-local'
345 : 'local' as 'local'
346 }
347
348 return existing === 'all'
349 ? null
350 : 'all'
351 }
352
353 protected enableAllFilterIfPossible () {
354 if (!this.authService.isLoggedIn()) return
355
356 this.authService.userInformationLoaded
357 .subscribe(() => {
358 const user = this.authService.getUser()
359 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
360 })
361 }
362
363 private calcPageSizes () {
364 if (this.screenService.isInMobileView()) {
365 this.pagination.itemsPerPage = 5
366 }
367 }
368
369 private setScrollRouteParams () {
370 // Already set
371 if (this.angularState) return
372
373 this.angularState = 42
374
375 const queryParams = {
376 'a-state': this.angularState,
377 categoryOneOf: this.categoryOneOf
378 }
379
380 let path = this.getUrlWithoutParams()
381 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
382
383 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
384 }
385
386 private loadUserAndSettings () {
387 return this.userService.getAnonymousOrLoggedUser()
388 .pipe(tap(user => {
389 this.userMiniature = user
390
391 if (!this.loadUserVideoPreferences) return
392
393 this.languageOneOf = user.videoLanguages
394 this.nsfwPolicy = user.nsfwPolicy
395 }))
396 }
397
398 private getUrlWithoutParams () {
399 const urlTree = this.router.parseUrl(this.router.url)
400 urlTree.queryParams = {}
401
402 return urlTree.toString()
403 }
404 }