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

826 lines
25 KiB
TypeScript

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { trigger, style, transition, animate } from '@angular/animations';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { Entry } from '../../../shared/models/entry.model';
import { EpisodeSeenDto } from '../../../shared/models/dtos/episode-seen.dto';
import { UserCollectionsModalComponent } from '../../../shared/components/modals/list-selection-modal/user-collections-modal.component';
import { SeenModalComponent } from '../../../shared/components/modals/seen-modal/seen-modal.component';
import { ConfirmModalComponent } from '../../../shared/components/modals/confirm-modal/confirm-modal.component';
import { EntrySeenService } from '../../../core/services/entry-seen.service';
import { EntryRatingsService } from '../../../core/services/entry-ratings.service';
import { EntryService } from '../../../core/services/entry.service';
import { EpisodeSeenService } from '../../../core/services/episode-seen.service';
import { SeasonService } from '../../../core/services/season.service';
import { LibraryService } from '../../../core/services/library.service';
import { ToastrService } from 'ngx-toastr';
import { EntrySeen } from '../../../shared/models/entry-seen.model';
import { EpisodeSeenModalComponent } from '../../../shared/components/modals/episode-seen-modal/episode-seen-modal.component';
import { MediaModalComponent } from '../media-modal/media-modal.component';
import { environment } from '../../../../environments/environment.prod';
import { Collection } from '../../../shared/models/collection.model';
import { EntrySettingsModalComponent } from '../entry-settings-modal/entry-settings-modal.component';
@Component({
selector: 'app-entry-page',
templateUrl: './entry-page.component.html',
styleUrls: ['./entry-page.component.css'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('fadeInOut', [
transition(':enter', [
// void => *
style({ opacity: 0 }),
animate('0.5s ease-in', style({ opacity: 1 })),
]),
transition(':leave', [
// * => void
animate('0.5s ease-out', style({ opacity: 0 })),
]),
]),
],
})
export class EntryPageComponent implements OnInit {
entry: Entry = {} as Entry;
public showAll = false;
public initialCount = 2;
lockActions: boolean = false;
seenHistory: any[] = [];
seenHistoryToShow: any[] = [];
itemsCount: number = 0;
maxPage: number = 10;
currentPage: number = 1;
pageSize: number = 10;
constructor(
private episodeSeenService: EpisodeSeenService,
private entryService: EntryService,
private seasonService: SeasonService,
private entrySeenService: EntrySeenService,
private entryRatingsService: EntryRatingsService,
private libraryService: LibraryService,
private dialog: MatDialog,
private route: ActivatedRoute,
private router: Router,
private toastr: ToastrService
) {}
ngOnInit(): void {
this.route.data.subscribe(
(data) => {
this.entry = data['entry'] as Entry;
this.entry.isInLibrary = true;
this.entry.collections = this.entry.collections.map((c) => {
c.mediasCount = c.medias.length;
c.selectedBackdrop = this.getCollectionBackdropPath(c);
c.medias = [];
return c;
});
if (this.entry.is_tvseries) {
// ? sorting seasons
this.entry.seasons = this.entry.seasons.sort((a, b) => {
if (b.season_number == 0) b.season_number = 30; // this will make the special season go last
if (a.season_number == 0) a.season_number = 30; // this will make the special season go last
return a.season_number - b.season_number;
});
// ? getting seaons episodes
this.entry.seasons.forEach((season) => {
this.seasonService.getSeasonEpisodes(season.id).subscribe({
next: (episodes) => {
// console.log(
// `Loaded Season ${season.season_number} Episodes (${episodes.length})`
// );
season.episodes = episodes;
},
error: (error) => {
// console.log(`Couldn't fetch season episodes data:`, error);
this.toastr.success(
'Error',
`Couldn't get season ${season.season_number} episodes.`,
{
tapToDismiss: true,
progressBar: true,
positionClass: 'bottom-right',
progressAnimation: 'increasing',
}
);
season.episodes = [];
},
});
});
}
if (!this.entry) {
this.router.navigate(['/error'], {
queryParams: { error: 'Entry not found' },
});
}
},
(error) => {
console.error('Error when trying to access route data', error);
this.router.navigate(['/error'], {
queryParams: { error: 'Error fetching data' },
});
}
);
this.getEpisodesSeenHistory();
}
onRatingChange(event: Event) {
this.entryRatingsService
.updateEntryRatings(this.entry.entryRating)
.subscribe({
next: (entryRatings) => {
if (entryRatings) {
// TODO show notification
this.entry.entryRating = entryRatings;
}
},
error: (error) => {
// TODO show notification
console.error('Error updating entryRatings:', error);
},
});
}
// ! ENTRY SEEN
openEntrySeenModal(entrySeen: EntrySeen = {} as EntrySeen) {
if (!this.entry) return;
let oldData = {} as { watchDate: Date; watchedWith: string };
if (entrySeen.id) {
oldData.watchDate = entrySeen.date_seen;
oldData.watchedWith = entrySeen.seen_with;
}
const dialogRef = this.dialog.open(SeenModalComponent, {
width: '360px',
data: oldData.watchDate ? oldData : {},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
if (result.watchDate == '') {
// TODO show no was passed date notification
return;
}
let watchDate = result.watchDate;
let watchedWith = result.watchedWith.split('\n').join(', ');
if (entrySeen.id) {
const es = {
id: entrySeen.id,
date_seen: watchDate,
seen_with: watchedWith,
} as EntrySeen;
// * Update
this.entrySeenService.updateEntrySeen(es).subscribe({
next: (updatedEntrySeen) => {
if (updatedEntrySeen) {
// TODO show confirm notification
// ? replace the entry-seen object with the updated one
for (let i = 0; i < this.entry.entrySeen.length; i++) {
if (this.entry.entrySeen[i].id == updatedEntrySeen.id)
this.entry.entrySeen[i] = updatedEntrySeen;
}
}
},
error: (error) => {
console.error('Error adding entrySeen:', error);
},
});
} else {
// * Create
this.entrySeenService
.createEntrySeen(this.entry.id.toString(), watchDate, watchedWith)
.subscribe({
next: (entrySeen) => {
if (entrySeen) {
// TODO show confirm notification
this.entry.entrySeen.push(entrySeen);
// ? if the entry was in watch list creating and entry-seen would have removed it
// ? from the watchlist, so now we need to refrech libraryService in order to
// ? update the watchlist page
if (this.entry.watchlist) {
this.libraryService.refreshEntries().subscribe();
}
}
},
error: (error) => {
console.error('Error adding entrySeen:', error);
},
});
}
// TODO show notification
} else {
// console.log('Seen dialog was cancelled');
}
});
}
editEntrySeen(entrySeen: EntrySeen) {
this.openEntrySeenModal(entrySeen);
}
removeEntrySeen(id: number) {
const dialogRef = this.dialog.open(ConfirmModalComponent, {
width: '400px',
data: {
title: 'Confirmation',
message: `Are you sure you want to delete this?`,
type: 'danger',
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
if (result.confirmed != true) return;
this.entrySeenService.removeEntrySeen(id).subscribe({
next: () => {
this.toastr.success('success', `Removed successfuly.`, {
tapToDismiss: true,
progressBar: true,
positionClass: 'bottom-right',
progressAnimation: 'increasing',
});
this.entry.entrySeen = this.entry.entrySeen.filter(
(item) => item.id !== id
);
},
error: (error) => {
// TODO show notification
console.error('Error deleting entrySeen:', error);
},
});
}
});
}
toggleFavorite() {
this.lockActions = true;
this.entry.favorit = !this.entry.favorit;
const entryData = { favorit: this.entry.favorit };
this.entryService.updateEntry(this.entry.id, entryData).subscribe({
next: (entry) => {
// console.log(`Entry updated: `, entry);
this.entry = entry;
this.entry.isInLibrary = true;
},
error: (error) => {
console.log(`Error updating entry: `, error);
this.entry.favorit = !this.entry.favorit;
},
complete: () => {
this.lockActions = false;
},
});
}
toggleHidden() {
this.lockActions = true;
this.entry.hidden = !this.entry.hidden;
const entryData = { hidden: this.entry.hidden };
this.entryService.updateEntry(this.entry.id, entryData).subscribe({
next: (entry) => {
// console.log(`Entry updated: `, entry);
this.entry = entry;
this.entry.isInLibrary = true;
},
error: (error) => {
console.log(`Error updating entry: `, error);
this.entry.favorit = !this.entry.favorit;
},
complete: () => {
this.lockActions = false;
},
});
}
addToCollectionModal() {
if (this.entry) {
const dialogRef = this.dialog.open(UserCollectionsModalComponent, {
width: '400px',
height: '55%',
data: {
entryId: this.entry.id,
},
});
dialogRef.afterClosed().subscribe((result) => {
// TODO update entry page collections
this.entryService.getEntryById(this.entry.id).subscribe({
next: (result) => {
this.entry.collections = result.collections.map((c) => {
c.mediasCount = c.medias.length;
c.selectedBackdrop = this.getCollectionBackdropPath(c);
c.medias = [];
return c;
});
result.collections;
},
});
});
}
}
getCollectionBackdropPath(collection: Collection) {
// console.log(`collection media:`, collection.medias);
if (collection.medias && collection.medias.length != 0) {
const backdrops = collection.medias.filter((m) => m.type == 'backdrop');
if (backdrops.length != 0) {
const selectedBackdrops = backdrops.filter(
(m) => m.type == 'backdrop' && m.isSelected
);
// console.log(selectedBackdrops);
let selectedBackdrop;
if (selectedBackdrops.length != 0) {
selectedBackdrop = selectedBackdrops[0].path;
} else {
selectedBackdrop = backdrops[0].path;
}
return (
environment.API_URL +
`/media/collections/backdrops/preview/${selectedBackdrop}`
);
}
}
// if (collection.entries && collection.entries.length != 0) {
// // * use the poster of the first entry in the collection
// // * if the collection is empty
// return this.getEntryBackdropPath(collection.entries[0]);
// } else
if (collection.backdropPath) {
// * use first remote tmdb poster
// * if collection has none and has no entry
return `https://image.tmdb.org/t/p/w1280/${collection.backdropPath}`;
} else {
// * use default poster
// * if collection has totaly no poster
return 'assets/images/default/default-backdrop.png';
}
}
getEntryBackdropPath(entry: Entry) {
return '';
}
refrechEntry() {
this.lockActions = true;
this.entryService.refrechEntryById(this.entry.id).subscribe({
next: (entry) => {
this.entry = entry;
this.entry.isInLibrary = true;
this.entry.collections = this.entry.collections.map((c) => {
c.mediasCount = c.medias.length;
c.selectedBackdrop = this.getCollectionBackdropPath(c);
c.medias = [];
return c;
});
// console.log(`Entry refreched: `, entry);
this.toastr.success(`Movie refreshed successfuly.`, 'Success', {
tapToDismiss: true,
progressBar: true,
positionClass: 'bottom-right',
progressAnimation: 'increasing',
});
},
error: (error) => {
// TODO show error notification
console.error('Error refreching movie info:', error);
},
complete: () => {
this.lockActions = false;
},
});
}
fetchEntryCollection() {
this.lockActions = true;
this.entryService.fetchEntryCollectionById(this.entry.id).subscribe({
next: (result) => {},
error: (error) => {
// TODO show error notification
console.error('Error refreching movie info:', error);
},
complete: () => {
this.lockActions = false;
},
});
}
// ! EPISODE SEEN
// ? episode marked as seen event
onEpisodeWatchedEvent() {
this.getEpisodesSeenHistory();
}
// ? fetch episodes seen history
getEpisodesSeenHistory() {
if (!this.entry.is_tvseries) return;
this.episodeSeenService.getEpisodeSeenByEntryId(this.entry.id).subscribe({
next: (data) => {
let episodeSeens = [] as EpisodeSeenDto[];
// mapping
data.forEach((item) => {
let e = {
id: item.id,
entryId: item.entry_id,
episodeId: item.episode_id,
season_number: item.episode.season.season_number,
episode_number: item.episode.episode_number,
date_seen: item.date_seen,
seen_with: item.seen_with,
createdAt: item.createdAt,
updatedAt: item.updatedAt,
} as EpisodeSeenDto;
episodeSeens.push(e);
});
this.seenHistory = episodeSeens;
// console.log(`Episode Seen History Received: `, episodeSeens);
this.filterEpisodesSeenHistory();
},
error: (error) => {
this.seenHistory = [] as EpisodeSeenDto[];
this.filterEpisodesSeenHistory();
console.log(`Error getting episodes watch history`, error);
},
});
}
// ? filter episode seen history
filterEpisodesSeenHistory() {
var temp = [] as EpisodeSeenDto[];
temp = this.seenHistory;
const startIndex = (this.currentPage - 1) * this.pageSize;
const endIndex = startIndex + this.pageSize;
this.itemsCount = temp.length;
this.maxPage = Math.ceil(this.itemsCount / this.pageSize);
this.seenHistoryToShow = temp.slice(startIndex, endIndex);
}
addEpisodeSeen() {
if (!this.entry) return;
this.seenHistory[0];
const dialogRef = this.dialog.open(EpisodeSeenModalComponent, {
width: '360px',
data: {
entryId: this.entry.id,
season_number: this.seenHistory[0].season_number,
episode_number: this.seenHistory[0].episode_number,
},
});
dialogRef.afterClosed().subscribe((result) => {
// ? if an episode-seen was created then refresh the watch history table
if (result && result.created) {
// ? call this function to fetch the new episode-seen history
this.getEpisodesSeenHistory();
// ? Updating the episodes seen progress bar in the season card
// ? by fetching a new updated episodes list
this.entry.seasons.forEach(async (season) => {
if (season.season_number == result.season_number) {
this.seasonService.getSeasonEpisodes(season.id).subscribe({
next: (episodes) => {
// console.log(
// `Loaded Season ${season.season_number} Episodes (${episodes.length})`
// );
season.episodes = episodes;
},
error: (error) => {
console.log(`Couldn't fetch season episodes data:`, error);
// TODO show notification
season.episodes = [];
},
});
}
});
}
});
}
editEpisodeSeen(episodeSeen: EpisodeSeenDto) {
if (episodeSeen == null) return;
const dialogRef = this.dialog.open(EpisodeSeenModalComponent, {
width: '360px',
data: {
entryId: this.entry.id,
episodeSeen: episodeSeen,
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result == null) return;
if (!result.updated) return;
// ? call this function to fetch the new episode-seen history
this.getEpisodesSeenHistory();
});
}
deleteEpisodeSeen(episodeSeen: EpisodeSeenDto) {
if (episodeSeen.id == null) return;
const dialogRef = this.dialog.open(ConfirmModalComponent, {
width: '400px',
data: {
title: 'Confirmation',
message: `Are you sure you want to delete this?`,
type: 'danger',
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
if (result.confirmed != true) return;
// first start by calling the service and deleting the episode-seen
this.episodeSeenService.removeEpisodeSeen(episodeSeen.id).subscribe({
next: () => {
// console.log(`Episode seen deleted.`);
// ? call this function to fetch the new episode-seen history
// this.getEpisodesSeenHistory();
this.seenHistory = this.seenHistory.filter(
(eps) => eps.id != episodeSeen.id
);
this.filterEpisodesSeenHistory();
// ? Updating the episodes seen progress bar in the season card
// ? by fetching a new updated episodes list
this.entry.seasons.forEach(async (season) => {
if (season.season_number == episodeSeen.season_number) {
this.seasonService.getSeasonEpisodes(season.id).subscribe({
next: (episodes) => {
// console.log(
// `Loaded Season ${season.season_number} Episodes (${episodes.length})`
// );
season.episodes = episodes;
},
error: (error) => {
console.log(`Couldn't fetch season episodes data:`, error);
// TODO show notification
season.episodes = [];
},
});
}
});
// TODO show notification
},
error: (error) => {
console.log(`Episode seen delete error: `, error);
},
});
}
});
}
triggerEpisodeWatchedDeletedEvent() {
// console.log(`Emitted Episode Watched Deleted Event`);
}
// + end EPISODE SEEN
// ! pagination
goToPage(page: number) {
this.currentPage = page;
this.filterEpisodesSeenHistory();
}
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
);
}
// + end pagination
toggleShowAllSeasons() {
this.showAll = !this.showAll;
}
redirectToTmdb() {
let type = this.entry.is_tvseries ? 'tv' : 'movie';
window.open(
`https://www.themoviedb.org/${type}/${this.entry.entryId.tmdb_id}`,
'_blank'
);
}
enlargePoster() {
let poster;
// * Not in library, use TMDB poster
if (!this.entry.isInLibrary)
poster = `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
// * Is in library: use a local poster
if (!poster && this.entry.medias) {
const selectedPosters = this.entry.medias.filter(
(m) => m.type == 'poster' && m.isSelected
);
if (
selectedPosters.length &&
selectedPosters[0] &&
selectedPosters[0].path
) {
poster =
environment.API_URL +
`/media/entries/posters/original/${selectedPosters[0].path}`;
}
}
// * No local poster available, Use TMDB poster
if (!poster && this.entry.poster_path)
poster = `https://image.tmdb.org/t/p/original` + this.entry.poster_path;
// * No poster found, use default poster image as a last stand
if (!poster) poster = 'assets/images/default/default-poster.png';
window.open(poster, '_blank');
}
mediaModal() {
const dialogRef = this.dialog.open(MediaModalComponent, {
width: '800px',
height: '600px',
minHeight: '50%',
panelClass: 'media-dialog-container',
data: {
entry: this.entry,
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
// TODO show notification
} else {
// console.log('Seen dialog was cancelled');
}
});
}
settingsModal() {
const dialogRef = this.dialog.open(EntrySettingsModalComponent, {
width: '800px',
height: '600px',
minHeight: '50%',
panelClass: 'media-dialog-container',
data: {
entry: this.entry,
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.entry.watchlist = result.entry.watchlist;
this.entry.favorit = result.entry.favorit;
this.entry.hidden = result.entry.hidden;
this.entry.showInCalendar = result.entry.showInCalendar;
this.entry.autoSync = result.entry.autoSync;
} else {
}
});
}
// * getters
get status() {
return this.entry.status;
}
get runtime() {
return this.entry.runtime;
}
get genres(): string {
return this.entry.genres.join(', ');
}
get poster(): string {
// * Not in library, use TMDB poster
if (!this.entry.isInLibrary)
return `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
// * Is in library: use a local poster
if (this.entry.medias) {
const selectedPosters = this.entry.medias.filter(
(m) => m.type == 'poster' && m.isSelected
);
if (
selectedPosters.length &&
selectedPosters[0] &&
selectedPosters[0].path
) {
return (
environment.API_URL +
`/media/entries/posters/original/${selectedPosters[0].path}`
);
}
}
// * No local poster available, Use TMDB poster
if (this.entry.poster_path)
return `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
// * No poster found, use default poster image as a last stand
return 'assets/images/default/default-poster.png';
}
get banner(): string {
// * Is in library: use a local backdrop
if (this.entry.medias) {
const selectedBackdrop = this.entry.medias.filter(
(m) => m.type == 'backdrop' && m.isSelected
);
if (
selectedBackdrop.length &&
selectedBackdrop[0] &&
selectedBackdrop[0].path
) {
return (
environment.API_URL +
`/media/entries/backdrops/original/${selectedBackdrop[0].path}`
);
}
}
// * No local backdrop available, Use TMDB backdrop
if (this.entry.banner_path)
return `https://image.tmdb.org/t/p/w1280` + this.entry.banner_path;
// * No backdrop found, use default backdrop image as a last stand
return 'assets/images/default/default-poster.png';
}
get nextEpisode() {
if (!this.entry.is_tvseries) return 'This is a movie';
return 'sooon';
}
fetchEntry() {
this.entryService.getEntryById(this.entry.id).subscribe({
next: (result) => {
this.entry = { ...result, isInLibrary: true };
},
});
}
}