Files
Showy/frontend/src/app/features/library/library-page/library-page.component.ts
T

554 lines
15 KiB
TypeScript

import { AfterViewInit, Component, OnInit } from '@angular/core';
import { Entry } from '../../../shared/models/entry.model';
import { LibraryService } from '../../../core/services/library.service';
import { ActivatedRoute, Event, Router } from '@angular/router';
import { LibraryQueryParams } from '../../../shared/models/library-query-params';
import { SettingsService } from '../../../core/services/settings.service';
import { Settings } from '../../../shared/models/settings.model';
import { ScrollService } from '../../../core/services/scroll.service';
import { Subscription } from 'rxjs';
declare var $: any;
@Component({
selector: 'app-library-page',
templateUrl: './library-page.component.html',
styleUrls: ['./library-page.component.css'],
})
export class LibraryPageComponent implements OnInit, AfterViewInit {
entries: Entry[] = [];
entriesList: Entry[] = [];
entriesToDisplay: Entry[] = [];
// ? pagination
entriesCount: number = 0;
maxPage: number = 10;
currentPage: number = 1;
pageSize: number = 10;
viewMode: string = 'grid';
// ? filter
years: { label: string; value: string }[] = [];
genres = [
{ label: 'Action & Adventure', value: 'Action & Adventure' },
{ label: 'Animation', value: 'Animation' },
{ label: 'Comedy', value: 'Comedy' },
{ label: 'Crime', value: 'Crime' },
{ label: 'Documentary', value: 'Documentary' },
{ label: 'Drama', value: 'Drama' },
{ label: 'Family', value: 'Family' },
{ label: 'Kids', value: 'Kids' },
{ label: 'Mystery', value: 'Mystery' },
{ label: 'News', value: 'News' },
{ label: 'Reality', value: 'Reality' },
{ label: 'Sci-Fi & Fantasy', value: 'Sci-Fi & Fantasy' },
{ label: 'Soap', value: 'Soap' },
{ label: 'Talk', value: 'Talk' },
{ label: 'War & Politics', value: 'War & Politics' },
{ label: 'Western', value: 'Western' },
{ label: 'Action', value: 'Action' },
{ label: 'Adventure', value: 'Adventure' },
{ label: 'Fantasy', value: 'Fantasy' },
{ label: 'History', value: 'History' },
{ label: 'Horror', value: 'Horror' },
{ label: 'Music', value: 'Music' },
{ label: 'Romance', value: 'Romance' },
{ label: 'Science Fiction', value: 'Science Fiction' },
{ label: 'TV Movie', value: 'TV Movie' },
{ label: 'Thriller', value: 'Thriller' },
{ label: 'War', value: 'War' },
];
filterCriteria: {
title?: string;
type: number;
years?: string[];
genres?: string[];
favorit: boolean;
watchlist: boolean;
hidden: boolean;
matchAll: boolean;
} = {
title: '',
type: 0,
years: [],
genres: [],
favorit: false,
watchlist: false,
hidden: false,
matchAll: true,
};
private scrollSubscription!: Subscription;
constructor(
private router: Router,
private route: ActivatedRoute,
private libraryService: LibraryService,
private settingsService: SettingsService,
private scrollService: ScrollService
) {}
async ngOnInit() {
this.getDefaultViewMode();
this.pageSize = await this.getDefaultTableSize();
await this.getEntries(true);
// this.router.events.subscribe((event) => {
// if (event instanceof NavigationEnd && event.url === '/library') {
// this.pageSize = this.getDefaultPageSize();
// this.getEntries(true);
// }
// });
this.scrollSubscription = this.scrollService.scrollEnd$.subscribe(() => {
if (this.viewMode == 'grid') {
this.loadNext();
}
});
}
ngAfterViewInit() {
// $('#year-select')
// .select2({
// placeholder: 'Year(s)...',
// allowClear: true,
// closeOnSelect: false,
// })
// .on('change', (event: { target: any }) => {
// this.onYearsChange(event);
// });
// $('#genre-select')
// .select2({
// placeholder: 'Genre(s)...',
// allowClear: true,
// closeOnSelect: false,
// })
// .on('change', (event: { target: any }) => {
// this.onGenresChange(event);
// });
// $('#year-select').val(this.filterCriteria.years)
// $('#genre-select').val(this.filterCriteria.genres)
}
ngOnDestroy(): void {
// Unsubscribe to avoid memory leaks
if (this.scrollSubscription) {
this.scrollSubscription.unsubscribe();
}
}
// ? uses libraryService to get library all entries
getEntries(forceFetch: boolean = false) {
this.libraryService.newGetAllEntries().subscribe({
next: (entries) => {
this.entries = entries.filter((e) => !e.watchlist);
this.populateYears();
this.getQueryParameters();
this.filterEntries();
},
error: (error) => {
console.log(`Couldn't get entries.`, error);
// TODO show notification
},
});
}
getDefaultViewMode() {
this.settingsService.getSettings().subscribe({
next: (s) => {
this.viewMode = s.libraryViewMode || 'grid';
},
error: (error) => {
console.log(`Couldn't get settings information, `, error);
},
});
}
setViewMode(mode: string) {
this.viewMode = mode;
const newSettings = { libraryViewMode: this.viewMode } as Settings;
this.settingsService.updateSettings(newSettings).subscribe({
next: (s) => {
// ? view mode updated
},
error: (error) => {
// error updating view mode
},
});
}
// ! FILTER
getQueryParameters() {
this.route.queryParams.subscribe((params) => {
this.currentPage = params['page'] ? parseInt(params['page'], 10) : 1;
this.filterCriteria.title = params['title'] || '';
this.filterCriteria.favorit = params.hasOwnProperty('favorit')
? params['favorit']
: false;
this.filterCriteria.years = params['years']
? params['years'].split(',')
: [];
this.filterCriteria.genres = params['genres']
? params['genres'].split(',')
: [];
this.filterCriteria.type = params.hasOwnProperty('type')
? params['type']
: 0;
this.filterCriteria.hidden = params.hasOwnProperty('hidden')
? params['hidden']
: false;
this.filterCriteria.matchAll = params.hasOwnProperty('matchAll')
? params['matchAll']
: true;
// this.filterCriteria();
// this.setQueryParameters(); // * update url query
// console.log(this.filterCriteria);
});
}
setQueryParameters() {
let params = { page: this.currentPage } as LibraryQueryParams;
// ? title
if (this.filterCriteria.title?.trim() != '') {
params.title = this.filterCriteria.title?.trim();
}
// ? years
if (this.filterCriteria.years?.length) {
params.years = this.filterCriteria.years.join(',');
}
// ? genres
if (this.filterCriteria.genres?.length) {
params.genres = this.filterCriteria.genres.join(',');
}
// ? type
if (this.filterCriteria.type != 0) {
params.type = this.filterCriteria.type;
}
// ? favorit
if (this.filterCriteria.favorit != false) {
params.favorit = this.filterCriteria.favorit;
}
// ? hidden
if (this.filterCriteria.hidden != false) {
params.hidden = this.filterCriteria.hidden;
}
// ? matchAll
if (this.filterCriteria.matchAll != true) {
params.matchAll = this.filterCriteria.matchAll;
}
// $('#year-select').val([])
// console.log( $('#year-select').val());
this.router.navigate([], {
relativeTo: this.route,
queryParams: params,
queryParamsHandling: '',
});
}
populateYears() {
this.years = [
...new Set(
this.entries.map((entry) => new Date(entry.release_date).getFullYear())
),
]
.sort((a, b) => b - a)
.map((year) => ({ label: year.toString(), value: year.toString() }));
}
clearFilter() {
this.filterCriteria = {
title: '',
type: 0,
years: [],
genres: [],
favorit: false,
watchlist: false,
hidden: false,
matchAll: true,
};
this.setQueryParameters();
this.filterEntries();
}
async filterEntries() {
var temp = [] as Entry[];
const formattedTitle =
this.filterCriteria.title?.toLowerCase().trim() || '';
temp = await this.entries.filter((entry) => {
// * Type check
let filterType = this.filterCriteria.type - 1 == 0 ? false : true;
if (this.filterCriteria.type != 0 && filterType != entry.is_tvseries) {
return false; // Skip entry if the type does not match, unless type is 'all' (0)
}
// * Hidden check
// ? skip hidden if show hidden is not checked
if (!this.filterCriteria.hidden && entry.hidden) {
return false;
}
const entryYear = new Date(entry.release_date).getFullYear().toString();
// ! Match all criteria logic
if (this.filterCriteria.matchAll) {
return (
((formattedTitle
? entry.title.toLowerCase().includes(formattedTitle) ||
entry.original_title.toLowerCase().includes(formattedTitle)
: true) ||
entry.networks
.map((network) => network.name.toLowerCase())
.some((networkName) =>
networkName.includes(
formattedTitle.replace('network:', '').toLowerCase().trim()
)
)) &&
(this.filterCriteria.genres?.length
? this.filterCriteria.genres.every((genre) =>
entry.genres.includes(genre)
)
: true) &&
(this.filterCriteria.years?.length
? this.filterCriteria.years.includes(entryYear)
: true) &&
(this.filterCriteria.favorit ? entry.favorit : true) &&
(this.filterCriteria.watchlist ? entry.watchlist : true) &&
(this.filterCriteria.hidden ? entry.hidden : true)
);
}
// ! Match at least one criteria logic
return (
(formattedTitle
? entry.title.toLowerCase().includes(formattedTitle) ||
entry.original_title.toLowerCase().includes(formattedTitle)
: true) ||
entry.networks
.map((network) => network.name.toLowerCase())
.some(
(networkName) =>
networkName ==
formattedTitle.replace('network:', '').toLowerCase()
) ||
(this.filterCriteria.genres?.length &&
this.filterCriteria.genres.some((genre) =>
entry.genres.includes(genre)
)) ||
(this.filterCriteria.years?.length &&
this.filterCriteria.years.includes(entryYear)) ||
(this.filterCriteria.favorit && entry.favorit) ||
(this.filterCriteria.watchlist && entry.watchlist)
);
});
// console.log(temp);
// ? sort filter
this.entriesList = await this.sortEntries(temp);
this.entriesCount = this.entriesList.length;
this.maxPage = Math.ceil(this.entriesCount / this.pageSize);
if (this.currentPage > this.maxPage) this.currentPage = this.maxPage; // fix for when 1 entry in the last page is removed
this.entriesToDisplay = [];
if (this.viewMode == 'table') {
this.getPageContent();
} else if (this.viewMode == 'grid') {
this.loadNext();
}
}
clearSelection(type: string) {
this.currentPage = 1;
if (type == 'years') {
this.filterCriteria.years = [];
} else if (type == 'genres') {
this.filterCriteria.genres = [];
}
this.filterEntries();
this.setQueryParameters();
}
isYearSelected(value: string): boolean {
return this.filterCriteria.years?.includes(value) || false;
}
isGenreSelected(value: string): boolean {
return this.filterCriteria.genres?.includes(value) || false;
}
// + FILTER END
private loadNext(): void {
const nextItems = this.entriesList.slice(
this.entriesToDisplay.length,
Math.min(this.entriesToDisplay.length + 30, this.entriesList.length)
);
if (nextItems.length > 0) {
this.entriesToDisplay = [...this.entriesToDisplay, ...nextItems];
}
}
private getPageContent(): void {
const startIndex = (this.currentPage - 1) * this.pageSize;
const endIndex = startIndex + this.pageSize;
this.entriesToDisplay = this.entriesList.slice(startIndex, endIndex);
}
// ! sorting
sortEntries(entries: Entry[]) {
return entries.sort(
(a, b) =>
new Date(b.date_last_seen).getTime() -
new Date(a.date_last_seen).getTime()
);
}
// ! calculated fields
moviesCount() {
return this.entries.filter((e) => !e.is_tvseries).length;
}
seriesCount() {
return this.entries.filter((e) => e.is_tvseries).length;
}
favoritCount() {
return this.entries.filter((e) => e.favorit).length;
}
hiddenCount() {
return this.entries.filter((e) => e.hidden).length;
}
// ! events catcher
entryRemoved(event: Event) {
this.entries = this.entries.filter(
(e) => e.id.toString() != event.toString()
);
this.pageSize = this.getDefaultPageSize();
this.filterEntries();
this.setQueryParameters(); // * update url query
}
// * filter events
onYearsChange(year: string) {
this.currentPage = 1;
if (this.filterCriteria.years?.includes(year)) {
this.filterCriteria.years = this.filterCriteria.years.filter(
(y) => y != year
);
} else {
this.filterCriteria.years?.push(year);
}
this.filterEntries();
this.setQueryParameters(); // * update url query
}
onGenresChange(genre: string) {
this.currentPage = 1;
if (this.filterCriteria.genres?.includes(genre)) {
this.filterCriteria.genres = this.filterCriteria.genres.filter(
(y) => y != genre
);
} else {
this.filterCriteria.genres?.push(genre);
}
this.filterEntries();
this.setQueryParameters(); // * update url query
}
onFilterChange() {
this.currentPage = 1;
this.filterEntries();
this.setQueryParameters(); // * update url query
}
onEntryTypeChange(entryType: number) {
this.filterCriteria.type = entryType;
this.currentPage = 1;
this.filterEntries();
this.setQueryParameters(); // * update url query
}
setFavorit() {
this.filterCriteria.favorit = !this.filterCriteria.favorit;
this.currentPage = 1;
this.filterEntries();
this.setQueryParameters(); // * update url query
}
setHidden() {
this.filterCriteria.hidden = !this.filterCriteria.hidden;
this.currentPage = 1;
this.filterEntries();
this.setQueryParameters(); // * update url query
}
// + end filter event
// ! pagination
setPageSize(event: any) {
this.pageSize = event.target.value;
this.filterEntries();
}
getDefaultPageSize() {
// TODO get default page size from settings service
return 54;
}
getDefaultTableSize() {
// TODO get default page size from settings service
return 10;
}
goToPage(page: number) {
this.currentPage = page;
this.getPageContent();
this.setQueryParameters(); // * update url query
}
get pageNumbers(): number[] {
let pagesToShow = 5; // Total pages to show at any time
let startPage: number, endPage: number;
if (this.maxPage <= pagesToShow) {
startPage = 1;
endPage = this.maxPage;
} else {
startPage = Math.max(this.currentPage - Math.floor(pagesToShow / 2), 1);
endPage = startPage + pagesToShow - 1;
if (endPage >= this.maxPage) {
endPage = this.maxPage;
startPage = endPage - pagesToShow + 1;
}
}
// Generate the page numbers array.
return Array.from(
{ length: endPage - startPage + 1 },
(_, i) => startPage + i
);
}
}