add edit/delete episode seens in episode seen history

This commit is contained in:
X4Lo committed 2024-04-24 13:22:56 +01:00
1 parent dbeb0ee524
commit a3f1b16376
9 files changed
+321 -52

No files matched your search

+89 -5
View File
@@ -115,11 +115,7 @@ episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => {
order: [['date_seen', 'DESC']] order: [['date_seen', 'DESC']]
}); });
if (episodeSeens.length > 0) {
res.status(200).json(episodeSeens); res.status(200).json(episodeSeens);
} else {
res.status(404).json({ message: 'No records found for the given entry ID.' });
}
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
@@ -128,9 +124,46 @@ episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => {
// * PUT - UPDATE EPISODE SEEN // * PUT - UPDATE EPISODE SEEN
episodeSeenRouter.put('/:id', async (req, res) => { episodeSeenRouter.put('/:id', async (req, res) => {
try { 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 } }); 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) { if (updated[0] > 0) {
const updatedEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); const updatedEpisodeSeen = await EpisodeSeen.findByPk(req.params.id);
res.status(200).json(updatedEpisodeSeen); res.status(200).json(updatedEpisodeSeen);
@@ -145,7 +178,57 @@ episodeSeenRouter.put('/:id', async (req, res) => {
// * DELETE - EPISODE SEEN // * DELETE - EPISODE SEEN
episodeSeenRouter.delete('/:id', async (req, res) => { episodeSeenRouter.delete('/:id', async (req, res) => {
try { 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 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) { if (deleted) {
res.status(204).send(); res.status(204).send();
} else { } else {
@@ -153,6 +236,7 @@ episodeSeenRouter.delete('/:id', async (req, res) => {
} }
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
console.log(error)
} }
}); });
+2
View File
@@ -8,6 +8,8 @@ const { fetchSeasonData } = require('./tmdbService.js');
const Episode = require('../models/Episode.js'); const Episode = require('../models/Episode.js');
async function saveEntry(data) { async function saveEntry(data) {
if (data == null) return;
// creating the object // creating the object
var is_tvseries = data.release_date == null ? true : false; var is_tvseries = data.release_date == null ? true : false;
@@ -1,6 +1,7 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { EpisodeSeen } from '../../shared/models/episodeSeen.model'; import { EpisodeSeen } from '../../shared/models/episodeSeen.model';
import { EpisodeSeenDto } from '../../shared/models/dtos/episode-seen.dto';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@@ -41,6 +42,17 @@ export class EpisodeSeenService {
); );
} }
updateEpisodeSeen(episodeSeen: EpisodeSeenDto) {
return this.http.put<any>(
`${this.backend_apiUrl}/${this.apiAction}/${episodeSeen.id}`,
{
date_seen: episodeSeen.date_seen,
seen_with: episodeSeen.seen_with,
episode_id: episodeSeen.episodeId,
}
);
}
removeEpisodeSeen(id: number) { removeEpisodeSeen(id: number) {
return this.http.delete<any>( return this.http.delete<any>(
`${this.backend_apiUrl}/${this.apiAction}/${id}` `${this.backend_apiUrl}/${this.apiAction}/${id}`
@@ -3,6 +3,7 @@ import { Routes, RouterModule } from '@angular/router';
import { UserCollectionsPageComponent } from './user-collections/userCollections-page/userCollections-page.component'; import { UserCollectionsPageComponent } from './user-collections/userCollections-page/userCollections-page.component';
import { UserCollectionInfoPageComponent } from './user-collection-info/userCollection-info-page/userCollection-info-page.component'; import { UserCollectionInfoPageComponent } from './user-collection-info/userCollection-info-page/userCollection-info-page.component';
// ! /user-collections
const routes: Routes = [ const routes: Routes = [
{ {
path: '', path: '',
@@ -16,7 +16,8 @@
<!-- Movie Side Info --> <!-- Movie Side Info -->
<ul class="list-group side-info"> <ul class="list-group side-info">
<li class="list-group-item"><strong>Rating:</strong> {{tmdbRating}}/10</li> <li class="list-group-item"><strong>Rating:</strong> {{tmdbRating}}/10</li>
<li class="list-group-item"><strong>Premiere:</strong> {{this.entry.release_date | dateFormat:'MMM dd, yyyy'}}</li> <li class="list-group-item"><strong>Premiere:</strong> {{this.entry.release_date | dateFormat:'MMM dd, yyyy'}}
</li>
<li class="list-group-item" *ngIf="entry.is_tvseries"><strong>Next Episode:</strong> {{nextEpisode}}</li> <li class="list-group-item" *ngIf="entry.is_tvseries"><strong>Next Episode:</strong> {{nextEpisode}}</li>
<li class="list-group-item"><strong>Status:</strong> {{status}}</li> <li class="list-group-item"><strong>Status:</strong> {{status}}</li>
<li class="list-group-item"><strong>Genre:</strong> {{genres}}</li> <li class="list-group-item"><strong>Genre:</strong> {{genres}}</li>
@@ -102,7 +103,8 @@
<div class="d-flex flex-column gap-3"> <div class="d-flex flex-column gap-3">
<app-season-main-card <app-season-main-card
*ngFor="let season of (showAll ? entry.seasons : entry.seasons | slice:0:initialCount); let i = index" *ngFor="let season of (showAll ? entry.seasons : entry.seasons | slice:0:initialCount); let i = index"
[@fadeInOut] [season]="season" (episodeWatchedEvent)="onEpisodeWatchedEvent()"> [@fadeInOut] [season]="season" (episodeWatchedEvent)="onEpisodeWatchedEvent()"
(episodeWatchedDeletedEvent)="triggerEpisodeWatchedDeletedEvent()">
</app-season-main-card> </app-season-main-card>
</div> </div>
<!-- show all/less when entry has more that 2 seasons --> <!-- show all/less when entry has more that 2 seasons -->
@@ -122,7 +124,7 @@
<h3>Collections</h3> <h3>Collections</h3>
</div> </div>
<div class="row" *ngIf="this.entry.is_tvseries"> <div class="row" *ngIf="this.entry.is_tvseries && this.seenHistory.length != 0">
<h3>Watch History</h3> <h3>Watch History</h3>
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
@@ -131,7 +133,7 @@
<th>Episode</th> <th>Episode</th>
<th>Date Seen</th> <th>Date Seen</th>
<th>Seen With</th> <th>Seen With</th>
<!-- Add more table headers as needed --> <th>Action</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -140,6 +142,19 @@
<td>{{ item.episode_number }}</td> <td>{{ item.episode_number }}</td>
<td>{{ item.date_seen | dateFormat:'MMM dd, yyyy' }}</td> <td>{{ item.date_seen | dateFormat:'MMM dd, yyyy' }}</td>
<td>{{ item.seen_with }}</td> <td>{{ item.seen_with }}</td>
<td>
<div class="dropdown">
<button class="btn btn-sm btn-filter dropdown-toggle dropdown-toggle-nocaret" type="button"
data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-three-dots"></i>
</button>
<ul class="dropdown-menu" style="cursor: pointer;">
<li (click)="editEpisodeSeen(item)"><a class="dropdown-item">Edit</a></li>
<li (click)="deleteEpisodeSeen(item)"><a class="dropdown-item">Delete</a></li>
</ul>
</div>
</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -14,11 +14,9 @@ import { SeenModalComponent } from '../../../shared/components/modals/seen-modal
import { EntrySeenService } from '../../../core/services/entry-seen.service'; import { EntrySeenService } from '../../../core/services/entry-seen.service';
import { EntryRatingsService } from '../../../core/services/entry-ratings.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 { EntryService } from '../../../core/services/entry.service';
import { EpisodeSeenService } from '../../../core/services/episode-seen.service'; import { EpisodeSeenService } from '../../../core/services/episode-seen.service';
import e from 'express'; import { SeasonService } from '../../../core/services/season.service';
@Component({ @Component({
selector: 'app-entry-page', selector: 'app-entry-page',
@@ -58,6 +56,7 @@ export class EntryPageComponent implements OnInit {
public dialog: MatDialog, public dialog: MatDialog,
private episodeSeenService: EpisodeSeenService, private episodeSeenService: EpisodeSeenService,
private entryService: EntryService, private entryService: EntryService,
private seasonService: SeasonService,
private entrySeenService: EntrySeenService, private entrySeenService: EntrySeenService,
private entryRatingsService: EntryRatingsService, private entryRatingsService: EntryRatingsService,
private datePipe: DatePipe private datePipe: DatePipe
@@ -67,10 +66,31 @@ export class EntryPageComponent implements OnInit {
this.route.data.subscribe( this.route.data.subscribe(
(data) => { (data) => {
this.entry = data['entry'] as Entry; this.entry = data['entry'] as Entry;
if (this.entry.is_tvseries) {
// ? sorting seasons
this.entry.seasons = this.entry.seasons.sort((a, b) => this.entry.seasons = this.entry.seasons.sort((a, b) =>
a.name.localeCompare(b.name) a.name.localeCompare(b.name)
); );
console.log(this.entry);
// ? 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) { if (!this.entry) {
this.router.navigate(['/error'], { this.router.navigate(['/error'], {
queryParams: { error: 'Entry not found' }, queryParams: { error: 'Entry not found' },
@@ -106,14 +126,11 @@ export class EntryPageComponent implements OnInit {
return; return;
} }
let watchDate = result.watchDate;
let watchedWith = result.watchedWith.split('\n').join(', '); let watchedWith = result.watchedWith.split('\n').join(', ');
this.entrySeenService this.entrySeenService
.createEntrySeen( .createEntrySeen(this.entry.id.toString(), watchDate, watchedWith)
this.entry.id.toString(),
result.watchDate,
watchedWith
)
.subscribe({ .subscribe({
next: (entrySeen) => { next: (entrySeen) => {
if (entrySeen) { if (entrySeen) {
@@ -151,10 +168,6 @@ export class EntryPageComponent implements OnInit {
}); });
} }
onEpisodeWatchedEvent() {
this.getEpisodesSeenHistory();
}
removeEntrySeen(id: number) { removeEntrySeen(id: number) {
// TODO add confirm modal // TODO add confirm modal
this.entrySeenService.removeEntrySeen(id).subscribe({ 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() { getEpisodesSeenHistory() {
if (!this.entry.is_tvseries) return; if (!this.entry.is_tvseries) return;
@@ -233,21 +253,14 @@ export class EntryPageComponent implements OnInit {
this.filterEpisodesSeenHistory(); this.filterEpisodesSeenHistory();
}, },
error: (error) => { error: (error) => {
this.seenHistory = [] as EpisodeSeenDto[];
this.filterEpisodesSeenHistory();
console.log(error); console.log(error);
}, },
}); });
} }
// nextPage(): void { // ? filter episode seen history
// this.currentPage++;
// }
// previousPage(): void {
// if (this.currentPage > 1) {
// this.currentPage--;
// }
// }
filterEpisodesSeenHistory() { filterEpisodesSeenHistory() {
var temp = [] as EpisodeSeenDto[]; var temp = [] as EpisodeSeenDto[];
@@ -261,11 +274,90 @@ export class EntryPageComponent implements OnInit {
this.seenHistoryToShow = temp.slice(startIndex, endIndex); this.seenHistoryToShow = temp.slice(startIndex, endIndex);
} }
// totalPageCount(): number { editEpisodeSeen(episodeSeen: EpisodeSeenDto) {
// return this.seenHistory.length / this.pageSize; 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) { goToPage(page: number) {
this.currentPage = page; this.currentPage = page;
this.filterEpisodesSeenHistory(); this.filterEpisodesSeenHistory();
@@ -294,7 +386,7 @@ export class EntryPageComponent implements OnInit {
(_, i) => startPage + i (_, i) => startPage + i
); );
} }
// ? end pagination // + end pagination
toggleShowAllSeasons() { toggleShowAllSeasons() {
this.showAll = !this.showAll; this.showAll = !this.showAll;
@@ -88,6 +88,7 @@ export class LibraryComponent {
(_, i) => startPage + i (_, i) => startPage + i
); );
} }
// ? end pagination
// ? setter // ? setter
setEntryType(entryType: number) { setEntryType(entryType: number) {
@@ -10,6 +10,8 @@ import {
} from '@angular/animations'; } from '@angular/animations';
import { Episode } from '../../models/episode.models'; import { Episode } from '../../models/episode.models';
import { EpisodeSeenService } from '../../../core/services/episode-seen.service'; 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({ @Component({
selector: 'app-season-main-card', selector: 'app-season-main-card',
@@ -37,11 +39,11 @@ export class SeasonMainCardComponent implements OnInit {
constructor( constructor(
private seasonService: SeasonService, private seasonService: SeasonService,
private episodeSeenService: EpisodeSeenService private episodeSeenService: EpisodeSeenService,
public dialog: MatDialog
) {} ) {}
ngOnInit(): void { ngOnInit(): void {
// TODO: GET SEASON EPISODES
this.seasonService.getSeasonEpisodes(this.season.id).subscribe({ this.seasonService.getSeasonEpisodes(this.season.id).subscribe({
next: (episodes) => { next: (episodes) => {
console.log(`Loaded Season Episodes: `, episodes); console.log(`Loaded Season Episodes: `, episodes);
@@ -83,29 +85,77 @@ export class SeasonMainCardComponent implements OnInit {
return count; return count;
} }
episodeMarkSeenClick() { async episodeMarkSeenClick() {
if (this.isLocked) return; if (this.isLocked) return;
this.isLocked = true; this.isLocked = true;
// starts looping from the last available episode let selectedEpisode = {} as Episode;
for (let i = this.season.episode_count; i >= 0; i--) { 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 // ? untils it finds that the previous episode episode is marked as seen
// ? > in that case it chooses the current one to mark // ? > in that case it chooses the current one to mark
for (let i = this.season.episodes.length - 1; i >= 0; i--) {
if (i == 0 || this.season.episodes[i - 1].date_first_seen != null) { if (i == 0 || this.season.episodes[i - 1].date_first_seen != null) {
let currentEpisode = this.season.episodes[i]; selectedEpisodeIndex = i;
// todo: show episode seen modal 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 this.episodeSeenService
.createEpisodeSeen( .createEpisodeSeen(
this.season.entry_id, this.season.entry_id,
currentEpisode.id, selectedEpisode.id,
new Date(), watchDate,
'Me, My Self & I' watchedWith
) )
.subscribe({ .subscribe({
next: (episodeSeen) => { next: (episodeSeen) => {
console.log(`Episode marked as seen`, episodeSeen); console.log(`Episode marked as seen`, episodeSeen);
this.season.episodes[i].date_first_seen = new Date(); // TODO get actualy date_first_seen & date_last_seen for episode seen (not just place holders)
this.season.episodes[i].date_last_seen = new Date(); this.season.episodes[selectedEpisodeIndex].date_first_seen =
new Date();
this.season.episodes[selectedEpisodeIndex].date_last_seen =
new Date();
this.episodeWatchedEvent.emit(); this.episodeWatchedEvent.emit();
// TODO show notification // TODO show notification
}, },
@@ -117,8 +167,10 @@ export class SeasonMainCardComponent implements OnInit {
this.isLocked = false; this.isLocked = false;
}, },
}); });
break; } else {
} console.log('Seen dialog was cancelled');
this.isLocked = false;
} }
});
} }
} }
@@ -13,6 +13,7 @@ import {
transition, transition,
animate, animate,
} from '@angular/animations'; } from '@angular/animations';
import { formatDate } from '@angular/common';
@Component({ @Component({
selector: 'app-seen-modal', selector: 'app-seen-modal',
@@ -36,7 +37,7 @@ import {
]), ]),
], ],
}) })
export class SeenModalComponent { export class SeenModalComponent implements OnInit {
public watchDate: string = ''; public watchDate: string = '';
public watchedWith: string = ''; public watchedWith: string = '';
@@ -45,6 +46,15 @@ export class SeenModalComponent {
@Inject(MAT_DIALOG_DATA) public data: any @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 { onConfirm(): void {
this.dialogRef.close({ this.dialogRef.close({
watchDate: this.watchDate, watchDate: this.watchDate,