const { Op } = require("sequelize"); const Entry = require("../models/Entry"); const EntryId = require("../models/EntryId"); const EntryRating = require("../models/EntryRating"); const EntrySeen = require("../models/EntrySeen"); const Episode = require("../models/Episode"); const EpisodeSeen = require("../models/EpisodeSeen"); const Season = require("../models/Season"); const { saveEntry } = require("./models-services/entryService"); const { fetchEntryData } = require("./tmdbService"); async function bulkImportMovies(movies) { const maxFetches = 35; // ! max fetch per 10 seconds const fetchInterval = 500; const waitTime = 10000; let entries = []; let overAllFetches = 0 let currenFetch = 0; // ? gettings all entries from db const entriesFromDb = await Entry.findAll({ include: [ { model: EntryId, as: 'entryId' } ] }) // ? creating a dict from the entries const entriesDict = entriesFromDb.reduce((dict, entry) => { dict[entry.entryId.tmdb_id] = entry; return dict; }, {}); for (const movie of movies) { if (entriesDict[movie.tmdbId]) { console.log(`Entry already exists: ${entriesDict[movie.tmdbId].title} (${movie.tmdbId})`) // ? adding date seen await EntrySeen.destroy({ where: { entry_id: entriesDict[movie.tmdbId].id } }); await EntrySeen.create({ entry_id: entriesDict[movie.tmdbId].id, date_seen: movie.dateSeen, seen_with: "" }); // ? adding entry user rating if (movie.userRating != 0) { await EntryRating.update({ user_rating: movie.userRating }, { where: { entry_id: entriesDict[movie.tmdbId].id } }); } } else { const data = await fetchEntryData(movie.tmdbId, false); if (data == null) { console.log(`${currenFetch} data null for id: ${movie.id}`); } const entry = await saveEntry(data); // ? adding date seen await EntrySeen.create({ entry_id: entry.id, date_seen: movie.dateSeen, seen_with: "" }); // ? adding entry user rating if (movie.userRating != 0) { await EntryRating.update({ user_rating: movie.userRating }, { where: { entry_id: entry.id } }); } entries.push(entry) // ? wait 100ms between each tmdb fetch await new Promise(resolve => setTimeout(resolve, fetchInterval)); console.log(`${currenFetch} imported id: ${movie.tmdbId}`); currenFetch++; overAllFetches++; // ? stop 10 seconds after 35 tmdb fetch if (currenFetch == maxFetches) { console.log(`Now waiting ${waitTime / 1000} seconds...`); await new Promise(resolve => setTimeout(resolve, waitTime)); currentFetch = 0; } } }; return entries; } async function bulkImportTmdb(movies) { const maxFetches = 35; // ! max fetch per 10 seconds const fetchInterval = 500; const waitTime = 10000; let entries = []; let overAllFetches = 0 let currentFetch = 0; // ? gettings all entries from db const entriesFromDb = await Entry.findAll({ include: [ { model: EntryId, as: 'entryId' } ] }) // ? creating a dict from the entries const entriesDict = entriesFromDb.reduce((dict, entry) => { dict[entry.entryId.tmdb_id] = entry; return dict; }, {}); let created = []; for (const movie of movies) { if (entriesDict[movie]) { console.log(`Entry already exists: ${entriesDict[movie].title} (${movie})`) created.push(movie); } else { if (created.includes(movie)) continue; // * skip doubles const data = await fetchEntryData(movie, true); if (data == null) { console.log(`${currentFetch} data null for id: ${movie.id}`); } // ? saving the entry const entry = await saveEntry(data); entries.push(entry) created.push(movie) currentFetch += data.seasons.length; // TODO implement option like rating, dateseen... // ? wait 100ms between each tmdb fetch await new Promise(resolve => setTimeout(resolve, fetchInterval)); console.log(`${overAllFetches} (${currentFetch + 1}/${maxFetches}) imported ${entry.title}`); if (data.seasons.length) console.log(`With ${data.seasons.length} season(s).`) currentFetch++; overAllFetches++; // ? stop 10 seconds after 35 tmdb fetch if (currentFetch >= maxFetches) { console.log(`Now waiting ${waitTime / 1000} seconds...`); await new Promise(resolve => setTimeout(resolve, waitTime)); currentFetch = 0; } } }; return entries; } async function bulkImportEpisodes(episodesSeen) { try { // ! DANGER clearing old episode seen await EpisodeSeen.destroy({ where: { entry_id: { [Op.ne]: 3 } } }) // ? gettings all entries from db const entriesFromDb = await Entry.findAll({ where: { is_tvseries: 1 }, include: [ { model: EntryId, as: 'entryId' }, { model: Season, as: 'seasons', include: [ { model: Episode, as: 'episodes' } ] } ] }) // ? creating two dictionnaries names & ids const idsDict = entriesFromDb.reduce((dict, entry) => { dict[entry.entryId.tmdb_id] = entry; return dict; }, {}); const titlesDict = entriesFromDb.reduce((dict, entry) => { dict[entry.title.toLowerCase()] = entry; return dict; }, {}); let added = {}; let rows = 0; let seasons = 0; let episodes = 0; for (let i = 0; i < episodesSeen.length; i++) { let theEntry; if (episodesSeen[i].type == 'id') { theEntry = idsDict[episodesSeen[i].id]; } else if (episodesSeen[i].type == 'title') { theEntry = titlesDict[episodesSeen[i].title.toLowerCase()]; } if (!theEntry) { console.log(`No entry found for line ${i + 1} (${episodesSeen[i].id || episodesSeen[i].title})`); continue; } let seasonFound = false; for (const season of theEntry.seasons) { if (season.season_number == episodesSeen[i].season) { seasonFound = true; seasons++; let episodeFound = false; for (const episode of season.episodes) { if (episode.episode_number == episodesSeen[i].episode) { episodeFound = true; episodes++; let date_seen = episodesSeen[i].date_seen; if (new Date(episodesSeen[i].date_seen) < new Date(episode.air_date)) { date_seen = episode.air_date.toISOString().split('T')[0]; console.log(`Date seen changed for ${theEntry.title} S${episodesSeen[i].season}E${episodesSeen[i].episode} from ${episodesSeen[i].date_seen} to ${date_seen}`); } let id = `${theEntry.id}${(episodesSeen[i].season + 0)}${episode.id}${date_seen.replace(/-/g, '')}`; if (!added[id]) { await EpisodeSeen.create({ entry_id: theEntry.id, episode_id: episode.id, date_seen: date_seen, seen_with: episodesSeen[i].seen_with }); added[id] = true; rows++; } } } } } } console.log(`rows:${rows}, seasons:${seasons}, episodes:${episodes} (out of ${episodesSeen.length})`) console.log(added); return rows; } catch (error) { console.log(error) } } module.exports = { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes, };