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