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