add episode seen history in entry page

This commit is contained in:
X4Lo committed 2024-04-22 17:41:30 +01:00
1 parent cf305cabae
commit dbeb0ee524
11 files changed
+288 -64

No files matched your search

+5
View File
@@ -96,6 +96,11 @@ Episode.belongsTo(Season, { foreignKey: 'season_id' });
Episode.hasMany(EpisodeSeen, { foreignKey: 'episode_id', onDelete: 'CASCADE', }); Episode.hasMany(EpisodeSeen, { foreignKey: 'episode_id', onDelete: 'CASCADE', });
EpisodeSeen.belongsTo(Episode, { foreignKey: 'episode_id' }); EpisodeSeen.belongsTo(Episode, { foreignKey: 'episode_id' });
// * ENTRY & EPISODE_SEEN - ONE TO MANY
Entry.hasMany(EpisodeSeen, { foreignKey: 'entry_id', onDelete: 'CASCADE', });
EpisodeSeen.belongsTo(Entry, { foreignKey: 'entry_id' });
// * ----
Franchise.hasMany(Entry, { foreignKey: 'franchise_id' }); Franchise.hasMany(Entry, { foreignKey: 'franchise_id' });
Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' }); Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' });
+7
View File
@@ -6,6 +6,13 @@ const EpisodeSeen = sequelize.define("episodeSeen",
{ {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
entry_id: {
type: DataTypes.INTEGER,
references: {
model: 'Entries',
key: 'id'
}
},
episode_id: { episode_id: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
references: { references: {
+31 -5
View File
@@ -1,15 +1,14 @@
const express = require('express'); const express = require('express');
const EntrySeen = require('../models/EntrySeen');
const Entry = require('../models/Entry');
const Episode = require('../models/Episode'); const Episode = require('../models/Episode');
const EpisodeSeen = require('../models/EpisodeSeen'); const EpisodeSeen = require('../models/EpisodeSeen');
const Season = require('../models/Season');
const episodeSeenRouter = express.Router(); const episodeSeenRouter = express.Router();
// ! /episode-seen // ! /episode-seen
// * POST - CREATE ENTRY SEEN // * POST - CREATE ENTRY SEEN
episodeSeenRouter.post('/', async (req, res) => { episodeSeenRouter.post('/', async (req, res) => {
try { try {
const { episode_id, date_seen, seen_with } = req.body; const { entry_id, episode_id, date_seen, seen_with } = req.body;
// Fetch the Entry based on entry_id // Fetch the Entry based on entry_id
const episode = await Episode.findByPk(episode_id); const episode = await Episode.findByPk(episode_id);
@@ -47,7 +46,7 @@ episodeSeenRouter.post('/', async (req, res) => {
} }
// Create a new EpisodeSeen record // Create a new EpisodeSeen record
const newEpisodeSeen = await EntrySeen.create({ episode_id: episode_id, date_seen, seen_with }); const newEpisodeSeen = await EpisodeSeen.create({ entry_id, episode_id, date_seen, seen_with });
res.status(201).json(newEpisodeSeen); res.status(201).json(newEpisodeSeen);
} catch (error) { } catch (error) {
res.status(400).json({ error: error.message }); res.status(400).json({ error: error.message });
@@ -80,7 +79,7 @@ episodeSeenRouter.get('/:id', async (req, res) => {
} }
}); });
// * GET - EPISODE SEEN BY ENTRY ID // * GET - EPISODE SEEN BY EPISODE ID
episodeSeenRouter.get('/by-episode/:episodeId', async (req, res) => { episodeSeenRouter.get('/by-episode/:episodeId', async (req, res) => {
try { try {
const { episodeId } = req.params; const { episodeId } = req.params;
@@ -99,6 +98,33 @@ episodeSeenRouter.get('/by-episode/:episodeId', async (req, res) => {
} }
}); });
// * GET - EPISODE SEEN BY ENTRY ID
episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => {
try {
const { entryId } = req.params;
const episodeSeens = await EpisodeSeen.findAll({
where: { entry_id: entryId },
include: [{
model: Episode,
include: [{
model: Season,
attributes: ['season_number'],
}],
attributes: ['episode_number'],
}],
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.' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// * PUT - UPDATE EPISODE SEEN // * PUT - UPDATE EPISODE SEEN
episodeSeenRouter.put('/:id', async (req, res) => { episodeSeenRouter.put('/:id', async (req, res) => {
try { try {
@@ -11,17 +11,28 @@ export class EpisodeSeenService {
constructor(private http: HttpClient) {} constructor(private http: HttpClient) {}
createEpisodeSeen(episodeId: number, dateSeen: Date, seenWith: string) { createEpisodeSeen(
entryId: number,
episodeId: number,
dateSeen: Date,
seenWith: string
) {
return this.http.post<EpisodeSeen>( return this.http.post<EpisodeSeen>(
`${this.backend_apiUrl}/${this.apiAction}`, `${this.backend_apiUrl}/${this.apiAction}`,
{ {
entry_id: entryId,
episode_id: episodeId, episode_id: episodeId,
date_seen: dateSeen, date_seen: dateSeen,
seen_with: seenWith, seen_with: seenWith,
} }
); );
} }
getEpisodeSeenByEntryId(entryId: number) {
return this.http.get<any[]>(
`${this.backend_apiUrl}/${this.apiAction}/by-entry/${entryId}`
);
}
// get episode-seen by episode Id // get episode-seen by episode Id
getEpisodeSeenById(id: number) { getEpisodeSeenById(id: number) {
@@ -67,7 +67,7 @@
<!-- Interraction buttons --> <!-- Interraction buttons -->
<div class="row"> <div class="row">
<button class="btn btn-icon-only-success wh-48" *ngIf="!entry.is_tvseries" (click)="openDialog()"> <button class="btn btn-icon-only-success wh-48" *ngIf="!entry.is_tvseries" (click)="openEntrySeenModal()">
<span class="material-symbols-outlined"> <span class="material-symbols-outlined">
visibility visibility
</span> </span>
@@ -102,7 +102,7 @@
<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"> [@fadeInOut] [season]="season" (episodeWatchedEvent)="onEpisodeWatchedEvent()">
</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 -->
@@ -121,6 +121,49 @@
<div class="row"> <div class="row">
<h3>Collections</h3> <h3>Collections</h3>
</div> </div>
<div class="row" *ngIf="this.entry.is_tvseries">
<h3>Watch History</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Season</th>
<th>Episode</th>
<th>Date Seen</th>
<th>Seen With</th>
<!-- Add more table headers as needed -->
</tr>
</thead>
<tbody>
<tr *ngFor="let item of seenHistoryToShow; let i = index">
<td>{{ item.season_number == 0 ? 'Special' : 'Season '+ item.season_number }}</td>
<td>{{ item.episode_number }}</td>
<td>{{ item.date_seen | dateFormat:'MMM dd, yyyy' }}</td>
<td>{{ item.seen_with }}</td>
</tr>
</tbody>
</table>
<div class="pagination-container d-flex justify-content-end" *ngIf="maxPage > 1">
<ul class="pagination pagination-sm">
<li class="page-item" [class.disabled]="currentPage === 1">
<a class="page-link" href="javascript:;" (click)="goToPage(currentPage - 1)">Previous</a>
</li>
<!-- Dynamically generate page numbers -->
<li class="page-item" *ngFor="let page of pageNumbers" [class.active]="currentPage === page">
<a class="page-link" href="javascript:;" (click)="goToPage(page)">{{ page }}</a>
</li>
<li class="page-item" [class.disabled]="currentPage == maxPage">
<a class="page-link" href="javascript:;" (click)="goToPage(currentPage + 1)">Next</a>
</li>
</ul>
</div>
<!--
<div>
<button (click)="previousPage()" [disabled]="currentPage === 1">Previous</button>
<button (click)="nextPage()" [disabled]="currentPage === totalPageCount()">Next</button>
</div> -->
</div>
</div> </div>
@@ -1,10 +1,11 @@
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations'; import { trigger, style, transition, animate } from '@angular/animations';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { Entry } from '../../../shared/models/entry.model'; import { Entry } from '../../../shared/models/entry.model';
import { EpisodeSeenDto } from '../../../shared/models/dtos/episode-seen.dto';
import { DatePipe } from '@angular/common'; import { DatePipe } from '@angular/common';
@@ -16,6 +17,8 @@ import { EntryRatingsService } from '../../../core/services/entry-ratings.servic
import { TmdbService } from '../../../core/services/tmdb.service'; import { TmdbService } from '../../../core/services/tmdb.service';
import { LibraryService } from '../../../core/services/library.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 e from 'express';
@Component({ @Component({
selector: 'app-entry-page', selector: 'app-entry-page',
@@ -24,14 +27,16 @@ import { EntryService } from '../../../core/services/entry.service';
encapsulation: ViewEncapsulation.None, encapsulation: ViewEncapsulation.None,
animations: [ animations: [
trigger('fadeInOut', [ trigger('fadeInOut', [
transition(':enter', [ // void => * transition(':enter', [
// void => *
style({ opacity: 0 }), style({ opacity: 0 }),
animate('0.5s ease-in', style({ opacity: 1 })) animate('0.5s ease-in', style({ opacity: 1 })),
]), ]),
transition(':leave', [ // * => void transition(':leave', [
animate('0.5s ease-out', style({ opacity: 0 })) // * => void
]) animate('0.5s ease-out', style({ opacity: 0 })),
]) ]),
]),
], ],
}) })
export class EntryPageComponent implements OnInit { export class EntryPageComponent implements OnInit {
@@ -39,12 +44,19 @@ export class EntryPageComponent implements OnInit {
public showAll = false; public showAll = false;
public initialCount = 2; public initialCount = 2;
seenHistory: any[] = [];
seenHistoryToShow: any[] = [];
itemsCount: number = 0;
maxPage: number = 10;
currentPage: number = 1;
pageSize: number = 10;
constructor( constructor(
private route: ActivatedRoute, private route: ActivatedRoute,
private router: Router, private router: Router,
public dialog: MatDialog, public dialog: MatDialog,
private tmdbService: TmdbService, private episodeSeenService: EpisodeSeenService,
private libraryService: LibraryService,
private entryService: EntryService, private entryService: EntryService,
private entrySeenService: EntrySeenService, private entrySeenService: EntrySeenService,
private entryRatingsService: EntryRatingsService, private entryRatingsService: EntryRatingsService,
@@ -55,7 +67,9 @@ 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;
this.entry.seasons = this.entry.seasons.sort((a, b) => a.name.localeCompare(b.name)); this.entry.seasons = this.entry.seasons.sort((a, b) =>
a.name.localeCompare(b.name)
);
console.log(this.entry); console.log(this.entry);
if (!this.entry) { if (!this.entry) {
this.router.navigate(['/error'], { this.router.navigate(['/error'], {
@@ -70,9 +84,11 @@ export class EntryPageComponent implements OnInit {
}); });
} }
); );
this.getEpisodesSeenHistory();
} }
openDialog() { openEntrySeenModal() {
if (!this.entry) return; if (!this.entry) return;
const dialogRef = this.dialog.open(SeenModalComponent, { const dialogRef = this.dialog.open(SeenModalComponent, {
@@ -135,6 +151,10 @@ 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({
@@ -180,6 +200,102 @@ export class EntryPageComponent implements OnInit {
}); });
} }
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) => {
console.log(error);
},
});
}
// nextPage(): void {
// this.currentPage++;
// }
// previousPage(): void {
// if (this.currentPage > 1) {
// this.currentPage--;
// }
// }
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);
}
// totalPageCount(): number {
// return this.seenHistory.length / this.pageSize;
// }
// ? 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() { toggleShowAllSeasons() {
this.showAll = !this.showAll; this.showAll = !this.showAll;
} }
@@ -6,7 +6,7 @@
<h6 class="mb-0 list-title">{{season.name}}</h6> <h6 class="mb-0 list-title">{{season.name}}</h6>
<p class="mb-0">{{season.air_date | dateFormat:'yyyy'}}</p> <p class="mb-0">{{season.air_date | dateFormat:'yyyy'}}</p>
<div class="d-flex align-items-center justify-content-between mb-4 mt-3"> <div class="d-flex align-items-center justify-content-between mb-4 mt-3" style="height: 40px;">
<div class="progress" style="height: 7px; width: 90%;"> <!-- Adjust width as needed --> <div class="progress" style="height: 7px; width: 90%;"> <!-- Adjust width as needed -->
<div class="progress-bar" role="progressbar" [style]="'width:'+ episodesWatchedPercentage + '%'" <div class="progress-bar" role="progressbar" [style]="'width:'+ episodesWatchedPercentage + '%'"
[attr.aria-valuenow]="episodesWatchedPercentage" aria-valuemin="0" aria-valuemax="100"></div> [attr.aria-valuenow]="episodesWatchedPercentage" aria-valuemin="0" aria-valuemax="100"></div>
@@ -14,10 +14,15 @@
<div style="margin-right: 5px;"> <div style="margin-right: 5px;">
{{episodesWatchedCount}}/{{this.season.episode_count}} {{episodesWatchedCount}}/{{this.season.episode_count}}
</div> </div>
<div class="form-check" style="margin-right: 5px;" *ngIf="episodesWatchedCount < this.season.episode_count"> <button *ngIf="episodesWatchedCount < this.season.episode_count" type="button"
class="btn btn-outline-primary rounded-pill d-flex justify-content-center align-items-center"
style="height: 30px; width: 40px; margin-right: 5px;" (click)="episodeMarkSeenClick()">
<span class="material-symbols-outlined">check</span>
</button>
<!-- <div class="form-check" style="margin-right: 5px;" *ngIf="episodesWatchedCount < this.season.episode_count">
<input class="form-check-input" type="checkbox" style="height: 20px; width: 20px;" [checked]="isChecked" <input class="form-check-input" type="checkbox" style="height: 20px; width: 20px;" [checked]="isChecked"
(change)="handleCheckChange()"> (change)="handleCheckChange()">
</div> </div> -->
</div> </div>
<!-- <p class="mb-0 overview">{{season.overview}}</p> --> <!-- <p class="mb-0 overview">{{season.overview}}</p> -->
</div> </div>
@@ -1,4 +1,4 @@
import { Component, Input, OnInit } from '@angular/core'; import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Season } from '../../models/season.model'; import { Season } from '../../models/season.model';
import { SeasonService } from '../../../core/services/season.service'; import { SeasonService } from '../../../core/services/season.service';
import { import {
@@ -30,6 +30,7 @@ import { EpisodeSeenService } from '../../../core/services/episode-seen.service'
], ],
}) })
export class SeasonMainCardComponent implements OnInit { export class SeasonMainCardComponent implements OnInit {
@Output() episodeWatchedEvent = new EventEmitter();
@Input() season: Season = {} as Season; @Input() season: Season = {} as Season;
isChecked: boolean = false; isChecked: boolean = false;
isLocked: boolean = false; isLocked: boolean = false;
@@ -43,7 +44,7 @@ export class SeasonMainCardComponent implements OnInit {
// TODO: GET SEASON EPISODES // TODO: GET SEASON EPISODES
this.seasonService.getSeasonEpisodes(this.season.id).subscribe({ this.seasonService.getSeasonEpisodes(this.season.id).subscribe({
next: (episodes) => { next: (episodes) => {
console.log(episodes); console.log(`Loaded Season Episodes: `, episodes);
this.season.episodes = episodes; this.season.episodes = episodes;
}, },
error: (error) => { error: (error) => {
@@ -82,48 +83,42 @@ export class SeasonMainCardComponent implements OnInit {
return count; return count;
} }
handleCheckChange() { episodeMarkSeenClick() {
this.isChecked = true;
if (this.isLocked) return; if (this.isLocked) return;
this.isLocked = true; this.isLocked = true;
if (this.isChecked) { // starts looping from the last available episode
for (let i = this.season.episode_count; i > 0; i--) { for (let i = this.season.episode_count; i >= 0; i--) {
if (this.season.episodes[i - 1].date_first_seen != null) { // ? untils it finds that the previous episode episode is marked as seen
let currentEpisode = this.season.episodes[i]; // ? > in that case it chooses the current one to mark
this.episodeSeenService if (i == 0 || this.season.episodes[i - 1].date_first_seen != null) {
.createEpisodeSeen(currentEpisode.id, new Date(), 'Me, My Self & I') let currentEpisode = this.season.episodes[i];
.subscribe({ // todo: show episode seen modal
next: (episodeSeen) => { this.episodeSeenService
console.log(`Episode marked as seen`, episodeSeen); .createEpisodeSeen(
this.season.episodes[i].date_first_seen = new Date(); this.season.entry_id,
this.season.episodes[i].date_last_seen = new Date(); currentEpisode.id,
// TODO show notification new Date(),
this.isChecked = false; 'Me, My Self & I'
this.isLocked = false; )
}, .subscribe({
error: (error) => { next: (episodeSeen) => {
console.log(`Couldn't mark episode as seen:`, error); console.log(`Episode marked as seen`, episodeSeen);
// TODO show notification this.season.episodes[i].date_first_seen = new Date();
this.isChecked = false; this.season.episodes[i].date_last_seen = new Date();
this.isLocked = false; this.episodeWatchedEvent.emit();
}, // TODO show notification
}); },
break; error: (error) => {
} console.log(`Couldn't mark episode as seen:`, error);
// TODO show notification
},
complete: () => {
this.isLocked = false;
},
});
break;
} }
// console.log('checking');
// this.executeFunction()
// .then(() => {
// this.isChecked = false;
// console.log('unchecking');
// })
// .catch((error) => {
// console.error('Failed to execute function:', error);
// this.isChecked = false;
// });
} }
} }
} }
@@ -0,0 +1,15 @@
export interface EpisodeSeenDto {
id: number;
entryId: number;
episodeId: number;
season_number: number;
episode_number: number;
date_seen: Date;
seen_with: string;
createdAt: Date;
updatedAt: Date;
}
@@ -1,6 +1,7 @@
export interface EpisodeSeen { export interface EpisodeSeen {
id: number; id: number;
entry_id: number;
episode_id: number; episode_id: number;
date_seen: Date; date_seen: Date;
@@ -8,7 +8,7 @@ export interface Season {
tmdb_id: string; tmdb_id: string;
imdb_id: string; imdb_id: string;
entry_id: string; entry_id: number;
name: string; name: string;
overview: string; overview: string;