From a3f1b16376dfa67195cdc6b7deaf8e4a11dd4a68 Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Wed, 24 Apr 2024 13:22:56 +0100 Subject: [PATCH] add edit/delete episode seens in episode seen history --- backend/routes/episodeSeenRoutes.js | 96 ++++++++++- backend/services/entryService.js | 2 + .../app/core/services/episode-seen.service.ts | 12 ++ .../collections/collections-routing.module.ts | 1 + .../entry-page/entry-page.component.html | 23 ++- .../entry/entry-page/entry-page.component.ts | 154 ++++++++++++++---- .../app/features/library/library.component.ts | 1 + .../season-main-card.component.ts | 82 ++++++++-- .../modals/seen-modal/seen-modal.component.ts | 12 +- 9 files changed, 326 insertions(+), 57 deletions(-) diff --git a/backend/routes/episodeSeenRoutes.js b/backend/routes/episodeSeenRoutes.js index 9ea0ac9..11a7ab5 100644 --- a/backend/routes/episodeSeenRoutes.js +++ b/backend/routes/episodeSeenRoutes.js @@ -115,11 +115,7 @@ episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => { order: [['date_seen', 'DESC']] }); - if (episodeSeens.length > 0) { - res.status(200).json(episodeSeens); - } else { - res.status(404).json({ message: 'No records found for the given entry ID.' }); - } + res.status(200).json(episodeSeens); } catch (error) { res.status(500).json({ error: error.message }); } @@ -128,9 +124,46 @@ episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => { // * PUT - UPDATE EPISODE SEEN episodeSeenRouter.put('/:id', async (req, res) => { try { - const { date_seen, seen_with } = req.body; + const { date_seen, seen_with, episode_id } = req.body; const updated = await EpisodeSeen.update({ date_seen, seen_with }, { where: { id: req.params.id } }); + // * episode update + // Fetch the Entry based on entry_id + const episode = await Episode.findByPk(episode_id); + if (!episode) { + return res.status(404).json({ error: "Episode not found" }); + } + + const episodeSeens = await EpisodeSeen.findAll({ + where: { + episode_id: episode_id + }, + order: [ + ['date_seen', 'DESC'] + ] + }); + + let update = {}; + const dateSeen = new Date(date_seen); + + if (episodeSeens.length == 0) { // ? case of first episodeSeen + update.date_first_seen = date_seen; + update.date_last_seen = date_seen; + } else { // ? case of 2nd+ episodeSeen + if (!episode.date_first_seen || dateSeen < new Date(episode.date_first_seen)) { + update.date_first_seen = date_seen; + } + if (!episode.date_last_seen || dateSeen > new Date(episode.date_last_seen)) { + update.date_last_seen = date_seen; + } + } + + // Update the Episode with new first or last seen dates + if (Object.keys(update).length > 0) { + await episode.update(update); + } + // + end episode update + if (updated[0] > 0) { const updatedEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); res.status(200).json(updatedEpisodeSeen); @@ -145,7 +178,57 @@ episodeSeenRouter.put('/:id', async (req, res) => { // * DELETE - EPISODE SEEN episodeSeenRouter.delete('/:id', async (req, res) => { try { + // getting the episode seen object + const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); + if (!oldEpisodeSeen) + res.status(404).json({ message: 'Episode seen record not found.' }); + + + // * episode update + const episode = await Episode.findByPk(oldEpisodeSeen.episode_id); + if (!episode) { + return res.status(404).json({ message: "Episode not found" }); + } + + // deleting the episode seen const deleted = await EpisodeSeen.destroy({ where: { id: req.params.id } }); + + const episodeSeens = await EpisodeSeen.findAll({ + where: { + episode_id: episode.id + }, + order: [ + ['date_seen', 'DESC'] + ] + }); + + let update = {}; + + if (episodeSeens.length == 0) { // ? case of 0 episodeSeen for the episode + update.date_first_seen = null; + update.date_last_seen = null; + } else { // ? case of 1+ episodeSeen for the episode + for (let i = 0; i < episodeSeens.length; i++) { + if (i == 0) { + update.date_first_seen = episodeSeens[i].date_seen; + update.date_last_seen = episodeSeens[i].date_seen; + } else { + if (episodeSeens[i].date_seen < update.date_first_seen) { + update.date_first_seen = episodeSeens[i].date_seen; + } + if (episodeSeens[i].date_seen > update.date_last_seen) { + update.date_last_seen = episodeSeens[i].date_seen; + } + } + } + } + + // Update the Episode with new first or last seen dates + if (Object.keys(update).length > 0) { + await episode.update(update); + } + // + end episode update + if (deleted) { res.status(204).send(); } else { @@ -153,6 +236,7 @@ episodeSeenRouter.delete('/:id', async (req, res) => { } } catch (error) { res.status(500).json({ error: error.message }); + console.log(error) } }); diff --git a/backend/services/entryService.js b/backend/services/entryService.js index 8f9acdd..37b6883 100644 --- a/backend/services/entryService.js +++ b/backend/services/entryService.js @@ -8,6 +8,8 @@ const { fetchSeasonData } = require('./tmdbService.js'); const Episode = require('../models/Episode.js'); async function saveEntry(data) { + if (data == null) return; + // creating the object var is_tvseries = data.release_date == null ? true : false; diff --git a/frontend/src/app/core/services/episode-seen.service.ts b/frontend/src/app/core/services/episode-seen.service.ts index fffb0e0..3d7bc33 100644 --- a/frontend/src/app/core/services/episode-seen.service.ts +++ b/frontend/src/app/core/services/episode-seen.service.ts @@ -1,6 +1,7 @@ import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { EpisodeSeen } from '../../shared/models/episodeSeen.model'; +import { EpisodeSeenDto } from '../../shared/models/dtos/episode-seen.dto'; @Injectable({ providedIn: 'root', @@ -41,6 +42,17 @@ export class EpisodeSeenService { ); } + updateEpisodeSeen(episodeSeen: EpisodeSeenDto) { + return this.http.put( + `${this.backend_apiUrl}/${this.apiAction}/${episodeSeen.id}`, + { + date_seen: episodeSeen.date_seen, + seen_with: episodeSeen.seen_with, + episode_id: episodeSeen.episodeId, + } + ); + } + removeEpisodeSeen(id: number) { return this.http.delete( `${this.backend_apiUrl}/${this.apiAction}/${id}` diff --git a/frontend/src/app/features/collections/collections-routing.module.ts b/frontend/src/app/features/collections/collections-routing.module.ts index a4656b4..ace2b0e 100644 --- a/frontend/src/app/features/collections/collections-routing.module.ts +++ b/frontend/src/app/features/collections/collections-routing.module.ts @@ -3,6 +3,7 @@ import { Routes, RouterModule } from '@angular/router'; import { UserCollectionsPageComponent } from './user-collections/userCollections-page/userCollections-page.component'; import { UserCollectionInfoPageComponent } from './user-collection-info/userCollection-info-page/userCollection-info-page.component'; +// ! /user-collections const routes: Routes = [ { path: '', diff --git a/frontend/src/app/features/entry/entry-page/entry-page.component.html b/frontend/src/app/features/entry/entry-page/entry-page.component.html index c3c3cd0..c160fb2 100644 --- a/frontend/src/app/features/entry/entry-page/entry-page.component.html +++ b/frontend/src/app/features/entry/entry-page/entry-page.component.html @@ -16,7 +16,8 @@
  • Rating: {{tmdbRating}}/10
  • -
  • Premiere: {{this.entry.release_date | dateFormat:'MMM dd, yyyy'}}
  • +
  • Premiere: {{this.entry.release_date | dateFormat:'MMM dd, yyyy'}} +
  • Next Episode: {{nextEpisode}}
  • Status: {{status}}
  • Genre: {{genres}}
  • @@ -102,7 +103,8 @@
    + [@fadeInOut] [season]="season" (episodeWatchedEvent)="onEpisodeWatchedEvent()" + (episodeWatchedDeletedEvent)="triggerEpisodeWatchedDeletedEvent()">
    @@ -122,7 +124,7 @@

    Collections

    -
    +

    Watch History

    @@ -131,7 +133,7 @@ - + @@ -140,6 +142,19 @@ + +
    Episode Date Seen Seen WithAction
    {{ item.episode_number }} {{ item.date_seen | dateFormat:'MMM dd, yyyy' }} {{ item.seen_with }} + +
    diff --git a/frontend/src/app/features/entry/entry-page/entry-page.component.ts b/frontend/src/app/features/entry/entry-page/entry-page.component.ts index 4572679..52d7c12 100644 --- a/frontend/src/app/features/entry/entry-page/entry-page.component.ts +++ b/frontend/src/app/features/entry/entry-page/entry-page.component.ts @@ -14,11 +14,9 @@ import { SeenModalComponent } from '../../../shared/components/modals/seen-modal import { EntrySeenService } from '../../../core/services/entry-seen.service'; import { EntryRatingsService } from '../../../core/services/entry-ratings.service'; -import { TmdbService } from '../../../core/services/tmdb.service'; -import { LibraryService } from '../../../core/services/library.service'; import { EntryService } from '../../../core/services/entry.service'; import { EpisodeSeenService } from '../../../core/services/episode-seen.service'; -import e from 'express'; +import { SeasonService } from '../../../core/services/season.service'; @Component({ selector: 'app-entry-page', @@ -58,6 +56,7 @@ export class EntryPageComponent implements OnInit { public dialog: MatDialog, private episodeSeenService: EpisodeSeenService, private entryService: EntryService, + private seasonService: SeasonService, private entrySeenService: EntrySeenService, private entryRatingsService: EntryRatingsService, private datePipe: DatePipe @@ -67,10 +66,31 @@ export class EntryPageComponent implements OnInit { this.route.data.subscribe( (data) => { this.entry = data['entry'] as Entry; - this.entry.seasons = this.entry.seasons.sort((a, b) => - a.name.localeCompare(b.name) - ); - console.log(this.entry); + + if (this.entry.is_tvseries) { + // ? sorting seasons + this.entry.seasons = this.entry.seasons.sort((a, b) => + a.name.localeCompare(b.name) + ); + + // ? 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); + // TODO show notification + season.episodes = []; + }, + }); + }); + } + if (!this.entry) { this.router.navigate(['/error'], { queryParams: { error: 'Entry not found' }, @@ -106,14 +126,11 @@ export class EntryPageComponent implements OnInit { return; } + let watchDate = result.watchDate; let watchedWith = result.watchedWith.split('\n').join(', '); this.entrySeenService - .createEntrySeen( - this.entry.id.toString(), - result.watchDate, - watchedWith - ) + .createEntrySeen(this.entry.id.toString(), watchDate, watchedWith) .subscribe({ next: (entrySeen) => { if (entrySeen) { @@ -151,10 +168,6 @@ export class EntryPageComponent implements OnInit { }); } - onEpisodeWatchedEvent() { - this.getEpisodesSeenHistory(); - } - removeEntrySeen(id: number) { // TODO add confirm modal this.entrySeenService.removeEntrySeen(id).subscribe({ @@ -200,6 +213,13 @@ export class EntryPageComponent implements OnInit { }); } + // ! EPISODE SEEN + // ? episode marked as seen event + onEpisodeWatchedEvent() { + this.getEpisodesSeenHistory(); + } + + // ? fetch episodes seen history getEpisodesSeenHistory() { if (!this.entry.is_tvseries) return; @@ -233,21 +253,14 @@ export class EntryPageComponent implements OnInit { this.filterEpisodesSeenHistory(); }, error: (error) => { + this.seenHistory = [] as EpisodeSeenDto[]; + this.filterEpisodesSeenHistory(); console.log(error); }, }); } - // nextPage(): void { - // this.currentPage++; - // } - - // previousPage(): void { - // if (this.currentPage > 1) { - // this.currentPage--; - // } - // } - + // ? filter episode seen history filterEpisodesSeenHistory() { var temp = [] as EpisodeSeenDto[]; @@ -261,11 +274,90 @@ export class EntryPageComponent implements OnInit { this.seenHistoryToShow = temp.slice(startIndex, endIndex); } - // totalPageCount(): number { - // return this.seenHistory.length / this.pageSize; - // } + editEpisodeSeen(episodeSeen: EpisodeSeenDto) { + if (episodeSeen == null) return; - // ? pagination + const dialogRef = this.dialog.open(SeenModalComponent, { + width: '400px', + data: { + watchDate: episodeSeen.date_seen, + watchedWith: episodeSeen.seen_with, + }, + }); + + dialogRef.afterClosed().subscribe((result) => { + // ? dialog closed + if (result == null) { + return console.log('Seen dialog was cancelled'); + } + + // ? dialog confimed + console.log('Episode seen dialog closed with:', result); + if (result.watchDate == '') { + // TODO show no date was passed notification + return console.log(`Episode seen dialog closed with no date.`); + } + + episodeSeen.date_seen = result.watchDate; + episodeSeen.seen_with = result.watchedWith.split('\n').join(', '); + + this.episodeSeenService.updateEpisodeSeen(episodeSeen).subscribe({ + next: () => { + console.log(`Episode seen updated.`); + this.getEpisodesSeenHistory(); + // TODO show notification + }, + error: (error) => { + console.log(`Episode seen update error: `, error); + // TODO show notification + }, + }); + }); + } + + deleteEpisodeSeen(episodeSeen: EpisodeSeenDto) { + if (episodeSeen.id == null) 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(); + + // trying to update 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(); @@ -294,7 +386,7 @@ export class EntryPageComponent implements OnInit { (_, i) => startPage + i ); } - // ? end pagination + // + end pagination toggleShowAllSeasons() { this.showAll = !this.showAll; diff --git a/frontend/src/app/features/library/library.component.ts b/frontend/src/app/features/library/library.component.ts index 5308083..327b54c 100644 --- a/frontend/src/app/features/library/library.component.ts +++ b/frontend/src/app/features/library/library.component.ts @@ -88,6 +88,7 @@ export class LibraryComponent { (_, i) => startPage + i ); } + // ? end pagination // ? setter setEntryType(entryType: number) { diff --git a/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts b/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts index ecec543..208d110 100644 --- a/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts +++ b/frontend/src/app/shared/cards/season-main-card/season-main-card.component.ts @@ -10,6 +10,8 @@ import { } from '@angular/animations'; import { Episode } from '../../models/episode.models'; import { EpisodeSeenService } from '../../../core/services/episode-seen.service'; +import { MatDialog } from '@angular/material/dialog'; +import { SeenModalComponent } from '../../components/modals/seen-modal/seen-modal.component'; @Component({ selector: 'app-season-main-card', @@ -37,11 +39,11 @@ export class SeasonMainCardComponent implements OnInit { constructor( private seasonService: SeasonService, - private episodeSeenService: EpisodeSeenService + private episodeSeenService: EpisodeSeenService, + public dialog: MatDialog ) {} ngOnInit(): void { - // TODO: GET SEASON EPISODES this.seasonService.getSeasonEpisodes(this.season.id).subscribe({ next: (episodes) => { console.log(`Loaded Season Episodes: `, episodes); @@ -83,29 +85,77 @@ export class SeasonMainCardComponent implements OnInit { return count; } - episodeMarkSeenClick() { + async episodeMarkSeenClick() { if (this.isLocked) return; this.isLocked = true; - // starts looping from the last available episode - for (let i = this.season.episode_count; i >= 0; i--) { + let selectedEpisode = {} as Episode; + let selectedEpisodeIndex = -1; + // * starts looping from the last available episode + if ( + this.season.episodes[this.season.episodes.length - 1].date_first_seen == + null + ) { // ? untils it finds that the previous episode episode is marked as seen // ? > in that case it chooses the current one to mark - if (i == 0 || this.season.episodes[i - 1].date_first_seen != null) { - let currentEpisode = this.season.episodes[i]; - // todo: show episode seen modal + for (let i = this.season.episodes.length - 1; i >= 0; i--) { + if (i == 0 || this.season.episodes[i - 1].date_first_seen != null) { + selectedEpisodeIndex = i; + selectedEpisode = this.season.episodes[i]; + break; + } + } + } else { + // ? in case the last episode is already marked as seen but + // ? there are other before it that are not, then start from + // ? episode 1 and look for any that are not seen + for (let i = 0; i < this.season.episodes.length; i++) { + if (this.season.episodes[i].date_first_seen == null) { + selectedEpisodeIndex = i; + selectedEpisode = this.season.episodes[i]; + break; + } + } + } + // + end loocking for episode + + if (selectedEpisode == null) return; + if (selectedEpisode.date_first_seen != null) return; + + // ? show the episode seen modal + const dialogRef = this.dialog.open(SeenModalComponent, { + width: '400px', + }); + + console.log('Episode seen dialog opened'); + await dialogRef.afterClosed().subscribe((result) => { + if (result) { + console.log('Episode seen dialog closed with:', result); + + if (result.watchDate == '') { + // TODO show no date was passed notification + this.isLocked = false; + return; + } + + let watchDate = result.watchDate; + let watchedWith = result.watchedWith.split('\n').join(', '); + this.episodeSeenService .createEpisodeSeen( this.season.entry_id, - currentEpisode.id, - new Date(), - 'Me, My Self & I' + selectedEpisode.id, + watchDate, + watchedWith ) .subscribe({ next: (episodeSeen) => { console.log(`Episode marked as seen`, episodeSeen); - this.season.episodes[i].date_first_seen = new Date(); - this.season.episodes[i].date_last_seen = new Date(); + // TODO get actualy date_first_seen & date_last_seen for episode seen (not just place holders) + this.season.episodes[selectedEpisodeIndex].date_first_seen = + new Date(); + this.season.episodes[selectedEpisodeIndex].date_last_seen = + new Date(); this.episodeWatchedEvent.emit(); // TODO show notification }, @@ -117,8 +167,10 @@ export class SeasonMainCardComponent implements OnInit { this.isLocked = false; }, }); - break; + } else { + console.log('Seen dialog was cancelled'); + this.isLocked = false; } - } + }); } } diff --git a/frontend/src/app/shared/components/modals/seen-modal/seen-modal.component.ts b/frontend/src/app/shared/components/modals/seen-modal/seen-modal.component.ts index ca3b719..77bd814 100644 --- a/frontend/src/app/shared/components/modals/seen-modal/seen-modal.component.ts +++ b/frontend/src/app/shared/components/modals/seen-modal/seen-modal.component.ts @@ -13,6 +13,7 @@ import { transition, animate, } from '@angular/animations'; +import { formatDate } from '@angular/common'; @Component({ selector: 'app-seen-modal', @@ -36,7 +37,7 @@ import { ]), ], }) -export class SeenModalComponent { +export class SeenModalComponent implements OnInit { public watchDate: string = ''; public watchedWith: string = ''; @@ -45,6 +46,15 @@ export class SeenModalComponent { @Inject(MAT_DIALOG_DATA) public data: any ) {} + ngOnInit(): void { + if (this.data == null) { + this.watchDate = formatDate(new Date(), 'yyyy-MM-dd', 'en-US'); + return; // ? no initial data was passed + } + this.watchDate = this.data.watchDate.toString().substring(0, 10); + this.watchedWith = this.data.watchedWith.split(', ').join('\n'); + } + onConfirm(): void { this.dialogRef.close({ watchDate: this.watchDate,