X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=client%2Fsrc%2Fapp%2Fshared%2Fvideo%2Fabstract-video-list.ts;h=2f5f82aa379e410d7e22bc6beae53fba79163701;hb=4c1def5fd8e9f483238eb38e221f555e2e6bbf07;hp=c18ebcf5463d5c893b853c337ba67aa8ff79df00;hpb=75236b98782c337959853ad3d2e981a01c599cff;p=github%2FChocobozzz%2FPeerTube.git diff --git a/client/src/app/shared/video/abstract-video-list.ts b/client/src/app/shared/video/abstract-video-list.ts index c18ebcf54..2f5f82aa3 100644 --- a/client/src/app/shared/video/abstract-video-list.ts +++ b/client/src/app/shared/video/abstract-video-list.ts @@ -1,218 +1,292 @@ -import { ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core' +import { debounceTime, first, tap } from 'rxjs/operators' +import { OnDestroy, OnInit } from '@angular/core' import { ActivatedRoute, Router } from '@angular/router' -import { isInMobileView } from '@app/shared/misc/utils' -import { InfiniteScrollerDirective } from '@app/shared/video/infinite-scroller.directive' -import { NotificationsService } from 'angular2-notifications' -import 'rxjs/add/operator/debounceTime' -import { Observable } from 'rxjs/Observable' -import { fromEvent } from 'rxjs/observable/fromEvent' -import { Subscription } from 'rxjs/Subscription' +import { fromEvent, Observable, of, Subject, Subscription } from 'rxjs' import { AuthService } from '../../core/auth' -import { ComponentPagination } from '../rest/component-pagination.model' -import { SortField } from './sort-field.type' +import { ComponentPaginationLight } from '../rest/component-pagination.model' +import { VideoSortField } from './sort-field.type' import { Video } from './video.model' +import { ScreenService } from '@app/shared/misc/screen.service' +import { MiniatureDisplayOptions, OwnerDisplayType } from '@app/shared/video/video-miniature.component' +import { Syndication } from '@app/shared/video/syndication.model' +import { Notifier, ServerService } from '@app/core' +import { DisableForReuseHook } from '@app/core/routing/disable-for-reuse-hook' +import { I18n } from '@ngx-translate/i18n-polyfill' +import { isLastMonth, isLastWeek, isToday, isYesterday } from '@shared/core-utils/miscs/date' +import { ServerConfig } from '@shared/models' +import { GlobalIconName } from '@app/shared/images/global-icon.component' + +enum GroupDate { + UNKNOWN = 0, + TODAY = 1, + YESTERDAY = 2, + LAST_WEEK = 3, + LAST_MONTH = 4, + OLDER = 5 +} -export abstract class AbstractVideoList implements OnInit, OnDestroy { - private static LINES_PER_PAGE = 4 - - @ViewChild('videosElement') videosElement: ElementRef - @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective - - pagination: ComponentPagination = { +export abstract class AbstractVideoList implements OnInit, OnDestroy, DisableForReuseHook { + pagination: ComponentPaginationLight = { currentPage: 1, - itemsPerPage: 10, - totalItems: null + itemsPerPage: 25 } - sort: SortField = '-createdAt' - defaultSort: SortField = '-createdAt' + sort: VideoSortField = '-publishedAt' + + categoryOneOf?: number + languageOneOf?: string[] + defaultSort: VideoSortField = '-publishedAt' + + syndicationItems: Syndication[] = [] + loadOnInit = true - pageHeight: number - videoWidth: number - videoHeight: number - videoPages: Video[][] = [] + useUserVideoLanguagePreferences = false + ownerDisplayType: OwnerDisplayType = 'account' + displayModerationBlock = false + titleTooltip: string + displayVideoActions = true + groupByDate = false + + videos: Video[] = [] + hasDoneFirstQuery = false + disabled = false + + displayOptions: MiniatureDisplayOptions = { + date: true, + views: true, + by: true, + privacyLabel: true, + privacyText: false, + state: false, + blacklistInfo: false + } - protected baseVideoWidth = 215 - protected baseVideoHeight = 230 + actions: { + routerLink: string + iconName: GlobalIconName + label: string + }[] = [] - protected abstract notificationsService: NotificationsService + onDataSubject = new Subject() + + protected serverConfig: ServerConfig + + protected abstract notifier: Notifier protected abstract authService: AuthService - protected abstract router: Router protected abstract route: ActivatedRoute - protected abstract currentRoute: string + protected abstract serverService: ServerService + protected abstract screenService: ScreenService + protected abstract router: Router + protected abstract i18n: I18n abstract titlePage: string - protected loadedPages: { [ id: number ]: Video[] } = {} - protected otherRouteParams = {} - private resizeSubscription: Subscription + private angularState: number + + private groupedDateLabels: { [id in GroupDate]: string } + private groupedDates: { [id: number]: GroupDate } = {} + + private lastQueryLength: number - abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}> + abstract getVideosObservable (page: number): Observable<{ data: Video[] }> + + abstract generateSyndicationList (): void get user () { return this.authService.getUser() } ngOnInit () { + this.serverConfig = this.serverService.getTmpConfig() + this.serverService.getConfig() + .subscribe(config => this.serverConfig = config) + + this.groupedDateLabels = { + [GroupDate.UNKNOWN]: null, + [GroupDate.TODAY]: this.i18n('Today'), + [GroupDate.YESTERDAY]: this.i18n('Yesterday'), + [GroupDate.LAST_WEEK]: this.i18n('Last week'), + [GroupDate.LAST_MONTH]: this.i18n('Last month'), + [GroupDate.OLDER]: this.i18n('Older') + } + // Subscribe to route changes - const routeParams = this.route.snapshot.params + const routeParams = this.route.snapshot.queryParams this.loadRouteParams(routeParams) this.resizeSubscription = fromEvent(window, 'resize') - .debounceTime(500) + .pipe(debounceTime(500)) .subscribe(() => this.calcPageSizes()) this.calcPageSizes() - if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage) + + const loadUserObservable = this.loadUserVideoLanguagesIfNeeded() + + if (this.loadOnInit === true) { + loadUserObservable.subscribe(() => this.loadMoreVideos()) + } } ngOnDestroy () { if (this.resizeSubscription) this.resizeSubscription.unsubscribe() } - onNearOfTop () { - this.previousPage() + disableForReuse () { + this.disabled = true } - onNearOfBottom () { - if (this.hasMoreVideos()) { - this.nextPage() - } + enabledForReuse () { + this.disabled = false } - onPageChanged (page: number) { - this.pagination.currentPage = page - this.setNewRouteParams() + videoById (index: number, video: Video) { + return video.id } - reloadVideos () { - this.loadedPages = {} - this.loadMoreVideos(this.pagination.currentPage) + onNearOfBottom () { + if (this.disabled) return + + // No more results + if (this.lastQueryLength !== undefined && this.lastQueryLength < this.pagination.itemsPerPage) return + + this.pagination.currentPage += 1 + + this.setScrollRouteParams() + + this.loadMoreVideos() } - loadMoreVideos (page: number) { - if (this.loadedPages[page] !== undefined) return + loadMoreVideos (reset = false) { + this.getVideosObservable(this.pagination.currentPage).subscribe( + ({ data }) => { + this.hasDoneFirstQuery = true + this.lastQueryLength = data.length - const observable = this.getVideosObservable(page) + if (reset) this.videos = [] + this.videos = this.videos.concat(data) - observable.subscribe( - ({ videos, totalVideos }) => { - // Paging is too high, return to the first one - if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) { - this.pagination.currentPage = 1 - this.setNewRouteParams() - return this.reloadVideos() - } + if (this.groupByDate) this.buildGroupedDateLabels() - this.loadedPages[page] = videos - this.buildVideoPages() - this.pagination.totalItems = totalVideos + this.onMoreVideos() - // Initialize infinite scroller now we loaded the first page - if (Object.keys(this.loadedPages).length === 1) { - // Wait elements creation - setTimeout(() => this.infiniteScroller.initialize(), 500) - } + this.onDataSubject.next(data) }, - error => this.notificationsService.error('Error', error.message) + + error => { + const message = this.i18n('Cannot load more videos. Try again later.') + + console.error(message, { error }) + this.notifier.error(message) + } ) } - protected hasMoreVideos () { - // No results - if (this.pagination.totalItems === 0) return false + reloadVideos () { + this.pagination.currentPage = 1 + this.loadMoreVideos(true) + } - // Not loaded yet - if (!this.pagination.totalItems) return true + toggleModerationDisplay () { + throw new Error('toggleModerationDisplay is not implemented') + } - const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage - return maxPage > this.maxPageLoaded() + removeVideoFromArray (video: Video) { + this.videos = this.videos.filter(v => v.id !== video.id) } - protected previousPage () { - const min = this.minPageLoaded() + buildGroupedDateLabels () { + let currentGroupedDate: GroupDate = GroupDate.UNKNOWN - if (min > 1) { - this.loadMoreVideos(min - 1) - } - } + for (const video of this.videos) { + const publishedDate = video.publishedAt - protected nextPage () { - this.loadMoreVideos(this.maxPageLoaded() + 1) - } + if (currentGroupedDate <= GroupDate.TODAY && isToday(publishedDate)) { + if (currentGroupedDate === GroupDate.TODAY) continue - protected buildRouteParams () { - // There is always a sort and a current page - const params = { - sort: this.sort, - page: this.pagination.currentPage - } + currentGroupedDate = GroupDate.TODAY + this.groupedDates[ video.id ] = currentGroupedDate + continue + } - return Object.assign(params, this.otherRouteParams) - } + if (currentGroupedDate <= GroupDate.YESTERDAY && isYesterday(publishedDate)) { + if (currentGroupedDate === GroupDate.YESTERDAY) continue - protected loadRouteParams (routeParams: { [ key: string ]: any }) { - this.sort = routeParams['sort'] as SortField || this.defaultSort + currentGroupedDate = GroupDate.YESTERDAY + this.groupedDates[ video.id ] = currentGroupedDate + continue + } + + if (currentGroupedDate <= GroupDate.LAST_WEEK && isLastWeek(publishedDate)) { + if (currentGroupedDate === GroupDate.LAST_WEEK) continue - if (routeParams['page'] !== undefined) { - this.pagination.currentPage = parseInt(routeParams['page'], 10) - } else { - this.pagination.currentPage = 1 + currentGroupedDate = GroupDate.LAST_WEEK + this.groupedDates[ video.id ] = currentGroupedDate + continue + } + + if (currentGroupedDate <= GroupDate.LAST_MONTH && isLastMonth(publishedDate)) { + if (currentGroupedDate === GroupDate.LAST_MONTH) continue + + currentGroupedDate = GroupDate.LAST_MONTH + this.groupedDates[ video.id ] = currentGroupedDate + continue + } + + if (currentGroupedDate <= GroupDate.OLDER) { + if (currentGroupedDate === GroupDate.OLDER) continue + + currentGroupedDate = GroupDate.OLDER + this.groupedDates[ video.id ] = currentGroupedDate + } } } - protected setNewRouteParams () { - const routeParams = this.buildRouteParams() - this.router.navigate([ this.currentRoute, routeParams ]) - } + getCurrentGroupedDateLabel (video: Video) { + if (this.groupByDate === false) return undefined - protected buildVideoPages () { - this.videoPages = Object.values(this.loadedPages) + return this.groupedDateLabels[this.groupedDates[video.id]] } - private minPageLoaded () { - return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10))) - } + // On videos hook for children that want to do something + protected onMoreVideos () { /* empty */ } - private maxPageLoaded () { - return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10))) + protected loadRouteParams (routeParams: { [ key: string ]: any }) { + this.sort = routeParams[ 'sort' ] as VideoSortField || this.defaultSort + this.categoryOneOf = routeParams[ 'categoryOneOf' ] + this.angularState = routeParams[ 'a-state' ] } private calcPageSizes () { - if (isInMobileView() || this.baseVideoWidth === -1) { + if (this.screenService.isInMobileView()) { this.pagination.itemsPerPage = 5 - - // Video takes all the width - this.videoWidth = -1 - // Same ratios than base width/height - this.videoHeight = this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth) - this.pageHeight = this.pagination.itemsPerPage * this.videoHeight - } else { - this.videoWidth = this.baseVideoWidth - this.videoHeight = this.baseVideoHeight - - const videosWidth = this.videosElement.nativeElement.offsetWidth - this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE - this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE } + } + + private setScrollRouteParams () { + // Already set + if (this.angularState) return - // Rebuild pages because maybe we modified the number of items per page - const videos = [].concat(...this.videoPages) - this.loadedPages = {} + this.angularState = 42 - let i = 1 - // Don't include the last page if it not complete - while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop - this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage) - i++ + const queryParams = { + 'a-state': this.angularState, + categoryOneOf: this.categoryOneOf } - // Re fetch the last page - if (videos.length !== 0) { - this.loadMoreVideos(i) - } else { - this.buildVideoPages() + let path = this.router.url + if (!path || path === '/') path = this.serverConfig.instance.defaultClientRoute + + this.router.navigate([ path ], { queryParams, replaceUrl: true, queryParamsHandling: 'merge' }) + } + + private loadUserVideoLanguagesIfNeeded () { + if (!this.authService.isLoggedIn() || !this.useUserVideoLanguagePreferences) { + return of(true) } - console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage) + return this.authService.userInformationLoaded + .pipe( + first(), + tap(() => this.languageOneOf = this.user.videoLanguages) + ) } }