added my lists page

This commit is contained in:
2025-12-06 14:28:40 +01:00
parent 9832384627
commit e5ec8aa7e5
21 changed files with 2400 additions and 44 deletions

View File

@@ -0,0 +1,112 @@
// list.controller.ts
import { FastifyReply, FastifyRequest } from 'fastify';
import * as listService from './list.service';
// Tipos de solicitud asumidos:
// - UserRequest: Request con el objeto 'user' adjunto por el hook de autenticación.
interface UserRequest extends FastifyRequest {
user?: { id: number };
}
interface UpsertEntryBody {
entry_type: any;
entry_id: number;
external_id?: string | null;
source: string;
status: string;
progress: number;
score: number;
}
interface DeleteEntryParams {
entryId: string;
}
/**
* GET /list
* Obtiene toda la lista del usuario autenticado.
*/
export async function getList(req: UserRequest, reply: FastifyReply) {
const userId = req.user?.id;
if (!userId) {
return reply.code(401).send({ error: "Unauthorized" });
}
try {
const results = await listService.getUserList(userId);
return { results };
} catch (err) {
console.error(err);
return reply.code(500).send({ error: "Failed to retrieve list" });
}
}
/**
* POST /list/entry
* Crea o actualiza una entrada de lista (upsert).
*/
export async function upsertEntry(req: UserRequest, reply: FastifyReply) {
const userId = req.user?.id;
const body = req.body as UpsertEntryBody;
if (!userId) {
return reply.code(401).send({ error: "Unauthorized" });
}
// <--- NUEVO: Validación de entry_type
if (!body.entry_id || !body.source || !body.status || !body.entry_type) {
return reply.code(400).send({ error: "Missing required fields (entry_id, source, status, entry_type)." });
}
try {
const entryData = {
user_id: userId,
entry_id: body.entry_id,
external_id: body.external_id,
source: body.source,
entry_type: body.entry_type, // <--- NUEVO: Pasar entry_type
status: body.status,
progress: body.progress || 0,
score: body.score || null
};
const result = await listService.upsertListEntry(entryData);
return { success: true, changes: result.changes };
} catch (err) {
console.error(err);
return reply.code(500).send({ error: "Failed to save list entry" });
}
}
/**
* DELETE /list/entry/:entryId
* Elimina una entrada de lista.
*/
export async function deleteEntry(req: UserRequest, reply: FastifyReply) {
const userId = req.user?.id;
const { entryId } = req.params as DeleteEntryParams;
if (!userId) {
return reply.code(401).send({ error: "Unauthorized" });
}
const numericEntryId = parseInt(entryId, 10);
if (isNaN(numericEntryId)) {
return reply.code(400).send({ error: "Invalid entry ID." });
}
try {
const result = await listService.deleteListEntry(userId, numericEntryId);
if (result.success) {
return { success: true, message: "Entry deleted successfully." };
} else {
return reply.code(404).send({ error: "Entry not found or unauthorized to delete." });
}
} catch (err) {
console.error(err);
return reply.code(500).send({ error: "Failed to delete list entry" });
}
}

View File

@@ -0,0 +1,10 @@
import { FastifyInstance } from 'fastify';
import * as controller from './list.controller';
async function listRoutes(fastify: FastifyInstance) {
fastify.get('/list', controller.getList);
fastify.post('/list/entry', controller.upsertEntry);
fastify.delete('/list/entry/:entryId', controller.deleteEntry);
}
export default listRoutes;

View File

@@ -0,0 +1,183 @@
// list.service.ts (Actualizado)
import {queryAll, run} from '../../shared/database';
import {getExtension} from '../../shared/extensions';
import * as animeService from '../anime/anime.service';
import * as booksService from '../books/books.service';
// Define la interfaz de entrada de lista (sin external_id)
interface ListEntryData {
entry_type: any;
user_id: number;
entry_id: number; // ID de contenido de la fuente (AniList, MAL, o local)
source: string; // 'anilist', 'local', etc.
status: string; // 'COMPLETED', 'WATCHING', etc.
progress: number;
score: number | null;
}
const USER_DB = 'userdata';
/**
* Inserta o actualiza una entrada de lista.
* Utiliza ON CONFLICT(user_id, entry_id) para el upsert.
*/
export async function upsertListEntry(entry: any) {
const {
user_id,
entry_id,
source,
entry_type,
status,
progress,
score
} = entry;
const sql = `
INSERT INTO ListEntry
(user_id, entry_id, source, entry_type, status, progress, score, updated_at)
VALUES
(?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(user_id, entry_id) DO UPDATE SET
source = EXCLUDED.source,
entry_type = EXCLUDED.entry_type,
status = EXCLUDED.status,
progress = EXCLUDED.progress,
score = EXCLUDED.score,
updated_at = CURRENT_TIMESTAMP;
`;
const params = [
user_id,
entry_id,
source,
entry_type,
status,
progress,
score || null
];
try {
const result = await run(sql, params, USER_DB);
return { changes: result.changes, lastID: result.lastID };
} catch (error) {
console.error("Error al guardar la entrada de lista:", error);
throw new Error("Error en la base de datos al guardar la entrada.");
}
}
/**
* Recupera la lista completa de un usuario.
*/
export async function getUserList(userId: number): Promise<any> {
const sql = `
SELECT * FROM ListEntry
WHERE user_id = ?
ORDER BY updated_at DESC;
`;
try {
// 1. Obtener la lista base de la DB
const dbList = await queryAll(sql, [userId], USER_DB) as ListEntryData[];
// 2. Crear un array de promesas para obtener los detalles de cada entrada concurrentemente
const enrichedListPromises = dbList.map(async (entry) => {
let contentDetails: any | null = null;
const id = entry.entry_id;
const source = entry.source;
const type = entry.entry_type;
try {
if (type === 'ANIME') {
// Lógica para ANIME
let anime: any;
if (source === 'anilist') {
anime = await animeService.getAnimeById(id);
} else {
const ext = getExtension(source);
// Asegurar que id sea una cadena para getAnimeInfoExtension si el id es un número
anime = await animeService.getAnimeInfoExtension(ext, id.toString());
}
contentDetails = {
title: anime?.title || 'Unknown Anime Title',
poster: anime?.coverImage?.extraLarge || anime?.image || '',
total_episodes: anime?.episodes || anime?.nextAiringEpisode?.episode - 1 || 0,
};
} else if (type === 'MANGA' || type === 'NOVEL') {
// Lógica para MANGA, NOVEL y otros "books"
let book: any;
if (source === 'anilist') {
book = await booksService.getBookById(id);
} else {
const ext = getExtension(source);
// Asegurar que id sea una cadena
const result = await booksService.getBookInfoExtension(ext, id.toString());
book = result || null;
}
contentDetails = {
title: book?.title || 'Unknown Book Title',
poster: book?.coverImage?.extraLarge || book?.image || '',
// Priorizar chapters, luego volumes * 10, sino 0
total_chapters: book?.chapters || book?.volumes * 10 || 0,
};
}
} catch (contentError) {
console.error(`Error fetching details for entry ${id} (${source}):`, contentError);
contentDetails = {
title: 'Error Loading Details',
poster: '/public/assets/placeholder.png',
};
}
// 3. Estandarizar y Combinar los datos.
let finalTitle = contentDetails?.title || 'Unknown Title';
let finalPoster = contentDetails?.poster || '/public/assets/placeholder.png';
// Aplanamiento del título (Necesario para Anilist que devuelve un objeto)
if (typeof finalTitle === 'object' && finalTitle !== null) {
// Priorizar userPreferred, luego english, luego romaji, sino 'Unknown Title'
finalTitle = finalTitle.userPreferred || finalTitle.english || finalTitle.romaji || 'Unknown Title';
}
// Retornar el objeto combinado y estandarizado
return {
...entry,
// Datos estandarizados para el frontend:
title: finalTitle,
poster: finalPoster,
total_episodes: contentDetails?.total_episodes, // Será undefined si es Manga/Novel
total_chapters: contentDetails?.total_chapters, // Será undefined si es Anime
};
});
// 4. Ejecutar todas las promesas y esperar el resultado
return await Promise.all(enrichedListPromises);
} catch (error) {
console.error("Error al obtener la lista del usuario:", error);
throw new Error("Error en la base de datos al obtener la lista.");
}
}
/**
* Elimina una entrada de lista por user_id y entry_id.
*/
export async function deleteListEntry(userId: number, entryId: number) {
const sql = `
DELETE FROM ListEntry
WHERE user_id = ? AND entry_id = ?;
`;
try {
const result = await run(sql, [userId, entryId], USER_DB);
return { success: result.changes > 0, changes: result.changes };
} catch (error) {
console.error("Error al eliminar la entrada de lista:", error);
throw new Error("Error en la base de datos al eliminar la entrada.");
}
}

View File

@@ -64,6 +64,12 @@ export async function deleteUser(userId: number): Promise<any> {
USER_DB_NAME
);
await run(
`DELETE FROM favorites WHERE user_id = ?`,
[userId],
'favorites'
);
const result = await run(
`DELETE FROM User WHERE id = ?`,
[userId],
@@ -73,6 +79,7 @@ export async function deleteUser(userId: number): Promise<any> {
return result;
}
export async function getAllUsers(): Promise<User[]> {
const sql = 'SELECT id, username, profile_picture_url FROM User ORDER BY id';

View File

@@ -1,16 +1,196 @@
const animeId = window.location.pathname.split('/').pop();
let player;
let totalEpisodes = 0;
let currentPage = 1;
const itemsPerPage = 12;
let extensionName;
let currentAnimeData = null;
let isInList = false;
let currentListEntry = null;
const API_BASE = '/api';
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
let extensionName;
// Auth helpers
function getAuthToken() {
return localStorage.getItem('token');
}
function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
// Check if anime is in list
async function checkIfInList() {
try {
const response = await fetch(`${API_BASE}/list`, {
headers: getAuthHeaders()
});
if (response.ok) {
const data = await response.json();
const entry = data.results?.find(item =>
item.entry_id === parseInt(animeId) &&
item.source === (extensionName || 'anilist')
);
if (entry) {
isInList = true;
currentListEntry = entry;
updateAddToListButton();
}
}
} catch (error) {
console.error('Error checking list:', error);
}
}
// Update button state
function updateAddToListButton() {
const btn = document.getElementById('add-to-list-btn');
if (isInList) {
btn.innerHTML = `
<svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
In Your List
`;
btn.style.background = 'rgba(34, 197, 94, 0.2)';
btn.style.color = '#22c55e';
btn.style.borderColor = 'rgba(34, 197, 94, 0.3)';
} else {
btn.innerHTML = '+ Add to List';
}
}
// Open add to list modal
function openAddToListModal() {
if (isInList) {
// If already in list, open edit modal with current data
document.getElementById('modal-status').value = currentListEntry.status || 'PLANNING';
document.getElementById('modal-progress').value = currentListEntry.progress || 0;
document.getElementById('modal-score').value = currentListEntry.score || '';
document.getElementById('modal-title').textContent = 'Edit List Entry';
document.getElementById('modal-delete-btn').style.display = 'block';
} else {
// New entry defaults
document.getElementById('modal-status').value = 'PLANNING';
document.getElementById('modal-progress').value = 0;
document.getElementById('modal-score').value = '';
document.getElementById('modal-title').textContent = 'Add to List';
document.getElementById('modal-delete-btn').style.display = 'none';
}
document.getElementById('modal-progress').max = totalEpisodes || 999;
document.getElementById('add-list-modal').classList.add('active');}
// Close modal
function closeAddToListModal() {
document.getElementById('add-list-modal').classList.remove('active');
}
// Save to list
async function saveToList() {
const status = document.getElementById('modal-status').value;
const progress = parseInt(document.getElementById('modal-progress').value) || 0;
const score = parseFloat(document.getElementById('modal-score').value) || null;
try {
const response = await fetch(`${API_BASE}/list/entry`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
entry_id: animeId,
source: extensionName || 'anilist',
entry_type: 'ANIME',
status: status,
progress: progress,
score: score
})
});
if (!response.ok) {
throw new Error('Failed to save entry');
}
// Si la operación fue exitosa, actualizamos currentListEntry con el nuevo campo type
isInList = true;
currentListEntry = {
entry_id: parseInt(animeId),
source: extensionName || 'anilist',
entry_type: 'ANIME', // <--- También se actualiza aquí
status,
progress,
score
};
updateAddToListButton();
closeAddToListModal();
showNotification(isInList ? 'Updated successfully!' : 'Added to your list!', 'success');
} catch (error) {
console.error('Error saving to list:', error);
showNotification('Failed to save. Please try again.', 'error');
}
}
// Delete from list
async function deleteFromList() {
if (!confirm('Remove this anime from your list?')) return;
try {
const response = await fetch(`${API_BASE}/list/entry/${animeId}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to delete entry');
}
isInList = false;
currentListEntry = null;
updateAddToListButton();
closeAddToListModal();
showNotification('Removed from your list', 'success');
} catch (error) {
console.error('Error deleting from list:', error);
showNotification('Failed to remove. Please try again.', 'error');
}
}
// Show notification
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#8b5cf6'};
color: white;
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
z-index: 9999;
font-weight: 600;
animation: slideInRight 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
async function loadAnime() {
try {
@@ -36,6 +216,8 @@ async function loadAnime() {
return;
}
currentAnimeData = data;
const title = data.title?.english || data.title?.romaji || data.title || "Unknown Title";
document.title = `${title} | WaifuBoard`;
document.getElementById('title').innerText = title;
@@ -44,7 +226,6 @@ async function loadAnime() {
if (extensionName) {
posterUrl = data.image || '';
} else {
posterUrl = data.coverImage?.extraLarge || '';
}
@@ -181,6 +362,9 @@ async function loadAnime() {
renderEpisodes();
// Check if in list after loading anime data
await checkIfInList();
} catch (err) {
console.error('Error loading anime:', err);
document.getElementById('title').innerText = "Error loading anime";
@@ -274,4 +458,30 @@ searchInput.addEventListener('input', (e) => {
}
});
// Close modal on outside click
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('add-list-modal');
if (modal) {
modal.addEventListener('click', (e) => {
if (e.target.id === 'add-list-modal') {
closeAddToListModal();
}
});
}
});
// Add animations
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from { transform: translateX(400px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOutRight {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(400px); opacity: 0; }
}
`;
document.head.appendChild(style);
loadAnime();

View File

@@ -6,6 +6,13 @@ const itemsPerPage = 12;
let extensionName = null;
let bookSlug = null;
// NUEVAS VARIABLES GLOBALES PARA LISTA
let currentBookData = null;
let isInList = false;
let currentListEntry = null;
const API_BASE = '/api';
function getBookUrl(id, source = 'anilist') {
return `/api/book/${id}?source=${source}`;
}
@@ -14,6 +21,222 @@ function getChaptersUrl(id, source = 'anilist') {
return `/api/book/${id}/chapters?source=${source}`;
}
// ==========================================================
// 1. FUNCIONES DE AUTENTICACIÓN Y LISTA
// ==========================================================
// Auth helpers
function getAuthToken() {
return localStorage.getItem('token');
}
function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
// Check if book is in list
async function checkIfInList() {
try {
const response = await fetch(`${API_BASE}/list`, {
headers: getAuthHeaders()
});
if (response.ok) {
const data = await response.json();
const idToSearch = extensionName ? bookSlug : bookId;
const entry = data.results?.find(item =>
item.entry_id === idToSearch &&
item.source === (extensionName || 'anilist')
);
if (entry) {
isInList = true;
currentListEntry = entry;
updateAddToListButton();
}
}
} catch (error) {
console.error('Error checking list:', error);
}
}
// Update button state
function updateAddToListButton() {
const btn = document.getElementById('add-to-list-btn');
if (!btn) return;
if (isInList) {
btn.innerHTML = `
<svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
In Your Library
`;
btn.style.background = 'rgba(34, 197, 94, 0.2)';
btn.style.color = '#22c55e';
btn.style.borderColor = 'rgba(34, 197, 94, 0.3)';
btn.onclick = openAddToListModal;
} else {
btn.innerHTML = '+ Add to Library';
btn.style.background = null; // Restablecer estilos si no está en lista
btn.style.color = null;
btn.style.borderColor = null;
btn.onclick = openAddToListModal;
}
}
// Open add to list modal
function openAddToListModal() {
if (!currentBookData) return;
// Obtener el total de capítulos/volúmenes
const totalUnits = currentBookData.chapters || currentBookData.volumes || 999;
if (isInList) {
// If already in list, open edit modal with current data
document.getElementById('modal-status').value = currentListEntry.status || 'PLANNING';
document.getElementById('modal-progress').value = currentListEntry.progress || 0;
document.getElementById('modal-score').value = currentListEntry.score || '';
document.getElementById('modal-title').textContent = 'Edit Library Entry';
document.getElementById('modal-delete-btn').style.display = 'block';
} else {
// New entry defaults
document.getElementById('modal-status').value = 'PLANNING';
document.getElementById('modal-progress').value = 0;
document.getElementById('modal-score').value = '';
document.getElementById('modal-title').textContent = 'Add to Library';
document.getElementById('modal-delete-btn').style.display = 'none';
}
// Ajustar etiqueta de progreso según el formato
const progressLabel = document.getElementById('modal-progress-label');
if (progressLabel) {
const format = currentBookData.format?.toUpperCase() || 'MANGA';
if (format === 'MANGA' || format === 'ONE_SHOT' || format === 'MANHWA') {
progressLabel.textContent = 'Chapters Read';
} else {
progressLabel.textContent = 'Volumes/Parts Read';
}
}
document.getElementById('modal-progress').max = totalUnits;
document.getElementById('add-list-modal').classList.add('active');
}
// Close modal
function closeAddToListModal() {
document.getElementById('add-list-modal').classList.remove('active');
}
// Save to list
async function saveToList() {
const status = document.getElementById('modal-status').value;
const progress = parseInt(document.getElementById('modal-progress').value) || 0;
const score = parseFloat(document.getElementById('modal-score').value) || null;
if (!currentBookData) {
showNotification('Cannot save: Book data not loaded.', 'error');
return;
}
// Determinar el tipo de entrada (MANGA o NOVEL basado en el formato)
const format = currentBookData.format?.toUpperCase() || 'MANGA';
const entryType = (format === 'MANGA' || format === 'ONE_SHOT' || format === 'MANHWA') ? 'MANGA' : 'NOVEL';
const idToSave = extensionName ? bookSlug : bookId;
try {
const response = await fetch(`${API_BASE}/list/entry`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
entry_id: idToSave,
source: extensionName || 'anilist',
entry_type: entryType,
status: status,
progress: progress,
score: score
})
});
if (!response.ok) {
throw new Error('Failed to save entry');
}
isInList = true;
currentListEntry = { entry_id: idToSave, source: extensionName || 'anilist', entry_type: entryType, status, progress, score };
updateAddToListButton();
closeAddToListModal();
showNotification(isInList ? 'Updated successfully!' : 'Added to your library!', 'success');
} catch (error) {
console.error('Error saving to list:', error);
showNotification('Failed to save. Please try again.', 'error');
}
}
// Delete from list
async function deleteFromList() {
if (!confirm('Remove this book from your library?')) return;
const idToDelete = extensionName ? bookSlug : bookId;
try {
const response = await fetch(`${API_BASE}/list/entry/${idToDelete}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to delete entry');
}
isInList = false;
currentListEntry = null;
updateAddToListButton();
closeAddToListModal();
showNotification('Removed from your library', 'success');
} catch (error) {
console.error('Error deleting from list:', error);
showNotification('Failed to remove. Please try again.', 'error');
}
}
// Show notification
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#8b5cf6'};
color: white;
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
z-index: 9999;
font-weight: 600;
animation: slideInRight 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// ==========================================================
// 2. FUNCIÓN PRINCIPAL DE CARGA (init)
// ==========================================================
async function init() {
try {
const path = window.location.pathname;
@@ -46,6 +269,8 @@ async function init() {
return;
}
currentBookData = data; // <--- GUARDAR DATOS GLOBALES
let title, description, score, year, status, format, chapters, poster, banner, genres;
if (extensionName) {
@@ -125,11 +350,18 @@ async function init() {
loadChapters(idForFetch);
await checkIfInList(); // <--- COMPROBAR ESTADO DE LA LISTA
} catch (err) {
console.error("Metadata Error:", err);
}
}
// ==========================================================
// 3. FUNCIONES DE CARGA Y RENDERIZADO DE CAPÍTULOS
// (Sin cambios, pero se incluyen para completar el script)
// ==========================================================
async function loadChapters(idForFetch) {
const tbody = document.getElementById('chapters-body');
if (!tbody) return;
@@ -291,4 +523,34 @@ function openReader(bookId, chapterId, provider) {
window.location.href = `/read/${p}/${c}/${bookId}${extension}`;
}
// ==========================================================
// 4. LISTENERS Y ARRANQUE
// ==========================================================
// Close modal on outside click
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('add-list-modal');
if (modal) {
modal.addEventListener('click', (e) => {
if (e.target.id === 'add-list-modal') {
closeAddToListModal();
}
});
}
});
// Add animations (Copied from anime.js)
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from { transform: translateX(400px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOutRight {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(400px); opacity: 0; }
}
`;
document.head.appendChild(style);
init();

428
src/scripts/list.js Normal file
View File

@@ -0,0 +1,428 @@
// API Configuration
const API_BASE = '/api';
let currentList = [];
let filteredList = [];
let currentEditingEntry = null;
// Get token from localStorage
function getAuthToken() {
return localStorage.getItem('token');
}
// Create headers with auth token
function getAuthHeaders() {
const token = getAuthToken();
return {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
}
// Initialize on page load
document.addEventListener('DOMContentLoaded', async () => {
await loadList();
setupEventListeners();
});
// ==========================================================
// FUNCIÓN: Poblar Filtro de Fuente (NUEVA LÓGICA)
// ==========================================================
async function populateSourceFilter() {
const select = document.getElementById('source-filter');
if (!select) return;
// Opciones base
select.innerHTML = `
<option value="all">All Sources</option>
<option value="anilist">AniList</option>
<option value="local">Local</option>
`;
try {
const response = await fetch(`${API_BASE}/extensions`);
if (response.ok) {
const data = await response.json();
const extensions = data.extensions || [];
// Añadir cada nombre de extensión como una opción
extensions.forEach(extName => {
// Evitar duplicar 'anilist' o 'local'
if (extName.toLowerCase() !== 'anilist' && extName.toLowerCase() !== 'local') {
const option = document.createElement('option');
option.value = extName;
// Capitalizar el nombre
option.textContent = extName.charAt(0).toUpperCase() + extName.slice(1);
select.appendChild(option);
}
});
}
} catch (error) {
console.error('Error loading extensions:', error);
}
}
// Setup all event listeners
function setupEventListeners() {
// View toggle
document.querySelectorAll('.view-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const view = btn.dataset.view;
const container = document.getElementById('list-container');
if (view === 'list') {
container.classList.add('list-view');
} else {
container.classList.remove('list-view');
}
});
});
// Filters
document.getElementById('status-filter').addEventListener('change', applyFilters);
document.getElementById('source-filter').addEventListener('change', applyFilters);
document.getElementById('type-filter').addEventListener('change', applyFilters);
document.getElementById('sort-filter').addEventListener('change', applyFilters);
// Search
document.querySelector('.search-input').addEventListener('input', (e) => {
const query = e.target.value.toLowerCase();
if (query) {
filteredList = currentList.filter(item =>
item.title?.toLowerCase().includes(query)
);
} else {
filteredList = [...currentList];
}
applyFilters();
});
}
// Load list from API (MODIFICADO para incluir populateSourceFilter)
async function loadList() {
const loadingState = document.getElementById('loading-state');
const emptyState = document.getElementById('empty-state');
const container = document.getElementById('list-container');
// Ejecutar la carga de extensiones antes de la lista principal
await populateSourceFilter();
try {
loadingState.style.display = 'flex';
emptyState.style.display = 'none';
container.innerHTML = '';
const response = await fetch(`${API_BASE}/list`, {
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to load list');
}
const data = await response.json();
currentList = data.results || [];
filteredList = [...currentList];
loadingState.style.display = 'none';
if (currentList.length === 0) {
emptyState.style.display = 'flex';
} else {
updateStats();
applyFilters();
}
} catch (error) {
console.error('Error loading list:', error);
loadingState.style.display = 'none';
alert('Failed to load your list. Please try again.');
}
}
// Update statistics
function updateStats() {
const total = currentList.length;
const watching = currentList.filter(item => item.status === 'WATCHING').length;
const completed = currentList.filter(item => item.status === 'COMPLETED').length;
const planning = currentList.filter(item => item.status === 'PLANNING').length;
document.getElementById('total-count').textContent = total;
document.getElementById('watching-count').textContent = watching;
document.getElementById('completed-count').textContent = completed;
document.getElementById('planned-count').textContent = planning;
}
// Apply filters and sorting
function applyFilters() {
const statusFilter = document.getElementById('status-filter').value;
const sourceFilter = document.getElementById('source-filter').value;
const typeFilter = document.getElementById('type-filter').value;
const sortFilter = document.getElementById('sort-filter').value;
// Filter
let filtered = [...filteredList];
if (statusFilter !== 'all') {
filtered = filtered.filter(item => item.status === statusFilter);
}
if (sourceFilter !== 'all') {
filtered = filtered.filter(item => item.source === sourceFilter);
}
// Filtrado por tipo
if (typeFilter !== 'all') {
filtered = filtered.filter(item => (item.entry_type || 'ANIME') === typeFilter);
}
// Sort
switch (sortFilter) {
case 'title':
filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
break;
case 'score':
filtered.sort((a, b) => (b.score || 0) - (a.score || 0));
break;
case 'progress':
filtered.sort((a, b) => (b.progress || 0) - (a.progress || 0));
break;
case 'updated':
default:
filtered.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
break;
}
renderList(filtered);
}
// Render list items
function renderList(items) {
const container = document.getElementById('list-container');
container.innerHTML = '';
if (items.length === 0) {
container.innerHTML = '<div class="empty-state"><p>No entries match your filters</p></div>';
return;
}
items.forEach(item => {
const element = createListItem(item);
container.appendChild(element);
});
}
// Create individual list item (ACTUALIZADO para MANGA/NOVEL)
function createListItem(item) {
const div = document.createElement('div');
div.className = 'list-item';
div.onclick = () => openEditModal(item);
const posterUrl = item.poster || '/public/assets/placeholder.png';
const progress = item.progress || 0;
// Determinar total de unidades basado en el tipo
const totalUnits = item.entry_type === 'ANIME' ?
item.total_episodes || 0 :
item.total_chapters || 0;
const progressPercent = totalUnits > 0 ? (progress / totalUnits) * 100 : 0;
const score = item.score ? item.score.toFixed(1) : null;
// Determinar la etiqueta de unidad (Episodes, Chapters, Volumes, etc.)
const entryType = (item.entry_type || 'ANIME').toUpperCase();
let unitLabel = 'units';
if (entryType === 'ANIME') {
unitLabel = 'episodes';
} else if (entryType === 'MANGA') {
unitLabel = 'chapters';
} else if (entryType === 'NOVEL') {
unitLabel = 'chapters/volumes';
}
// Ajustar etiquetas de estado según el tipo (Watching/Reading)
const statusLabels = {
'WATCHING': entryType === 'ANIME' ? 'Watching' : 'Reading',
'COMPLETED': 'Completed',
'PLANNING': entryType === 'ANIME' ? 'Plan to Watch' : 'Plan to Read',
'PAUSED': 'Paused',
'DROPPED': 'Dropped'
};
div.innerHTML = `
<img src="${posterUrl}" alt="${item.title || 'Entry'}" class="item-poster" onerror="this.src='/public/assets/placeholder.png'">
<div class="item-content">
<h3 class="item-title">${item.title || 'Unknown Title'}</h3>
<div class="item-meta">
<span class="meta-pill status-pill">${statusLabels[item.status] || item.status}</span>
<span class="meta-pill type-pill">${entryType}</span>
<span class="meta-pill source-pill">${item.source.toUpperCase()}</span>
</div>
<div class="progress-bar-container">
<div class="progress-bar" style="width: ${progressPercent}%"></div>
</div>
<div class="progress-text">
<span>${progress}${totalUnits > 0 ? ` / ${totalUnits}` : ''} ${unitLabel}</span> ${score ? `<span class="score-badge">⭐ ${score}</span>` : ''}
</div>
</div>
`;
return div;
}
// Open edit modal (ACTUALIZADO para MANGA/NOVEL)
function openEditModal(item) {
currentEditingEntry = item;
document.getElementById('edit-status').value = item.status;
document.getElementById('edit-progress').value = item.progress || 0;
document.getElementById('edit-score').value = item.score || '';
// Ajusta el texto del campo de progreso en el modal
const entryType = (item.entry_type || 'ANIME').toUpperCase();
const progressLabel = document.querySelector('label[for="edit-progress"]');
if (progressLabel) {
if (entryType === 'MANGA') {
progressLabel.textContent = 'Chapters Read';
} else if (entryType === 'NOVEL') {
progressLabel.textContent = 'Chapters/Volumes Read';
} else {
progressLabel.textContent = 'Episodes Watched';
}
}
// Establecer el max del progreso
const totalUnits = item.entry_type === 'ANIME' ?
item.total_episodes || 999 :
item.total_chapters || 999;
document.getElementById('edit-progress').max = totalUnits;
document.getElementById('edit-modal').style.display = 'flex';
}
// Close edit modal
function closeEditModal() {
currentEditingEntry = null;
document.getElementById('edit-modal').style.display = 'none';
}
// Save entry changes
async function saveEntry() {
if (!currentEditingEntry) return;
const status = document.getElementById('edit-status').value;
const progress = parseInt(document.getElementById('edit-progress').value) || 0;
const score = parseFloat(document.getElementById('edit-score').value) || null;
try {
const response = await fetch(`${API_BASE}/list/entry`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({
entry_id: currentEditingEntry.entry_id,
source: currentEditingEntry.source,
entry_type: currentEditingEntry.entry_type || 'ANIME',
status: status,
progress: progress,
score: score
})
});
if (!response.ok) {
throw new Error('Failed to update entry');
}
closeEditModal();
await loadList();
showNotification('Entry updated successfully!', 'success');
} catch (error) {
console.error('Error updating entry:', error);
showNotification('Failed to update entry', 'error');
}
}
// Delete entry
async function deleteEntry() {
if (!currentEditingEntry) return;
if (!confirm('Are you sure you want to remove this entry from your list?')) {
return;
}
try {
const response = await fetch(`${API_BASE}/list/entry/${currentEditingEntry.entry_id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!response.ok) {
throw new Error('Failed to delete entry');
}
closeEditModal();
await loadList();
showNotification('Entry removed from list', 'success');
} catch (error) {
console.error('Error deleting entry:', error);
showNotification('Failed to remove entry', 'error');
}
}
// Show notification (unchanged)
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 100px;
right: 20px;
background: ${type === 'success' ? '#22c55e' : type === 'error' ? '#ef4444' : '#8b5cf6'};
color: white;
padding: 1rem 1.5rem;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
z-index: 9999;
font-weight: 600;
animation: slideInRight 0.3s ease;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Add keyframe animations (unchanged)
const style = document.createElement('style');
style.textContent = `
@keyframes slideInRight {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOutRight {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
`;
document.head.appendChild(style);
// Close modal on outside click (unchanged)
document.getElementById('edit-modal').addEventListener('click', (e) => {
if (e.target.id === 'edit-modal') {
closeEditModal();
}
});

View File

@@ -588,9 +588,6 @@ async function redirectToAniListLogin() {
const data = await res.json();
localStorage.setItem('token', data.token);
token = data.token;
localStorage.setItem('anilist_link_user', currentUserId);
const clientId = 32898;
const redirectUri = encodeURIComponent(

View File

@@ -51,14 +51,14 @@ async function ensureUserDataDB(dbPath) {
CREATE TABLE IF NOT EXISTS ListEntry (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
anime_id INTEGER NOT NULL,
external_id INTEGER,
entry_id INTEGER NOT NULL,
source TEXT NOT NULL,
entry_type TEXT NOT NULL,
status TEXT NOT NULL,
progress INTEGER NOT NULL DEFAULT 0,
score INTEGER,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_id, anime_id),
UNIQUE (user_id, entry_id),
FOREIGN KEY (user_id) REFERENCES User(id) ON DELETE CASCADE
);
`;

View File

@@ -13,6 +13,11 @@ async function viewsRoutes(fastify: FastifyInstance) {
reply.type('text/html').send(stream);
});
fastify.get('/my-list', (req: FastifyRequest, reply: FastifyReply) => {
const stream = fs.createReadStream(path.join(__dirname, '..', '..', 'views', 'list.html'));
reply.type('text/html').send(stream);
});
fastify.get('/books', (req: FastifyRequest, reply: FastifyReply) => {
const stream = fs.createReadStream(path.join(__dirname, '..', '..', 'views', 'books', 'books.html'));
reply.type('text/html').send(stream);