]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/video/abstract-video-list.ts
Limit thumbnail sizes
[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: false,
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 // Display avatar in mobile view
144 if (this.screenService.isInMobileView()) {
145 this.displayOptions.avatar = true
146 }
147 }
148
149 ngOnDestroy () {
150 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
151 }
152
153 disableForReuse () {
154 this.disabled = true
155 }
156
157 enabledForReuse () {
158 this.disabled = false
159 }
160
161 videoById (index: number, video: Video) {
162 return video.id
163 }
164
165 onNearOfBottom () {
166 if (this.disabled) return
167
168 // No more results
169 if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return
170
171 this.pagination.currentPage += 1
172
173 this.setScrollRouteParams()
174
175 this.loadMoreVideos()
176 }
177
178 loadMoreVideos (reset = false) {
179 this.getVideosObservable(this.pagination.currentPage).subscribe(
180 ({ data }) => {
181 this.hasDoneFirstQuery = true
182 this.lastQueryLength = data.length
183
184 if (reset) this.videos = []
185 this.videos = this.videos.concat(data)
186
187 if (this.groupByDate) this.buildGroupedDateLabels()
188
189 this.onMoreVideos()
190
191 this.onDataSubject.next(data)
192 },
193
194 error => {
195 const message = this.i18n('Cannot load more videos. Try again later.')
196
197 console.error(message, { error })
198 this.notifier.error(message)
199 }
200 )
201 }
202
203 reloadVideos () {
204 this.pagination.currentPage = 1
205 this.loadMoreVideos(true)
206 }
207
208 toggleModerationDisplay () {
209 throw new Error('toggleModerationDisplay is not implemented')
210 }
211
212 removeVideoFromArray (video: Video) {
213 this.videos = this.videos.filter(v => v.id !== video.id)
214 }
215
216 buildGroupedDateLabels () {
217 let currentGroupedDate: GroupDate = GroupDate.UNKNOWN
218
219 for (const video of this.videos) {
220 const publishedDate = video.publishedAt
221
222 if (currentGroupedDate <= GroupDate.TODAY && isToday(publishedDate)) {
223 if (currentGroupedDate === GroupDate.TODAY) continue
224
225 currentGroupedDate = GroupDate.TODAY
226 this.groupedDates[ video.id ] = currentGroupedDate
227 continue
228 }
229
230 if (currentGroupedDate <= GroupDate.YESTERDAY && isYesterday(publishedDate)) {
231 if (currentGroupedDate === GroupDate.YESTERDAY) continue
232
233 currentGroupedDate = GroupDate.YESTERDAY
234 this.groupedDates[ video.id ] = currentGroupedDate
235 continue
236 }
237
238 if (currentGroupedDate <= GroupDate.LAST_WEEK && isLastWeek(publishedDate)) {
239 if (currentGroupedDate === GroupDate.LAST_WEEK) continue
240
241 currentGroupedDate = GroupDate.LAST_WEEK
242 this.groupedDates[ video.id ] = currentGroupedDate
243 continue
244 }
245
246 if (currentGroupedDate <= GroupDate.LAST_MONTH && isLastMonth(publishedDate)) {
247 if (currentGroupedDate === GroupDate.LAST_MONTH) continue
248
249 currentGroupedDate = GroupDate.LAST_MONTH
250 this.groupedDates[ video.id ] = currentGroupedDate
251 continue
252 }
253
254 if (currentGroupedDate <= GroupDate.OLDER) {
255 if (currentGroupedDate === GroupDate.OLDER) continue
256
257 currentGroupedDate = GroupDate.OLDER
258 this.groupedDates[ video.id ] = currentGroupedDate
259 }
260 }
261 }
262
263 getCurrentGroupedDateLabel (video: Video) {
264 if (this.groupByDate === false) return undefined
265
266 return this.groupedDateLabels[this.groupedDates[video.id]]
267 }
268
269 // On videos hook for children that want to do something
270 protected onMoreVideos () { /* empty */ }
271
272 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
273 this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort
274 this.categoryOneOf = routeParams[ 'categoryOneOf' ]
275 this.angularState = routeParams[ 'a-state' ]
276 }
277
278 private calcPageSizes () {
279 if (this.screenService.isInMobileView()) {
280 this.pagination.itemsPerPage = 5
281 }
282 }
283
284 private setScrollRouteParams () {
285 // Already set
286 if (this.angularState) return
287
288 this.angularState = 42
289
290 const queryParams = {
291 'a-state': this.angularState,
292 categoryOneOf: this.categoryOneOf
293 }
294
295 let path = this.router.url
296 if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute
297
298 this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' })
299 }
300
301 private loadUserVideoLanguagesIfNeeded () {
302 if (!this.useUserVideoLanguagePreferences) {
303 return of(true)
304 }
305
306 if (!this.authService.isLoggedIn()) {
307 this.languageOneOf = this.userService.getAnonymousUser().videoLanguages
308 return of(true)
309 }
310
311 return this.authService.userInformationLoaded
312 .pipe(
313 first(),
314 tap(() => this.languageOneOf = this.user.videoLanguages)
315 )
316 }
317 }