]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-miniature/videos-list.component.ts
Don't display no results if still loading
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-miniature / videos-list.component.ts
1 import * as debug from 'debug'
2 import { fromEvent, Observable, Subject, Subscription } from 'rxjs'
3 import { debounceTime, switchMap } from 'rxjs/operators'
4 import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges } from '@angular/core'
5 import { ActivatedRoute } from '@angular/router'
6 import { AuthService, ComponentPaginationLight, Notifier, PeerTubeRouterService, ScreenService, User, UserService } from '@app/core'
7 import { GlobalIconName } from '@app/shared/shared-icons'
8 import { isLastMonth, isLastWeek, isThisMonth, isToday, isYesterday } from '@shared/core-utils'
9 import { ResultList, UserRight, VideoSortField } from '@shared/models'
10 import { Syndication, Video } from '../shared-main'
11 import { VideoFilters, VideoFilterScope } from './video-filters.model'
12 import { MiniatureDisplayOptions } from './video-miniature.component'
13
14 const logger = debug('peertube:videos:VideosListComponent')
15
16 export type HeaderAction = {
17 iconName: GlobalIconName
18 label: string
19 justIcon?: boolean
20 routerLink?: string
21 href?: string
22 click?: (e: Event) => void
23 }
24
25 enum GroupDate {
26 UNKNOWN = 0,
27 TODAY = 1,
28 YESTERDAY = 2,
29 THIS_WEEK = 3,
30 THIS_MONTH = 4,
31 LAST_MONTH = 5,
32 OLDER = 6
33 }
34
35 @Component({
36 selector: 'my-videos-list',
37 templateUrl: './videos-list.component.html',
38 styleUrls: [ './videos-list.component.scss' ]
39 })
40 export class VideosListComponent implements OnInit, OnChanges, OnDestroy {
41 @Input() getVideosObservableFunction: (pagination: ComponentPaginationLight, filters: VideoFilters) => Observable<ResultList<Video>>
42 @Input() getSyndicationItemsFunction: (filters: VideoFilters) => Promise<Syndication[]> | Syndication[]
43 @Input() baseRouteBuilderFunction: (filters: VideoFilters) => string[]
44
45 @Input() title: string
46 @Input() titleTooltip: string
47 @Input() displayTitle = true
48
49 @Input() defaultSort: VideoSortField
50 @Input() defaultScope: VideoFilterScope = 'federated'
51 @Input() displayFilters = false
52 @Input() displayModerationBlock = false
53
54 @Input() loadUserVideoPreferences = false
55
56 @Input() displayAsRow = false
57 @Input() displayVideoActions = true
58 @Input() groupByDate = false
59
60 @Input() headerActions: HeaderAction[] = []
61
62 @Input() hideScopeFilter = false
63
64 @Input() displayOptions: MiniatureDisplayOptions = {
65 date: true,
66 views: true,
67 by: true,
68 avatar: false,
69 privacyLabel: true,
70 privacyText: false,
71 state: false,
72 blacklistInfo: false
73 }
74
75 @Input() disabled = false
76
77 @Output() filtersChanged = new EventEmitter<VideoFilters>()
78
79 videos: Video[] = []
80 filters: VideoFilters
81 syndicationItems: Syndication[]
82
83 onDataSubject = new Subject<any[]>()
84 hasDoneFirstQuery = false
85
86 userMiniature: User
87
88 private routeSub: Subscription
89 private userSub: Subscription
90 private resizeSub: Subscription
91
92 private pagination: ComponentPaginationLight = {
93 currentPage: 1,
94 itemsPerPage: 25
95 }
96
97 private groupedDateLabels: { [id in GroupDate]: string }
98 private groupedDates: { [id: number]: GroupDate } = {}
99
100 private lastQueryLength: number
101
102 constructor (
103 private notifier: Notifier,
104 private authService: AuthService,
105 private userService: UserService,
106 private route: ActivatedRoute,
107 private screenService: ScreenService,
108 private peertubeRouter: PeerTubeRouterService
109 ) {
110
111 }
112
113 ngOnInit () {
114 const hiddenFilters = this.hideScopeFilter
115 ? [ 'scope' ]
116 : []
117
118 this.filters = new VideoFilters(this.defaultSort, this.defaultScope, hiddenFilters)
119 this.filters.load({ ...this.route.snapshot.queryParams, scope: this.defaultScope })
120
121 this.groupedDateLabels = {
122 [GroupDate.UNKNOWN]: null,
123 [GroupDate.TODAY]: $localize`Today`,
124 [GroupDate.YESTERDAY]: $localize`Yesterday`,
125 [GroupDate.THIS_WEEK]: $localize`This week`,
126 [GroupDate.THIS_MONTH]: $localize`This month`,
127 [GroupDate.LAST_MONTH]: $localize`Last month`,
128 [GroupDate.OLDER]: $localize`Older`
129 }
130
131 this.resizeSub = fromEvent(window, 'resize')
132 .pipe(debounceTime(500))
133 .subscribe(() => this.calcPageSizes())
134
135 this.calcPageSizes()
136
137 this.userService.getAnonymousOrLoggedUser()
138 .subscribe(user => {
139 this.userMiniature = user
140
141 if (this.loadUserVideoPreferences) {
142 this.loadUserSettings(user)
143 }
144
145 this.scheduleOnFiltersChanged(false)
146
147 this.subscribeToAnonymousUpdate()
148 this.subscribeToSearchChange()
149 })
150
151 // Display avatar in mobile view
152 if (this.screenService.isInMobileView()) {
153 this.displayOptions.avatar = true
154 }
155 }
156
157 ngOnDestroy () {
158 if (this.resizeSub) this.resizeSub.unsubscribe()
159 if (this.routeSub) this.routeSub.unsubscribe()
160 if (this.userSub) this.userSub.unsubscribe()
161 }
162
163 ngOnChanges (changes: SimpleChanges) {
164 if (!this.filters) return
165
166 let updated = false
167
168 if (changes['defaultScope']) {
169 updated = true
170 this.filters.setDefaultScope(this.defaultScope)
171 }
172
173 if (changes['defaultSort']) {
174 updated = true
175 this.filters.setDefaultSort(this.defaultSort)
176 }
177
178 if (!updated) return
179
180 const customizedByUser = this.hasBeenCustomizedByUser()
181
182 if (!customizedByUser) {
183 if (this.loadUserVideoPreferences) {
184 this.loadUserSettings(this.userMiniature)
185 }
186
187 this.filters.reset('scope')
188 this.filters.reset('sort')
189 }
190
191 this.scheduleOnFiltersChanged(customizedByUser)
192 }
193
194 videoById (_index: number, video: Video) {
195 return video.id
196 }
197
198 onNearOfBottom () {
199 if (this.disabled) return
200
201 // No more results
202 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
203
204 this.pagination.currentPage += 1
205
206 this.loadMoreVideos()
207 }
208
209 loadMoreVideos (reset = false) {
210 if (reset) this.hasDoneFirstQuery = false
211
212 this.getVideosObservableFunction(this.pagination, this.filters)
213 .subscribe({
214 next: ({ data }) => {
215 this.hasDoneFirstQuery = true
216 this.lastQueryLength = data.length
217
218 if (reset) this.videos = []
219 this.videos = this.videos.concat(data)
220
221 if (this.groupByDate) this.buildGroupedDateLabels()
222
223 this.onDataSubject.next(data)
224 },
225
226 error: err => {
227 const message = $localize`Cannot load more videos. Try again later.`
228
229 console.error(message, { err })
230 this.notifier.error(message)
231 }
232 })
233 }
234
235 reloadVideos () {
236 this.pagination.currentPage = 1
237 this.loadMoreVideos(true)
238 }
239
240 removeVideoFromArray (video: Video) {
241 this.videos = this.videos.filter(v => v.id !== video.id)
242 }
243
244 buildGroupedDateLabels () {
245 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
246
247 const periods = [
248 {
249 value: GroupDate.TODAY,
250 validator: (d: Date) => isToday(d)
251 },
252 {
253 value: GroupDate.YESTERDAY,
254 validator: (d: Date) => isYesterday(d)
255 },
256 {
257 value: GroupDate.THIS_WEEK,
258 validator: (d: Date) => isLastWeek(d)
259 },
260 {
261 value: GroupDate.THIS_MONTH,
262 validator: (d: Date) => isThisMonth(d)
263 },
264 {
265 value: GroupDate.LAST_MONTH,
266 validator: (d: Date) => isLastMonth(d)
267 },
268 {
269 value: GroupDate.OLDER,
270 validator: () => true
271 }
272 ]
273
274 for (const video of this.videos) {
275 const publishedDate = video.publishedAt
276
277 for (let i = 0; i < periods.length; i++) {
278 const period = periods[i]
279
280 if (currentGroupedDate <= period.value && period.validator(publishedDate)) {
281
282 if (currentGroupedDate !== period.value) {
283 currentGroupedDate = period.value
284 this.groupedDates[video.id] = currentGroupedDate
285 }
286
287 break
288 }
289 }
290 }
291 }
292
293 getCurrentGroupedDateLabel (video: Video) {
294 if (this.groupByDate === false) return undefined
295
296 return this.groupedDateLabels[this.groupedDates[video.id]]
297 }
298
299 scheduleOnFiltersChanged (customizedByUser: boolean) {
300 // We'll reload videos, but avoid weird UI effect
301 this.videos = []
302
303 setTimeout(() => this.onFiltersChanged(customizedByUser))
304 }
305
306 onFiltersChanged (customizedByUser: boolean) {
307 logger('Running on filters changed')
308
309 this.updateUrl(customizedByUser)
310
311 this.filters.triggerChange()
312
313 this.reloadSyndicationItems()
314 this.reloadVideos()
315 }
316
317 protected enableAllFilterIfPossible () {
318 if (!this.authService.isLoggedIn()) return
319
320 this.authService.userInformationLoaded
321 .subscribe(() => {
322 const user = this.authService.getUser()
323 this.displayModerationBlock = user.hasRight(UserRight.SEE_ALL_VIDEOS)
324 })
325 }
326
327 private calcPageSizes () {
328 if (this.screenService.isInMobileView()) {
329 this.pagination.itemsPerPage = 5
330 }
331 }
332
333 private loadUserSettings (user: User) {
334 this.filters.setNSFWPolicy(user.nsfwPolicy)
335
336 // Don't reset language filter if we don't want to refresh the component
337 if (!this.hasBeenCustomizedByUser()) {
338 this.filters.load({ languageOneOf: user.videoLanguages })
339 }
340 }
341
342 private reloadSyndicationItems () {
343 Promise.resolve(this.getSyndicationItemsFunction(this.filters))
344 .then(items => {
345 if (!items || items.length === 0) this.syndicationItems = undefined
346 else this.syndicationItems = items
347 })
348 .catch(err => console.error('Cannot get syndication items.', err))
349 }
350
351 private updateUrl (customizedByUser: boolean) {
352 const baseQuery = this.filters.toUrlObject()
353
354 // Set or reset customized by user query param
355 const queryParams = customizedByUser || this.hasBeenCustomizedByUser()
356 ? { ...baseQuery, c: customizedByUser }
357 : baseQuery
358
359 logger('Will inject %O in URL query', queryParams)
360
361 const baseRoute = this.baseRouteBuilderFunction
362 ? this.baseRouteBuilderFunction(this.filters)
363 : []
364
365 const pathname = window.location.pathname
366
367 const baseRouteChanged = baseRoute.length !== 0 &&
368 pathname !== '/' && // Exclude special '/' case, we'll be redirected without component change
369 baseRoute.length !== 0 && pathname !== baseRoute.join('/')
370
371 if (baseRouteChanged || Object.keys(baseQuery).length !== 0 || customizedByUser) {
372 this.peertubeRouter.silentNavigate(baseRoute, queryParams)
373 }
374
375 this.filtersChanged.emit(this.filters)
376 }
377
378 private hasBeenCustomizedByUser () {
379 return this.route.snapshot.queryParams['c'] === 'true'
380 }
381
382 private subscribeToAnonymousUpdate () {
383 this.userSub = this.userService.listenAnonymousUpdate()
384 .pipe(switchMap(() => this.userService.getAnonymousOrLoggedUser()))
385 .subscribe(user => {
386 if (this.loadUserVideoPreferences) {
387 this.loadUserSettings(user)
388 }
389
390 if (this.hasDoneFirstQuery) {
391 this.reloadVideos()
392 }
393 })
394 }
395
396 private subscribeToSearchChange () {
397 this.routeSub = this.route.queryParams.subscribe(param => {
398 if (!param['search']) return
399
400 this.filters.load({ search: param['search'] })
401 this.onFiltersChanged(true)
402 })
403 }
404 }