]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-miniature/abstract-video-list.ts
Upgrade to angular 10
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-miniature / abstract-video-list.ts
1 import { fromEvent, Observable, Subject, Subscription } from 'rxjs'
2 import { debounceTime, switchMap, tap } from 'rxjs/operators'
3 import { OnDestroy, OnInit, Directive } from '@angular/core'
4 import { ActivatedRoute, Router } from '@angular/router'
5 import {
6 AuthService,
7 ComponentPaginationLight,
8 LocalStorageService,
9 Notifier,
10 ScreenService,
11 ServerService,
12 User,
13 UserService
14 } from '@app/core'
15 import { DisableForReuseHook } from '@app/core/routing/disable-for-reuse-hook'
16 import { GlobalIconName } from '@app/shared/shared-icons'
17 import { I18n } from '@ngx-translate/i18n-polyfill'
18 import { isLastMonth, isLastWeek, isToday, isYesterday } from '@shared/core-utils/miscs/date'
19 import { ServerConfig, VideoSortField } from '@shared/models'
20 import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
21 import { Syndication, Video } from '../shared-main'
22 import { MiniatureDisplayOptions, OwnerDisplayType } from './video-miniature.component'
23
24 enum GroupDate {
25 UNKNOWN = 0,
26 TODAY = 1,
27 YESTERDAY = 2,
28 LAST_WEEK = 3,
29 LAST_MONTH = 4,
30 OLDER = 5
31 }
32
33 @Directive()
34 export abstract class AbstractVideoList implements OnInit, OnDestroy, DisableForReuseHook {
35 pagination: ComponentPaginationLight = {
36 currentPage: 1,
37 itemsPerPage: 25
38 }
39 sort: VideoSortField = '-publishedAt'
40
41 categoryOneOf?: number[]
42 languageOneOf?: string[]
43 nsfwPolicy?: NSFWPolicyType
44 defaultSort: VideoSortField = '-publishedAt'
45
46 syndicationItems: Syndication[] = []
47
48 loadOnInit = true
49 useUserVideoPreferences = false
50 ownerDisplayType: OwnerDisplayType = 'account'
51 displayModerationBlock = false
52 titleTooltip: string
53 displayVideoActions = true
54 groupByDate = false
55
56 videos: Video[] = []
57 hasDoneFirstQuery = false
58 disabled = false
59
60 displayOptions: MiniatureDisplayOptions = {
61 date: true,
62 views: true,
63 by: true,
64 avatar: false,
65 privacyLabel: true,
66 privacyText: false,
67 state: false,
68 blacklistInfo: false
69 }
70
71 actions: {
72 routerLink: string
73 iconName: GlobalIconName
74 label: string
75 }[] = []
76
77 onDataSubject = new Subject<any[]>()
78
79 userMiniature: User
80
81 protected serverConfig: ServerConfig
82
83 protected abstract notifier: Notifier
84 protected abstract authService: AuthService
85 protected abstract userService: UserService
86 protected abstract route: ActivatedRoute
87 protected abstract serverService: ServerService
88 protected abstract screenService: ScreenService
89 protected abstract storageService: LocalStorageService
90 protected abstract router: Router
91 protected abstract i18n: I18n
92 abstract titlePage: string
93
94 private resizeSubscription: Subscription
95 private angularState: number
96
97 private groupedDateLabels: { [id in GroupDate]: string }
98 private groupedDates: { [id: number]: GroupDate } = {}
99
100 private lastQueryLength: number
101
102 abstract getVideosObservable (page: number): Observable<{ data: Video[] }>
103
104 abstract generateSyndicationList (): void
105
106 ngOnInit () {
107 this.serverConfig = this.serverService.getTmpConfig()
108 this.serverService.getConfig()
109 .subscribe(config => this.serverConfig = config)
110
111 this.groupedDateLabels = {
112 [GroupDate.UNKNOWN]: null,
113 [GroupDate.TODAY]: this.i18n('Today'),
114 [GroupDate.YESTERDAY]: this.i18n('Yesterday'),
115 [GroupDate.LAST_WEEK]: this.i18n('Last week'),
116 [GroupDate.LAST_MONTH]: this.i18n('Last month'),
117 [GroupDate.OLDER]: this.i18n('Older')
118 }
119
120 // Subscribe to route changes
121 const routeParams = this.route.snapshot.queryParams
122 this.loadRouteParams(routeParams)
123
124 this.resizeSubscription = fromEvent(window, 'resize')
125 .pipe(debounceTime(500))
126 .subscribe(() => this.calcPageSizes())
127
128 this.calcPageSizes()
129
130 const loadUserObservable = this.loadUserAndSettings()
131
132 if (this.loadOnInit === true) {
133 loadUserObservable.subscribe(() => this.loadMoreVideos())
134 }
135
136 this.userService.listenAnonymousUpdate()
137 .pipe(switchMap(() => this.loadUserAndSettings()))
138 .subscribe(() => {
139 if (this.hasDoneFirstQuery) this.reloadVideos()
140 })
141
142 // Display avatar in mobile view
143 if (this.screenService.isInMobileView()) {
144 this.displayOptions.avatar = true
145 }
146 }
147
148 ngOnDestroy () {
149 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
150 }
151
152 disableForReuse () {
153 this.disabled = true
154 }
155
156 enabledForReuse () {
157 this.disabled = false
158 }
159
160 videoById (index: number, video: Video) {
161 return video.id
162 }
163
164 onNearOfBottom () {
165 if (this.disabled) return
166
167 // No more results
168 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
169
170 this.pagination.currentPage += 1
171
172 this.setScrollRouteParams()
173
174 this.loadMoreVideos()
175 }
176
177 loadMoreVideos (reset = false) {
178 this.getVideosObservable(this.pagination.currentPage).subscribe(
179 ({ data }) => {
180 this.hasDoneFirstQuery = true
181 this.lastQueryLength = data.length
182
183 if (reset) this.videos = []
184 this.videos = this.videos.concat(data)
185
186 if (this.groupByDate) this.buildGroupedDateLabels()
187
188 this.onMoreVideos()
189
190 this.onDataSubject.next(data)
191 },
192
193 error => {
194 const message = this.i18n('Cannot load more videos. Try again later.')
195
196 console.error(message, { error })
197 this.notifier.error(message)
198 }
199 )
200 }
201
202 reloadVideos () {
203 this.pagination.currentPage = 1
204 this.loadMoreVideos(true)
205 }
206
207 toggleModerationDisplay () {
208 throw new Error('toggleModerationDisplay is not implemented')
209 }
210
211 removeVideoFromArray (video: Video) {
212 this.videos = this.videos.filter(v => v.id !== video.id)
213 }
214
215 buildGroupedDateLabels () {
216 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
217
218 for (const video of this.videos) {
219 const publishedDate = video.publishedAt
220
221 if (currentGroupedDate <= GroupDate.TODAY && isToday(publishedDate)) {
222 if (currentGroupedDate === GroupDate.TODAY) continue
223
224 currentGroupedDate = GroupDate.TODAY
225 this.groupedDates[ video.id ] = currentGroupedDate
226 continue
227 }
228
229 if (currentGroupedDate <= GroupDate.YESTERDAY && isYesterday(publishedDate)) {
230 if (currentGroupedDate === GroupDate.YESTERDAY) continue
231
232 currentGroupedDate = GroupDate.YESTERDAY
233 this.groupedDates[ video.id ] = currentGroupedDate
234 continue
235 }
236
237 if (currentGroupedDate <= GroupDate.LAST_WEEK && isLastWeek(publishedDate)) {
238 if (currentGroupedDate === GroupDate.LAST_WEEK) continue
239
240 currentGroupedDate = GroupDate.LAST_WEEK
241 this.groupedDates[ video.id ] = currentGroupedDate
242 continue
243 }
244
245 if (currentGroupedDate <= GroupDate.LAST_MONTH && isLastMonth(publishedDate)) {
246 if (currentGroupedDate === GroupDate.LAST_MONTH) continue
247
248 currentGroupedDate = GroupDate.LAST_MONTH
249 this.groupedDates[ video.id ] = currentGroupedDate
250 continue
251 }
252
253 if (currentGroupedDate <= GroupDate.OLDER) {
254 if (currentGroupedDate === GroupDate.OLDER) continue
255
256 currentGroupedDate = GroupDate.OLDER
257 this.groupedDates[ video.id ] = currentGroupedDate
258 }
259 }
260 }
261
262 getCurrentGroupedDateLabel (video: Video) {
263 if (this.groupByDate === false) return undefined
264
265 return this.groupedDateLabels[this.groupedDates[video.id]]
266 }
267
268 // On videos hook for children that want to do something
269 protected onMoreVideos () { /* empty */ }
270
271 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
272 this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
273 this.categoryOneOf = routeParams[ 'categoryOneOf' ]
274 this.angularState = routeParams[ 'a-state' ]
275 }
276
277 private calcPageSizes () {
278 if (this.screenService.isInMobileView()) {
279 this.pagination.itemsPerPage = 5
280 }
281 }
282
283 private setScrollRouteParams () {
284 // Already set
285 if (this.angularState) return
286
287 this.angularState = 42
288
289 const queryParams = {
290 'a-state': this.angularState,
291 categoryOneOf: this.categoryOneOf
292 }
293
294 let path = this.router.url
295 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
296
297 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
298 }
299
300 private loadUserAndSettings () {
301 return this.userService.getAnonymousOrLoggedUser()
302 .pipe(tap(user => {
303 this.userMiniature = user
304
305 if (!this.useUserVideoPreferences) return
306
307 this.languageOneOf = user.videoLanguages
308 this.nsfwPolicy = user.nsfwPolicy
309 }))
310 }
311 }