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