const db = require('../models'); const FileDBApi = require('./file'); const crypto = require('crypto'); const Utils = require('../utils'); const Sequelize = db.Sequelize; const Op = Sequelize.Op; module.exports = class EpisodesDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const episodes = await db.episodes.create( { id: data.id || undefined, title: data.title || null, release_date: data.release_date || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await episodes.setAnime(data.anime || null, { transaction, }); await episodes.setAniplay(data.aniplay || null, { transaction, }); await episodes.setComments(data.comments || [], { transaction, }); return episodes; } static async bulkImport(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; // Prepare data - wrapping individual data transformations in a map() method const episodesData = data.map((item, index) => ({ id: item.id || undefined, title: item.title || null, release_date: item.release_date || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const episodes = await db.episodes.bulkCreate(episodesData, { transaction, }); // For each item created, replace relation files return episodes; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const globalAccess = currentUser.app_role?.globalAccess; const episodes = await db.episodes.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.title !== undefined) updatePayload.title = data.title; if (data.release_date !== undefined) updatePayload.release_date = data.release_date; updatePayload.updatedById = currentUser.id; await episodes.update(updatePayload, { transaction }); if (data.anime !== undefined) { await episodes.setAnime( data.anime, { transaction }, ); } if (data.aniplay !== undefined) { await episodes.setAniplay( data.aniplay, { transaction }, ); } if (data.comments !== undefined) { await episodes.setComments(data.comments, { transaction }); } return episodes; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const episodes = await db.episodes.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of episodes) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of episodes) { await record.destroy({ transaction }); } }); return episodes; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const episodes = await db.episodes.findByPk(id, options); await episodes.update( { deletedBy: currentUser.id, }, { transaction, }, ); await episodes.destroy({ transaction, }); return episodes; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const episodes = await db.episodes.findOne({ where }, { transaction }); if (!episodes) { return episodes; } const output = episodes.get({ plain: true }); output.anime = await episodes.getAnime({ transaction, }); output.comments = await episodes.getComments({ transaction, }); output.aniplay = await episodes.getAniplay({ transaction, }); return output; } static async findAll(filter, globalAccess, options) { const limit = filter.limit || 0; let offset = 0; let where = {}; const currentPage = +filter.page; const user = (options && options.currentUser) || null; const userAniplay = (user && user.aniplay?.id) || null; if (userAniplay) { if (options?.currentUser?.aniplayId) { where.aniplayId = options.currentUser.aniplayId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.anime, as: 'anime', where: filter.anime ? { [Op.or]: [ { id: { [Op.in]: filter.anime .split('|') .map((term) => Utils.uuid(term)), }, }, { title: { [Op.or]: filter.anime .split('|') .map((term) => ({ [Op.iLike]: `%${term}%` })), }, }, ], } : {}, }, { model: db.aniplay, as: 'aniplay', }, { model: db.comments, as: 'comments', required: false, }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.title) { where = { ...where, [Op.and]: Utils.ilike('episodes', 'title', filter.title), }; } if (filter.calendarStart && filter.calendarEnd) { where = { ...where, [Op.or]: [ { release_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, { release_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, ], }; } if (filter.release_dateRange) { const [start, end] = filter.release_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, release_date: { ...where.release_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, release_date: { ...where.release_date, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.aniplay) { const listItems = filter.aniplay.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, aniplayId: { [Op.or]: listItems }, }; } if (filter.comments) { const searchTerms = filter.comments.split('|'); include = [ { model: db.comments, as: 'comments_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map((term) => Utils.uuid(term)), }, }, { content: { [Op.or]: searchTerms.map((term) => ({ [Op.iLike]: `%${term}%`, })), }, }, ], } : undefined, }, ...include, ]; } if (filter.createdAtRange) { const [start, end] = filter.createdAtRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, ['createdAt']: { ...where.createdAt, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, ['createdAt']: { ...where.createdAt, [Op.lte]: end, }, }; } } } if (globalAccess) { delete where.aniplayId; } const queryOptions = { where, include, distinct: true, order: filter.field && filter.sort ? [[filter.field, filter.sort]] : [['createdAt', 'desc']], transaction: options?.transaction, logging: console.log, }; if (!options?.countOnly) { queryOptions.limit = limit ? Number(limit) : undefined; queryOptions.offset = offset ? Number(offset) : undefined; } try { const { rows, count } = await db.episodes.findAndCountAll(queryOptions); return { rows: options?.countOnly ? [] : rows, count: count, }; } catch (error) { console.error('Error executing query:', error); throw error; } } static async findAllAutocomplete( query, limit, offset, globalAccess, organizationId, ) { let where = {}; if (!globalAccess && organizationId) { where.organizationId = organizationId; } if (query) { where = { [Op.or]: [ { ['id']: Utils.uuid(query) }, Utils.ilike('episodes', 'title', query), ], }; } const records = await db.episodes.findAll({ attributes: ['id', 'title'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['title', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.title, })); } };