From a5659cf4c81b2da8fb219485aaf9b873f2f04560 Mon Sep 17 00:00:00 2001 From: X4Lo Date: Sun, 21 Jun 2026 22:28:08 +0100 Subject: [PATCH] Normalize to double quotes across all files with Prettier --- backend/.prettierrc | 6 + backend/config/dataInitializer.js | 68 +- backend/config/database.js | 18 +- backend/config/relations.js | 237 +- backend/config/sequelizeHooks.js | 230 +- backend/controllers/aiQueryController.js | 859 +- backend/controllers/collectionController.js | 282 +- backend/controllers/entryController.js | 76 +- backend/controllers/entrySeenController.js | 28 +- backend/controllers/episodeController.js | 7 +- backend/controllers/episodeSeenController.js | 67 +- backend/controllers/importController.js | 6 +- backend/controllers/killerController.js | 4 +- backend/controllers/mediaController.js | 90 +- backend/controllers/peopleController.js | 43 +- backend/controllers/pingController.js | 8 +- backend/controllers/seasonController.js | 33 +- backend/controllers/settingsController.js | 6 +- backend/controllers/statisticsController.js | 100 +- backend/errors/BadRequestError.js | 4 +- backend/errors/ConflictError.js | 2 +- backend/errors/CustomError.js | 2 +- backend/errors/ForbiddenError.js | 2 +- backend/errors/InternalServerError.js | 2 +- backend/errors/NotFoundError.js | 4 +- backend/errors/UnauthorizedError.js | 4 +- backend/errors/ValidationError.js | 4 +- backend/middleware/errorHandler.js | 44 +- backend/models/Collection.js | 38 +- backend/models/Credit.js | 38 +- backend/models/EntryGenre.js | 33 +- backend/models/EntryId.js | 22 +- backend/models/EntryNetwork.js | 29 +- backend/models/EntryRating.js | 23 +- backend/models/EntrySeen.js | 26 +- backend/models/Episode.js | 55 +- backend/models/EpisodeSeen.js | 50 +- backend/models/Franchise.js | 18 +- backend/models/Genre.js | 16 +- backend/models/Media.js | 42 +- backend/models/Network.js | 26 +- backend/models/People.js | 51 +- backend/models/Season.js | 50 +- backend/models/UserCollectionEntry.js | 30 +- backend/routes/ai-query.routes.js | 41 +- backend/routes/collection.routes.js | 46 +- backend/routes/entry-seen.routes.js | 19 +- backend/routes/entry.routes.js | 119 +- backend/routes/episode-seen.routes.js | 24 +- backend/routes/episode.routes.js | 9 +- backend/routes/import.routes.js | 13 +- backend/routes/killer.routes.js | 8 +- backend/routes/media.routes.js | 8 +- backend/routes/people.routes.js | 58 +- backend/routes/ping.routes.js | 6 +- backend/routes/routes.js | 71 +- backend/routes/season.routes.js | 18 +- backend/routes/settings.routes.js | 8 +- backend/routes/statistics.routes.js | 21 +- backend/server.js | 60 +- backend/services/collectionManager.js | 106 +- backend/services/collectionService.js | 52 +- backend/services/configService.js | 98 +- backend/services/episodeService.js | 26 +- backend/services/importerService.js | 149 +- backend/services/logService.js | 16 +- backend/services/mediaDownloaderService.js | 140 +- backend/services/mediaManager.js | 154 +- backend/services/mediaOptimizerService.js | 50 +- backend/services/mediaService.js | 4 +- .../services/models-services/entryService.js | 307 +- .../services/models-services/seasonService.js | 32 +- backend/services/mutlerStorageLocations.js | 93 +- backend/services/networkService.js | 39 +- backend/services/peopleManager.js | 36 +- backend/services/peopleService.js | 50 +- backend/services/storageService.js | 10 +- backend/services/tmdbService.js | 144 +- backend/utils/moment.js | 7652 ++++++++--------- changes.md | 6 + electron/pnpm-lock.yaml | 1190 +-- react_frontend/.prettierrc | 6 + react_frontend/src/App.tsx | 17 +- react_frontend/src/api/collections.ts | 23 +- react_frontend/src/api/entries.ts | 43 +- react_frontend/src/api/entry-seen.ts | 14 +- react_frontend/src/api/episode-seen.ts | 11 +- react_frontend/src/api/episodes.ts | 4 +- react_frontend/src/api/people.ts | 29 +- react_frontend/src/api/seasons.ts | 8 +- react_frontend/src/api/settings.ts | 8 +- react_frontend/src/api/statistics.ts | 16 +- react_frontend/src/api/tmdb.ts | 24 +- .../src/components/CommandPalette.tsx | 201 +- .../collections/CollectionsGrid.tsx | 12 +- .../components/dashboard/CouchDayChart.tsx | 80 +- .../dashboard/LibraryGrowthChart.tsx | 105 +- .../components/dashboard/MediaTypeChart.tsx | 57 +- .../src/components/dashboard/RatingsChart.tsx | 104 +- .../components/dashboard/TopGenresChart.tsx | 88 +- .../dashboard/WatchActivityChart.tsx | 120 +- .../components/dashboard/WatchTimeChart.tsx | 108 +- .../dialogs/AddEntryToCollectionDialog.tsx | 53 +- .../dialogs/CollectionEditDialog.tsx | 48 +- .../src/components/dialogs/ConfirmDialog.tsx | 22 +- .../components/dialogs/EntryMediaDialog.tsx | 40 +- .../components/dialogs/EntrySeenDialog.tsx | 102 +- .../dialogs/EntrySettingsDialog.tsx | 41 +- .../dialogs/EpisodeSeenEditDialog.tsx | 56 +- .../dialogs/MarkSeasonWatchedDialog.tsx | 80 +- .../dialogs/MovieWatchHistoryDialog.tsx | 16 +- .../src/components/dialogs/RatingDialog.tsx | 18 +- .../entries/EpisodeWatchHistory.tsx | 14 +- .../components/entries/SeasonsContainer.tsx | 44 +- .../src/components/entries/TrendingGrid.tsx | 20 +- .../src/components/entries/TrendingSlider.tsx | 40 +- .../src/components/home/HeroSlider.tsx | 65 +- .../src/components/home/PopularBelt.tsx | 20 +- .../src/components/home/SectionHeader.tsx | 2 +- react_frontend/src/components/home/index.ts | 14 +- .../src/components/layout/AppLayout.tsx | 41 +- .../src/components/layout/Sidebar.tsx | 61 +- .../src/components/layout/TitleBar.tsx | 16 +- .../components/skeletons/PageSkeletons.tsx | 9 +- .../streaming/AutoMarkWatchedPrompt.tsx | 9 +- .../components/streaming/EpisodeNavigator.tsx | 39 +- .../components/streaming/EpisodesSidebar.tsx | 55 +- .../components/streaming/ServerSelector.tsx | 15 +- .../components/streaming/StreamingDialog.tsx | 125 +- .../src/components/streaming/index.ts | 14 +- react_frontend/src/components/ui/avatar.tsx | 36 +- react_frontend/src/components/ui/badge.tsx | 18 +- react_frontend/src/components/ui/button.tsx | 14 +- react_frontend/src/components/ui/calendar.tsx | 89 +- react_frontend/src/components/ui/card.tsx | 30 +- react_frontend/src/components/ui/checkbox.tsx | 15 +- react_frontend/src/components/ui/dialog.tsx | 51 +- .../src/components/ui/dropdown-menu.tsx | 82 +- react_frontend/src/components/ui/input.tsx | 12 +- react_frontend/src/components/ui/label.tsx | 10 +- react_frontend/src/components/ui/popover.tsx | 24 +- react_frontend/src/components/ui/progress.tsx | 20 +- .../src/components/ui/scroll-area.tsx | 16 +- react_frontend/src/components/ui/select.tsx | 53 +- .../src/components/ui/separator.tsx | 10 +- react_frontend/src/components/ui/sheet.tsx | 45 +- react_frontend/src/components/ui/skeleton.tsx | 6 +- react_frontend/src/components/ui/sonner.tsx | 16 +- .../src/components/ui/star-rating.tsx | 34 +- react_frontend/src/components/ui/switch.tsx | 12 +- react_frontend/src/components/ui/tabs.tsx | 26 +- react_frontend/src/components/ui/textarea.tsx | 10 +- react_frontend/src/hooks/useCollections.ts | 43 +- react_frontend/src/hooks/useDebounce.ts | 2 +- react_frontend/src/hooks/useEntrySeen.ts | 31 +- react_frontend/src/hooks/useEpisodeSeen.ts | 34 +- react_frontend/src/hooks/useEpisodes.ts | 6 +- react_frontend/src/hooks/usePeople.ts | 51 +- react_frontend/src/hooks/useSeasons.ts | 10 +- react_frontend/src/hooks/useStatistics.ts | 12 +- react_frontend/src/hooks/useTmdb.ts | 24 +- react_frontend/src/hooks/useTmdbEntryLink.ts | 10 +- react_frontend/src/lib/api.ts | 17 +- react_frontend/src/lib/media-utils.ts | 69 +- react_frontend/src/lib/streaming/index.ts | 15 +- .../src/lib/streaming/providers/anyembed.ts | 50 +- .../src/lib/streaming/providers/index.ts | 6 +- .../src/lib/streaming/providers/vidking.ts | 30 +- .../src/lib/streaming/providers/vidlink.ts | 40 +- .../src/lib/streaming/streaming-manager.ts | 86 +- react_frontend/src/lib/streaming/types.ts | 27 +- react_frontend/src/lib/utils.ts | 6 +- react_frontend/src/main.tsx | 12 +- react_frontend/src/pages/CalendarPage.tsx | 207 +- react_frontend/src/pages/CollectionsPage.tsx | 33 +- react_frontend/src/pages/DashboardPage.tsx | 81 +- react_frontend/src/pages/DiscoverPage.tsx | 62 +- react_frontend/src/pages/EntryCastsPage.tsx | 154 +- react_frontend/src/pages/EpisodePage.tsx | 105 +- react_frontend/src/pages/MediaPage.tsx | 64 +- react_frontend/src/pages/PeoplePage.tsx | 76 +- .../src/pages/PersonDetailsPage.tsx | 183 +- .../src/pages/PersonTmdbRedirectPage.tsx | 165 +- react_frontend/src/pages/SearchPage.tsx | 42 +- react_frontend/src/pages/SeasonPage.tsx | 71 +- .../src/stores/useCommandPaletteStore.ts | 11 +- .../src/stores/useLibraryFiltersStore.ts | 45 +- react_frontend/src/stores/useLibraryStore.ts | 4 +- .../src/stores/useStreamingStore.ts | 26 +- react_frontend/src/stores/useThemeStore.ts | 20 +- 190 files changed, 9523 insertions(+), 8859 deletions(-) create mode 100644 backend/.prettierrc create mode 100644 react_frontend/.prettierrc diff --git a/backend/.prettierrc b/backend/.prettierrc new file mode 100644 index 0000000..168791c --- /dev/null +++ b/backend/.prettierrc @@ -0,0 +1,6 @@ +{ + "singleQuote": false, + "trailingComma": "all", + "tabWidth": 2, + "semi": true +} diff --git a/backend/config/dataInitializer.js b/backend/config/dataInitializer.js index cfe2e6f..a314519 100644 --- a/backend/config/dataInitializer.js +++ b/backend/config/dataInitializer.js @@ -5,14 +5,12 @@ const Entry = require("../models/Entry"); const Genre = require("../models/Genre"); const Media = require("../models/Media"); - async function initializeData() { initializeGenres(); //markEntriesRequireCreditsSync(); // migrateAccuracyField(); } - // const collections = await Collection.findAll({ // where: { // posterPath: { [Sequelize.Op.notLike]: '/%' } @@ -36,14 +34,14 @@ async function initializeData() { async function markEntriesRequireCreditsSync() { try { const [affectedCount] = await Entry.update( - { entry_sync_status: 'RequireCreditsSync' }, - { where: { entry_sync_status: null } } + { entry_sync_status: "RequireCreditsSync" }, + { where: { entry_sync_status: null } }, ); if (affectedCount > 0) { console.log(`Marked ${affectedCount} entries as RequireCreditsSync`); } } catch (error) { - console.error('Error marking entries for credits sync:', error); + console.error("Error marking entries for credits sync:", error); } } @@ -51,33 +49,33 @@ async function initializeGenres() { try { // * data to insert: const initialGenres = [ - { id: 10759, name: 'Action & Adventure' }, - { id: 16, name: 'Animation' }, - { id: 35, name: 'Comedy' }, - { id: 80, name: 'Crime' }, - { id: 99, name: 'Documentary' }, - { id: 18, name: 'Drama' }, - { id: 10751, name: 'Family' }, - { id: 10762, name: 'Kids' }, - { id: 9648, name: 'Mystery' }, - { id: 10763, name: 'News' }, - { id: 10764, name: 'Reality' }, - { id: 10765, name: 'Sci-Fi & Fantasy' }, - { id: 10766, name: 'Soap' }, - { id: 10767, name: 'Talk' }, - { id: 10768, name: 'War & Politics' }, - { id: 37, name: 'Western' }, - { id: 28, name: 'Action' }, - { id: 12, name: 'Adventure' }, - { id: 14, name: 'Fantasy' }, - { id: 36, name: 'History' }, - { id: 27, name: 'Horror' }, - { id: 10402, name: 'Music' }, - { id: 10749, name: 'Romance' }, - { id: 878, name: 'Science Fiction' }, - { id: 10770, name: 'TV Movie' }, - { id: 53, name: 'Thriller' }, - { id: 10752, name: 'War' } + { id: 10759, name: "Action & Adventure" }, + { id: 16, name: "Animation" }, + { id: 35, name: "Comedy" }, + { id: 80, name: "Crime" }, + { id: 99, name: "Documentary" }, + { id: 18, name: "Drama" }, + { id: 10751, name: "Family" }, + { id: 10762, name: "Kids" }, + { id: 9648, name: "Mystery" }, + { id: 10763, name: "News" }, + { id: 10764, name: "Reality" }, + { id: 10765, name: "Sci-Fi & Fantasy" }, + { id: 10766, name: "Soap" }, + { id: 10767, name: "Talk" }, + { id: 10768, name: "War & Politics" }, + { id: 37, name: "Western" }, + { id: 28, name: "Action" }, + { id: 12, name: "Adventure" }, + { id: 14, name: "Fantasy" }, + { id: 36, name: "History" }, + { id: 27, name: "Horror" }, + { id: 10402, name: "Music" }, + { id: 10749, name: "Romance" }, + { id: 878, name: "Science Fiction" }, + { id: 10770, name: "TV Movie" }, + { id: 53, name: "Thriller" }, + { id: 10752, name: "War" }, ]; // * Check if the data already exists @@ -85,7 +83,7 @@ async function initializeGenres() { // ? If data already exists, return if (existingGenres.length == initialGenres.length) { - console.log('Genres already initialized'); + console.log("Genres already initialized"); return; } @@ -94,7 +92,7 @@ async function initializeGenres() { console.log(`${initialGenres.length} Genres initialized successfully`); } catch (error) { - console.error('Error initializing data:', error); + console.error("Error initializing data:", error); } } @@ -102,7 +100,7 @@ module.exports = { initializeData, initializeGenres, markEntriesRequireCreditsSync, -} +}; // async function migrateAccuracyField() { // try { diff --git a/backend/config/database.js b/backend/config/database.js index ff7e7df..8112f38 100644 --- a/backend/config/database.js +++ b/backend/config/database.js @@ -1,14 +1,14 @@ -const { Sequelize } = require('sequelize'); -const fs = require('fs'); +const { Sequelize } = require("sequelize"); +const fs = require("fs"); -const logStream = fs.createWriteStream('sequelize.log', { flags: 'a' }); +const logStream = fs.createWriteStream("sequelize.log", { flags: "a" }); -const sequelize = new Sequelize('Showzy', 'root', 'password', { - host: 'localhost', - dialect: 'mysql', +const sequelize = new Sequelize("Showzy", "root", "password", { + host: "localhost", + dialect: "mysql", logging: (msg) => { - logStream.write(msg + '\n'); - } + logStream.write(msg + "\n"); + }, }); -module.exports = sequelize; \ No newline at end of file +module.exports = sequelize; diff --git a/backend/config/relations.js b/backend/config/relations.js index ffd78a6..056ffe8 100644 --- a/backend/config/relations.js +++ b/backend/config/relations.js @@ -1,22 +1,21 @@ // Import models -const Franchise = require('../models/Franchise'); -const Entry = require('../models/Entry') -const EntryId = require('../models/EntryId') -const EntryRating = require('../models/EntryRating') -const EntrySeen = require('../models/EntrySeen'); -const Collection = require('../models/Collection'); -const UserCollectionEntry = require('../models/UserCollectionEntry'); -const Season = require('../models/Season'); -const Episode = require('../models/Episode'); -const EpisodeSeen = require('../models/EpisodeSeen'); -const Genre = require('../models/Genre'); -const EntryGenre = require('../models/EntryGenre'); -const Media = require('../models/Media'); -const Network = require('../models/Network'); -const EntryNetwork = require('../models/EntryNetwork'); -const People = require('../models/People'); -const Credit = require('../models/Credit'); - +const Franchise = require("../models/Franchise"); +const Entry = require("../models/Entry"); +const EntryId = require("../models/EntryId"); +const EntryRating = require("../models/EntryRating"); +const EntrySeen = require("../models/EntrySeen"); +const Collection = require("../models/Collection"); +const UserCollectionEntry = require("../models/UserCollectionEntry"); +const Season = require("../models/Season"); +const Episode = require("../models/Episode"); +const EpisodeSeen = require("../models/EpisodeSeen"); +const Genre = require("../models/Genre"); +const EntryGenre = require("../models/EntryGenre"); +const Media = require("../models/Media"); +const Network = require("../models/Network"); +const EntryNetwork = require("../models/EntryNetwork"); +const People = require("../models/People"); +const Credit = require("../models/Credit"); // ? one to one // A hasOne B = A > B @@ -25,197 +24,223 @@ const Credit = require('../models/Credit'); // A hasMany B = A > B // A belongsTo B = A < B - // * ENTRY & EntryId - ONE TO ONE Entry.hasOne(EntryId, { - foreignKey: 'entry_id', as: 'entryId', onDelete: 'CASCADE', + foreignKey: "entry_id", + as: "entryId", + onDelete: "CASCADE", }); -EntryId.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' }); +EntryId.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); // * ENTRY & EntryRating - ONE TO ONE Entry.hasOne(EntryRating, { - foreignKey: 'entry_id', as: 'entryRating', onDelete: 'CASCADE', + foreignKey: "entry_id", + as: "entryRating", + onDelete: "CASCADE", }); -EntryRating.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' }); +EntryRating.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); // * ENTRY & ENTRY_SEEN - ONE TO MANY Entry.hasMany(EntrySeen, { - foreignKey: 'entry_id', as: 'entrySeen', onDelete: 'CASCADE', + foreignKey: "entry_id", + as: "entrySeen", + onDelete: "CASCADE", }); -EntrySeen.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' }); +EntrySeen.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); // * ENTRY & LIST - MANY TO MANY Entry.belongsToMany(Collection, { through: UserCollectionEntry, - foreignKey: 'entry_id', - otherKey: 'user_collection_id', - onDelete: 'CASCADE', - as: 'collections', + foreignKey: "entry_id", + otherKey: "user_collection_id", + onDelete: "CASCADE", + as: "collections", }); Collection.belongsToMany(Entry, { through: UserCollectionEntry, - foreignKey: 'user_collection_id', - otherKey: 'entry_id', - onDelete: 'CASCADE', - as: 'entries', + foreignKey: "user_collection_id", + otherKey: "entry_id", + onDelete: "CASCADE", + as: "entries", }); -Entry.hasMany(UserCollectionEntry, { foreignKey: 'entry_id', as: 'userCollectionEntries' }); -UserCollectionEntry.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' }); -Collection.hasMany(UserCollectionEntry, { foreignKey: 'user_collection_id', as: 'userCollectionEntries' }); -UserCollectionEntry.belongsTo(Collection, { foreignKey: 'user_collection_id', as: 'userCollection' }); +Entry.hasMany(UserCollectionEntry, { + foreignKey: "entry_id", + as: "userCollectionEntries", +}); +UserCollectionEntry.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); +Collection.hasMany(UserCollectionEntry, { + foreignKey: "user_collection_id", + as: "userCollectionEntries", +}); +UserCollectionEntry.belongsTo(Collection, { + foreignKey: "user_collection_id", + as: "userCollection", +}); // * ENTRY & GENRE - MANY TO MANY Entry.belongsToMany(Genre, { through: EntryGenre, - foreignKey: 'entry_id', - otherKey: 'genre_id', - onDelete: 'CASCADE', - as: 'genres', + foreignKey: "entry_id", + otherKey: "genre_id", + onDelete: "CASCADE", + as: "genres", }); Genre.belongsToMany(Entry, { through: EntryGenre, - foreignKey: 'genre_id', - otherKey: 'entry_id', - onDelete: 'CASCADE', - as: 'entries', + foreignKey: "genre_id", + otherKey: "entry_id", + onDelete: "CASCADE", + as: "entries", }); -Entry.hasMany(EntryGenre, { foreignKey: 'entry_id', as: 'entryGenres' }); -EntryGenre.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' }); -Genre.hasMany(EntryGenre, { foreignKey: 'genre_id', as: 'entryGenres' }); -EntryGenre.belongsTo(Genre, { foreignKey: 'genre_id', as: 'genre' }); +Entry.hasMany(EntryGenre, { foreignKey: "entry_id", as: "entryGenres" }); +EntryGenre.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); +Genre.hasMany(EntryGenre, { foreignKey: "genre_id", as: "entryGenres" }); +EntryGenre.belongsTo(Genre, { foreignKey: "genre_id", as: "genre" }); // * ENTRY & NETWORK - MANY TO MANY Entry.belongsToMany(Network, { through: EntryNetwork, - foreignKey: 'entry_id', - otherKey: 'network_id', - onDelete: 'CASCADE', - as: 'networks', + foreignKey: "entry_id", + otherKey: "network_id", + onDelete: "CASCADE", + as: "networks", }); Network.belongsToMany(Entry, { through: EntryNetwork, - foreignKey: 'network_id', - otherKey: 'entry_id', - onDelete: 'CASCADE', - as: 'entries', + foreignKey: "network_id", + otherKey: "entry_id", + onDelete: "CASCADE", + as: "entries", }); // ! MEDIA // * MEDIA & ENTRY - MANY TO ONE Media.belongsTo(Entry, { - foreignKey: 'mediaableId', - as: 'entry', + foreignKey: "mediaableId", + as: "entry", constraints: false, where: { - mediaable: 'entry' - } + mediaable: "entry", + }, }); Entry.hasMany(Media, { - foreignKey: 'mediaableId', + foreignKey: "mediaableId", constraints: false, - as: 'medias', - scope: { mediaable: 'entry' } + as: "medias", + scope: { mediaable: "entry" }, }); // * MEDIA & People - MANY TO ONE Media.belongsTo(People, { - foreignKey: 'mediaableId', - as: 'people', + foreignKey: "mediaableId", + as: "people", constraints: false, where: { - mediaable: 'people' - } + mediaable: "people", + }, }); People.hasMany(Media, { - foreignKey: 'mediaableId', + foreignKey: "mediaableId", constraints: false, - as: 'medias', - scope: { mediaable: 'people' } + as: "medias", + scope: { mediaable: "people" }, }); // * MEDIA & Collection - MANY TO ONE Media.belongsTo(Collection, { - foreignKey: 'mediaableId', - as: 'collection', + foreignKey: "mediaableId", + as: "collection", constraints: false, where: { - mediaable: 'collection' - } + mediaable: "collection", + }, }); Collection.hasMany(Media, { - foreignKey: 'mediaableId', + foreignKey: "mediaableId", constraints: false, - as: 'medias', - scope: { mediaable: 'collection' } + as: "medias", + scope: { mediaable: "collection" }, }); // * MEDIA & Season - MANY TO ONE Media.belongsTo(Season, { - foreignKey: 'mediaableId', - as: 'season', + foreignKey: "mediaableId", + as: "season", constraints: false, where: { - mediaable: 'season' - } + mediaable: "season", + }, }); Season.hasMany(Media, { - foreignKey: 'mediaableId', + foreignKey: "mediaableId", constraints: false, - as: 'medias', - scope: { mediaable: 'season' } + as: "medias", + scope: { mediaable: "season" }, }); // * MEDIA & Episode - MANY TO ONE Media.belongsTo(Episode, { - foreignKey: 'mediaableId', - as: 'episode', + foreignKey: "mediaableId", + as: "episode", constraints: false, where: { - mediaable: 'episode' - } + mediaable: "episode", + }, }); Episode.hasMany(Media, { - foreignKey: 'mediaableId', + foreignKey: "mediaableId", constraints: false, - as: 'medias', - scope: { mediaable: 'episode' } + as: "medias", + scope: { mediaable: "episode" }, }); // ! MEDIA END // * ENTRY & SEASON - ONE TO MANY -Entry.hasMany(Season, { foreignKey: 'entry_id', as: 'seasons', onDelete: 'CASCADE', }); -Season.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' }); +Entry.hasMany(Season, { + foreignKey: "entry_id", + as: "seasons", + onDelete: "CASCADE", +}); +Season.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); // * SEASON & EPISODE - ONE TO MANY -Season.hasMany(Episode, { foreignKey: 'season_id', onDelete: 'CASCADE', }); -Episode.belongsTo(Season, { foreignKey: 'season_id' }); +Season.hasMany(Episode, { foreignKey: "season_id", onDelete: "CASCADE" }); +Episode.belongsTo(Season, { foreignKey: "season_id" }); // * EPISODE & EPISODE_SEEN - ONE TO MANY -Episode.hasMany(EpisodeSeen, { foreignKey: 'episode_id', onDelete: 'CASCADE', }); -EpisodeSeen.belongsTo(Episode, { foreignKey: 'episode_id' }); +Episode.hasMany(EpisodeSeen, { foreignKey: "episode_id", onDelete: "CASCADE" }); +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' }); +Entry.hasMany(EpisodeSeen, { foreignKey: "entry_id", onDelete: "CASCADE" }); +EpisodeSeen.belongsTo(Entry, { foreignKey: "entry_id" }); // * ---- -Franchise.hasMany(Entry, { foreignKey: 'franchise_id' }); -Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' }); +Franchise.hasMany(Entry, { foreignKey: "franchise_id" }); +Entry.belongsTo(Franchise, { foreignKey: "franchise_id" }); // * ENTRY & Credit - ONE TO MANY -Entry.hasMany(Credit, { foreignKey: 'entry_id', as: 'credits', onDelete: 'CASCADE', }); -Credit.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' }); +Entry.hasMany(Credit, { + foreignKey: "entry_id", + as: "credits", + onDelete: "CASCADE", +}); +Credit.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" }); // * PEOPLE & CAST - ONE TO MANY -People.hasMany(Credit, { foreignKey: 'people_id', as: 'roles', onDelete: 'CASCADE', }); -Credit.belongsTo(People, { foreignKey: 'people_id', as: 'person' }); \ No newline at end of file +People.hasMany(Credit, { + foreignKey: "people_id", + as: "roles", + onDelete: "CASCADE", +}); +Credit.belongsTo(People, { foreignKey: "people_id", as: "person" }); diff --git a/backend/config/sequelizeHooks.js b/backend/config/sequelizeHooks.js index 9b4f2c4..ac01080 100644 --- a/backend/config/sequelizeHooks.js +++ b/backend/config/sequelizeHooks.js @@ -1,17 +1,17 @@ // Import models -const Franchise = require('../models/Franchise'); -const Entry = require('../models/Entry') -const EntryId = require('../models/EntryId') -const EntryRating = require('../models/EntryRating') -const EntrySeen = require('../models/EntrySeen'); -const UserCollection = require('../models/Collection'); -const UserCollectionEntry = require('../models/UserCollectionEntry'); -const Season = require('../models/Season'); -const Episode = require('../models/Episode'); -const EpisodeSeen = require('../models/EpisodeSeen'); -const Genre = require('../models/Genre'); -const EntryGenre = require('../models/EntryGenre'); -const sequelize = require('./database'); +const Franchise = require("../models/Franchise"); +const Entry = require("../models/Entry"); +const EntryId = require("../models/EntryId"); +const EntryRating = require("../models/EntryRating"); +const EntrySeen = require("../models/EntrySeen"); +const UserCollection = require("../models/Collection"); +const UserCollectionEntry = require("../models/UserCollectionEntry"); +const Season = require("../models/Season"); +const Episode = require("../models/Episode"); +const EpisodeSeen = require("../models/EpisodeSeen"); +const Genre = require("../models/Genre"); +const EntryGenre = require("../models/EntryGenre"); +const sequelize = require("./database"); // ! Hooks // ? user collections @@ -19,22 +19,27 @@ const sequelize = require('./database'); UserCollectionEntry.afterCreate(async (instance, options) => { try { // ? mimicking a change in UserCollection to trigger updatedAt property update for the UserCollection - const userCollections = await UserCollection.findByPk(instance.user_collection_id); + const userCollections = await UserCollection.findByPk( + instance.user_collection_id, + ); await userCollections.update({ - name: sequelize.literal('name') + name: sequelize.literal("name"), }); const userCollectionEntriesCount = await UserCollectionEntry.count({ where: { - user_collection_id: instance.user_collection_id - } - }) + user_collection_id: instance.user_collection_id, + }, + }); // ? updating newly create UserCollectionEntry order await instance.update({ - order: userCollectionEntriesCount - }) + order: userCollectionEntriesCount, + }); } catch (error) { - console.log(`Sequelize Hook Error: UserCollectionEntry.afterCreate: `, error) + console.log( + `Sequelize Hook Error: UserCollectionEntry.afterCreate: `, + error, + ); } }); @@ -42,53 +47,64 @@ UserCollectionEntry.afterCreate(async (instance, options) => { UserCollectionEntry.afterUpdate(async (instance, options) => { try { // ? mimicking a change in UserCollection to trigger updatedAt property update for the UserCollection - const userCollections = await UserCollection.findByPk(instance.user_collection_id); + const userCollections = await UserCollection.findByPk( + instance.user_collection_id, + ); await userCollections.update({ - name: sequelize.literal('name') + name: sequelize.literal("name"), }); // ? updating other entries order const collectionEntries = await UserCollectionEntry.findAll({ where: { - user_collection_id: instance.user_collection_id + user_collection_id: instance.user_collection_id, }, - order: [['order', 'ASC']] - }) + order: [["order", "ASC"]], + }); - // * changing the order of all entries that are now after the updated entry + // * changing the order of all entries that are now after the updated entry let startOrder = instance.order + 1; for (let i = 0; i < collectionEntries.length; i++) { - if (collectionEntries[i].order >= instance.order && collectionEntries[i].entry_id != instance.entry_id) { - await collectionEntries[i].update({ order: startOrder }, { hooks: false }) + if ( + collectionEntries[i].order >= instance.order && + collectionEntries[i].entry_id != instance.entry_id + ) { + await collectionEntries[i].update( + { order: startOrder }, + { hooks: false }, + ); startOrder++; } } } catch (error) { - console.log(`Sequelize Hook Error: UserCollectionEntry.afterUpdate: `, error) + console.log( + `Sequelize Hook Error: UserCollectionEntry.afterUpdate: `, + error, + ); } }); // * entry remove UserCollectionEntry.afterDestroy(async (instance, options) => { try { - const userCollection = await UserCollection.findByPk(instance.user_collection_id); + const userCollection = await UserCollection.findByPk( + instance.user_collection_id, + ); const entry = await Entry.findByPk(instance.entry_id); if (!entry || !userCollection) return; // ? mimicking a change to trigger updatedAt property update let updates = { - name: sequelize.literal('name') - } + name: sequelize.literal("name"), + }; const collectionsEntries = await UserCollectionEntry.findAll({ where: { - user_collection_id: instance.user_collection_id + user_collection_id: instance.user_collection_id, }, - include: [ - { model: Entry, as: 'entry' }, - ] - }) + include: [{ model: Entry, as: "entry" }], + }); // ? updating collection poster // ? remove the poster if the collection is empty now @@ -106,16 +122,19 @@ UserCollectionEntry.afterDestroy(async (instance, options) => { if (instance.order != collectionsEntries.length) { for (let i = 0; i < collectionsEntries.length; i++) { if (collectionsEntries[i].order > instance.order) { - collectionsEntries[i].update({ order: order }, { hooks: false }) + collectionsEntries[i].update({ order: order }, { hooks: false }); order++; } } } // ? updating the collection updatedAt and poster maybe - await userCollection.update(updates) + await userCollection.update(updates); } catch (error) { - console.log(`Sequelize Hook Error: UserCollectionEntry.afterDestroy: `, error) + console.log( + `Sequelize Hook Error: UserCollectionEntry.afterDestroy: `, + error, + ); } }); @@ -128,22 +147,28 @@ EntrySeen.afterCreate(async (instance, options) => { // this will ensure that the entry is updated anyways to trigger the updatedAt property let update = { - watchlist: false + watchlist: false, }; // ? comparing the instance.date_seen with the entry date_first_seen & // ? date_last_seen to check if they should be replaced - if (!entry.date_first_seen || instance.date_seen < new Date(entry.date_first_seen)) { + if ( + !entry.date_first_seen || + instance.date_seen < new Date(entry.date_first_seen) + ) { update.date_first_seen = instance.date_seen; } - if (!entry.date_last_seen || instance.date_seen > new Date(entry.date_last_seen)) { + if ( + !entry.date_last_seen || + instance.date_seen > new Date(entry.date_last_seen) + ) { update.date_last_seen = instance.date_seen; } // * updating the entry await entry.update(update); } catch (error) { - console.log(`Sequelize Hook Error: EntrySeen.afterCreate: `, error) + console.log(`Sequelize Hook Error: EntrySeen.afterCreate: `, error); } }); @@ -158,11 +183,9 @@ EntrySeen.afterUpdate(async (instance, options) => { // ? and the last one to: date_last_seen const entrySeens = await EntrySeen.findAll({ where: { - entry_id: instance.entry_id + entry_id: instance.entry_id, }, - order: [ - ['date_seen', 'ASC'] - ] + order: [["date_seen", "ASC"]], }); let update = {}; @@ -172,7 +195,7 @@ EntrySeen.afterUpdate(async (instance, options) => { // * updating the entry await entry.update(update); } catch (error) { - console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error) + console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error); } }); @@ -187,11 +210,9 @@ EntrySeen.afterDestroy(async (instance, options) => { // ? and the last one to: date_last_seen const entrySeens = await EntrySeen.findAll({ where: { - entry_id: instance.entry_id + entry_id: instance.entry_id, }, - order: [ - ['date_seen', 'ASC'] - ] + order: [["date_seen", "ASC"]], }); let update = {}; @@ -209,7 +230,7 @@ EntrySeen.afterDestroy(async (instance, options) => { // * updating the entry await entry.update(update); } catch (error) { - console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error) + console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error); } }); @@ -224,15 +245,21 @@ EpisodeSeen.afterCreate(async (instance, options) => { // this will ensure that the entry is updated anyways to trigger the updatedAt property let update = { // title: sequelize.literal('title') - watchlist: false + watchlist: false, }; // ? comparing the instance.date_seen with the entry date_first_seen & // ? date_last_seen to check if they should be replaced - if (!entry.date_first_seen || instance.date_seen < new Date(entry.date_first_seen)) { + if ( + !entry.date_first_seen || + instance.date_seen < new Date(entry.date_first_seen) + ) { update.date_first_seen = instance.date_seen; } - if (!entry.date_last_seen || instance.date_seen > new Date(entry.date_last_seen)) { + if ( + !entry.date_last_seen || + instance.date_seen > new Date(entry.date_last_seen) + ) { update.date_last_seen = instance.date_seen; } @@ -245,22 +272,28 @@ EpisodeSeen.afterCreate(async (instance, options) => { // this will ensure that the episode is updated anyways to trigger the updatedAt property let episodeUpdate = { - name: sequelize.literal('name') + name: sequelize.literal("name"), }; // ? comparing the instance.date_seen with the entry date_first_seen & // ? date_last_seen to check if they should be replaced - if (!episode.date_first_seen || instance.date_seen < new Date(episode.date_first_seen)) { + if ( + !episode.date_first_seen || + instance.date_seen < new Date(episode.date_first_seen) + ) { episodeUpdate.date_first_seen = instance.date_seen; } - if (!episode.date_last_seen || instance.date_seen > new Date(episode.date_last_seen)) { + if ( + !episode.date_last_seen || + instance.date_seen > new Date(episode.date_last_seen) + ) { episodeUpdate.date_last_seen = instance.date_seen; } // * updating the episode await episode.update(episodeUpdate); } catch (error) { - console.log(`Sequelize Hook Error: EpisodeSeen.afterCreate: `, error) + console.log(`Sequelize Hook Error: EpisodeSeen.afterCreate: `, error); } }); @@ -275,22 +308,24 @@ EpisodeSeen.afterUpdate(async (instance, options) => { // ? for the current entry EpisodeSeen.findAll({ attributes: [ - [sequelize.fn('min', sequelize.col('date_seen')), 'minValue'], - [sequelize.fn('max', sequelize.col('date_seen')), 'maxValue'] + [sequelize.fn("min", sequelize.col("date_seen")), "minValue"], + [sequelize.fn("max", sequelize.col("date_seen")), "maxValue"], ], where: { - entry_id: instance.entry_id - } - }).then(result => { - let update = {}; + entry_id: instance.entry_id, + }, + }) + .then((result) => { + let update = {}; - update.date_first_seen = result[0].dataValues.minValue; - update.date_last_seen = result[0].dataValues.maxValue; + update.date_first_seen = result[0].dataValues.minValue; + update.date_last_seen = result[0].dataValues.maxValue; - entry.update(update); - }).catch(err => { - console.error('Error:', err); - }); + entry.update(update); + }) + .catch((err) => { + console.error("Error:", err); + }); // ! updating the episode // ? getting the episode that we just created the episode-seen for @@ -300,22 +335,24 @@ EpisodeSeen.afterUpdate(async (instance, options) => { // ? for the current episode EpisodeSeen.findAll({ attributes: [ - [sequelize.fn('min', sequelize.col('date_seen')), 'minValue'], - [sequelize.fn('max', sequelize.col('date_seen')), 'maxValue'] + [sequelize.fn("min", sequelize.col("date_seen")), "minValue"], + [sequelize.fn("max", sequelize.col("date_seen")), "maxValue"], ], where: { - episode_id: instance.episode_id - } - }).then(result => { - let update = {}; - update.date_first_seen = result[0].dataValues.minValue; - update.date_last_seen = result[0].dataValues.maxValue; - episode.update(update); - }).catch(err => { - console.error('Error:', err); - }); + episode_id: instance.episode_id, + }, + }) + .then((result) => { + let update = {}; + update.date_first_seen = result[0].dataValues.minValue; + update.date_last_seen = result[0].dataValues.maxValue; + episode.update(update); + }) + .catch((err) => { + console.error("Error:", err); + }); } catch (error) { - console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error) + console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error); } }); @@ -331,11 +368,9 @@ EpisodeSeen.afterDestroy(async (instance, options) => { // ? and the last one to: date_last_seen const episodeSeens = await EpisodeSeen.findAll({ where: { - entry_id: instance.entry_id + entry_id: instance.entry_id, }, - order: [ - ['date_seen', 'ASC'] - ] + order: [["date_seen", "ASC"]], }); let update = {}; @@ -362,11 +397,9 @@ EpisodeSeen.afterDestroy(async (instance, options) => { // ? and the last one to: date_last_seen const episodeSeens2 = await EpisodeSeen.findAll({ where: { - episode_id: instance.episode_id + episode_id: instance.episode_id, }, - order: [ - ['date_seen', 'ASC'] - ] + order: [["date_seen", "ASC"]], }); let episodeUpdate = {}; @@ -378,12 +411,13 @@ EpisodeSeen.afterDestroy(async (instance, options) => { episodeUpdate.date_last_seen = null; } else { episodeUpdate.date_first_seen = episodeSeens2[0].date_seen; - episodeUpdate.date_last_seen = episodeSeens2[episodeSeens2.length - 1].date_seen; + episodeUpdate.date_last_seen = + episodeSeens2[episodeSeens2.length - 1].date_seen; } // * updating the episode await episode.update(episodeUpdate); } catch (error) { - console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error) + console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error); } -}); \ No newline at end of file +}); diff --git a/backend/controllers/aiQueryController.js b/backend/controllers/aiQueryController.js index 56532a0..557a82b 100644 --- a/backend/controllers/aiQueryController.js +++ b/backend/controllers/aiQueryController.js @@ -1,19 +1,19 @@ -const { Op } = require('sequelize'); -const sequelize = require('../config/database'); -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 Genre = require('../models/Genre'); -const Collection = require('../models/Collection'); -const Credit = require('../models/Credit'); -const People = require('../models/People'); -const Network = require('../models/Network'); -const Media = require('../models/Media'); -const asyncWrapper = require('../utils/asyncWrapper'); +const { Op } = require("sequelize"); +const sequelize = require("../config/database"); +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 Genre = require("../models/Genre"); +const Collection = require("../models/Collection"); +const Credit = require("../models/Credit"); +const People = require("../models/People"); +const Network = require("../models/Network"); +const Media = require("../models/Media"); +const asyncWrapper = require("../utils/asyncWrapper"); // ─── Shared Helper ────────────────────────────────────────────────────────── @@ -29,14 +29,13 @@ function formatEntryBrief(entry) { is_favorite: entry.favorit, is_on_watchlist: entry.watchlist, rating: entry.entryRating || null, - genres: entry.genres || [] + genres: entry.genres || [], }; } // ─── Controller ───────────────────────────────────────────────────────────── class AiQueryController { - constructor() { if (!AiQueryController.instance) { AiQueryController.instance = this; @@ -51,39 +50,73 @@ class AiQueryController { // Step 1: Get the last N EntrySeen IDs for movies (simple query, no genre joins) const seenIds = await EntrySeen.findAll({ - attributes: ['id'], - include: [{ - model: Entry, - as: 'entry', - attributes: [], - where: { is_tvseries: false, hidden: false } - }], - order: [['date_seen', 'DESC'], ['id', 'DESC']], - limit + attributes: ["id"], + include: [ + { + model: Entry, + as: "entry", + attributes: [], + where: { is_tvseries: false, hidden: false }, + }, + ], + order: [ + ["date_seen", "DESC"], + ["id", "DESC"], + ], + limit, }); if (seenIds.length === 0) { return res.status(200).json([]); } - const idList = seenIds.map(s => s.id); + const idList = seenIds.map((s) => s.id); // Step 2: Fetch full data for those IDs with all joins const entries = await EntrySeen.findAll({ where: { id: idList }, - include: [{ - model: Entry, - as: 'entry', - include: [ - { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, - { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } - ], - attributes: ['id', 'title', 'is_tvseries', 'poster_path', 'banner_path', 'runtime', 'release_date', 'favorit', 'watchlist'] - }], - order: [['date_seen', 'DESC'], ['id', 'DESC']] + include: [ + { + model: Entry, + as: "entry", + include: [ + { + model: EntryRating, + as: "entryRating", + attributes: [ + "user_rating", + "tmdb_rating", + "imdb_rating", + "rotten_tomatoes_rating", + ], + }, + { + model: Genre, + as: "genres", + attributes: ["id", "name"], + through: { attributes: [] }, + }, + ], + attributes: [ + "id", + "title", + "is_tvseries", + "poster_path", + "banner_path", + "runtime", + "release_date", + "favorit", + "watchlist", + ], + }, + ], + order: [ + ["date_seen", "DESC"], + ["id", "DESC"], + ], }); - const result = entries.map(es => ({ + const result = entries.map((es) => ({ watch_id: es.id, date_watched: es.date_seen, seen_with: es.seen_with, @@ -97,8 +130,8 @@ class AiQueryController { release_date: es.entry.release_date, is_favorite: es.entry.favorit, rating: es.entry.entryRating || null, - genres: es.entry.genres || [] - } + genres: es.entry.genres || [], + }, })); res.status(200).json(result); @@ -111,56 +144,87 @@ class AiQueryController { // Step 1: Get the last N EpisodeSeen IDs (simple query, no nested joins) const seenIds = await EpisodeSeen.findAll({ - attributes: ['id'], - include: [{ - model: Episode, - as: 'episode', - attributes: [], - include: [{ - model: Season, - as: 'season', + attributes: ["id"], + include: [ + { + model: Episode, + as: "episode", attributes: [], - include: [{ - model: Entry, - as: 'entry', - attributes: [], - where: { hidden: false } - }] - }] - }], - order: [['date_seen', 'DESC'], ['id', 'DESC']], - limit + include: [ + { + model: Season, + as: "season", + attributes: [], + include: [ + { + model: Entry, + as: "entry", + attributes: [], + where: { hidden: false }, + }, + ], + }, + ], + }, + ], + order: [ + ["date_seen", "DESC"], + ["id", "DESC"], + ], + limit, }); if (seenIds.length === 0) { return res.status(200).json([]); } - const idList = seenIds.map(s => s.id); + const idList = seenIds.map((s) => s.id); // Step 2: Fetch full data for those IDs with all joins const records = await EpisodeSeen.findAll({ where: { id: idList }, - include: [{ - model: Episode, - as: 'episode', - attributes: ['id', 'name', 'episode_number', 'runtime', 'still_path', 'air_date'], - include: [{ - model: Season, - as: 'season', - attributes: ['id', 'name', 'season_number'], - include: [{ - model: Entry, - as: 'entry', - attributes: ['id', 'title', 'is_tvseries', 'poster_path', 'banner_path'], - where: { hidden: false } - }] - }] - }], - order: [['date_seen', 'DESC'], ['id', 'DESC']] + include: [ + { + model: Episode, + as: "episode", + attributes: [ + "id", + "name", + "episode_number", + "runtime", + "still_path", + "air_date", + ], + include: [ + { + model: Season, + as: "season", + attributes: ["id", "name", "season_number"], + include: [ + { + model: Entry, + as: "entry", + attributes: [ + "id", + "title", + "is_tvseries", + "poster_path", + "banner_path", + ], + where: { hidden: false }, + }, + ], + }, + ], + }, + ], + order: [ + ["date_seen", "DESC"], + ["id", "DESC"], + ], }); - const result = records.map(es => ({ + const result = records.map((es) => ({ watch_id: es.id, date_watched: es.date_seen, seen_with: es.seen_with, @@ -170,18 +234,23 @@ class AiQueryController { episode_number: es.episode.episode_number, runtime: es.episode.runtime, still_path: es.episode.still_path, - air_date: es.episode.air_date + air_date: es.episode.air_date, }, - season: es.episode.season ? { - id: es.episode.season.id, - name: es.episode.season.name, - season_number: es.episode.season.season_number - } : null, - series: es.episode.season && es.episode.season.entry ? { - id: es.episode.season.entry.id, - title: es.episode.season.entry.title, - poster_path: es.episode.season.entry.poster_path - } : null + season: es.episode.season + ? { + id: es.episode.season.id, + name: es.episode.season.name, + season_number: es.episode.season.season_number, + } + : null, + series: + es.episode.season && es.episode.season.entry + ? { + id: es.episode.season.entry.id, + title: es.episode.season.entry.title, + poster_path: es.episode.season.entry.poster_path, + } + : null, })); res.status(200).json(result); @@ -193,10 +262,24 @@ class AiQueryController { const entries = await Entry.findAll({ where: { watchlist: true, hidden: false }, include: [ - { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, - { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } + { + model: EntryRating, + as: "entryRating", + attributes: [ + "user_rating", + "tmdb_rating", + "imdb_rating", + "rotten_tomatoes_rating", + ], + }, + { + model: Genre, + as: "genres", + attributes: ["id", "name"], + through: { attributes: [] }, + }, ], - order: [['updatedAt', 'DESC']] + order: [["updatedAt", "DESC"]], }); res.status(200).json(entries.map(formatEntryBrief)); @@ -208,10 +291,24 @@ class AiQueryController { const entries = await Entry.findAll({ where: { favorit: true, hidden: false }, include: [ - { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, - { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } + { + model: EntryRating, + as: "entryRating", + attributes: [ + "user_rating", + "tmdb_rating", + "imdb_rating", + "rotten_tomatoes_rating", + ], + }, + { + model: Genre, + as: "genres", + attributes: ["id", "name"], + through: { attributes: [] }, + }, ], - order: [['updatedAt', 'DESC']] + order: [["updatedAt", "DESC"]], }); res.status(200).json(entries.map(formatEntryBrief)); @@ -220,26 +317,68 @@ class AiQueryController { // ── Task 6: Library Overview ───────────────────────────────────────────── getLibraryOverview = asyncWrapper(async (req, res) => { - const [movieCount, seriesCount, totalEntries, movieWatchTime, seriesWatchTime, - movieSeenCount, episodeSeenCount, genreCount] = await Promise.all([ + const [ + movieCount, + seriesCount, + totalEntries, + movieWatchTime, + seriesWatchTime, + movieSeenCount, + episodeSeenCount, + genreCount, + ] = await Promise.all([ Entry.count({ where: { is_tvseries: false, hidden: false } }), Entry.count({ where: { is_tvseries: true, hidden: false } }), Entry.count({ where: { hidden: false } }), EntrySeen.findOne({ - include: [{ model: Entry, as: 'entry', attributes: [], where: { hidden: false } }], - attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'totalMinutes']] + include: [ + { + model: Entry, + as: "entry", + attributes: [], + where: { hidden: false }, + }, + ], + attributes: [ + [ + sequelize.fn( + "COALESCE", + sequelize.fn("SUM", sequelize.col("runtime")), + 0, + ), + "totalMinutes", + ], + ], }), EpisodeSeen.findOne({ - include: [{ model: Episode, as: 'episode', attributes: [] }], - attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'totalMinutes']] + include: [{ model: Episode, as: "episode", attributes: [] }], + attributes: [ + [ + sequelize.fn( + "COALESCE", + sequelize.fn("SUM", sequelize.col("runtime")), + 0, + ), + "totalMinutes", + ], + ], + }), + EntrySeen.count({ + include: [ + { + model: Entry, + as: "entry", + where: { hidden: false }, + attributes: [], + }, + ], }), - EntrySeen.count({ include: [{ model: Entry, as: 'entry', where: { hidden: false }, attributes: [] }] }), EpisodeSeen.count(), Entry.count({ distinct: true, - include: [{ model: Genre, as: 'genres', attributes: [] }], - attributes: [] - }) + include: [{ model: Genre, as: "genres", attributes: [] }], + attributes: [], + }), ]); res.status(200).json({ @@ -251,8 +390,8 @@ class AiQueryController { total_genres: genreCount, total_watch_time_minutes: { movies: parseInt(movieWatchTime.dataValues.totalMinutes) || 0, - series: parseInt(seriesWatchTime.dataValues.totalMinutes) || 0 - } + series: parseInt(seriesWatchTime.dataValues.totalMinutes) || 0, + }, }); }); @@ -267,24 +406,38 @@ class AiQueryController { if (q) { where.title = { [Op.like]: `%${q}%` }; } - if (type === 'movie') where.is_tvseries = false; - if (type === 'series') where.is_tvseries = true; - if (watchlist === 'true') where.watchlist = true; - if (favorite === 'true') where.favorit = true; + if (type === "movie") where.is_tvseries = false; + if (type === "series") where.is_tvseries = true; + if (watchlist === "true") where.watchlist = true; + if (favorite === "true") where.favorit = true; const entries = await Entry.findAll({ where, include: [ - { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating', 'imdb_rating', 'rotten_tomatoes_rating'] }, - { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } } + { + model: EntryRating, + as: "entryRating", + attributes: [ + "user_rating", + "tmdb_rating", + "imdb_rating", + "rotten_tomatoes_rating", + ], + }, + { + model: Genre, + as: "genres", + attributes: ["id", "name"], + through: { attributes: [] }, + }, ], - order: [['title', 'ASC']], - limit + order: [["title", "ASC"]], + limit, }); if (genre) { - const filtered = entries.filter(e => - e.genres.some(g => g.name.toLowerCase() === genre.toLowerCase()) + const filtered = entries.filter((e) => + e.genres.some((g) => g.name.toLowerCase() === genre.toLowerCase()), ); return res.status(200).json(filtered.map(formatEntryBrief)); } @@ -296,7 +449,9 @@ class AiQueryController { getUpcoming = asyncWrapper(async (req, res) => { const today = new Date(); - const thirtyDaysLater = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000); + const thirtyDaysLater = new Date( + today.getTime() + 30 * 24 * 60 * 60 * 1000, + ); const [upcomingMovies, nextEpisodes] = await Promise.all([ Entry.findAll({ @@ -304,43 +459,54 @@ class AiQueryController { is_tvseries: false, release_date: { [Op.gte]: today }, hidden: false, - showInCalendar: true + showInCalendar: true, }, - attributes: ['id', 'title', 'release_date', 'poster_path', 'banner_path', 'runtime'], - order: [['release_date', 'ASC']], - limit: 20 + attributes: [ + "id", + "title", + "release_date", + "poster_path", + "banner_path", + "runtime", + ], + order: [["release_date", "ASC"]], + limit: 20, }), Episode.findAll({ where: { - air_date: { [Op.gte]: today, [Op.lte]: thirtyDaysLater } + air_date: { [Op.gte]: today, [Op.lte]: thirtyDaysLater }, }, - attributes: ['id', 'name', 'episode_number', 'air_date', 'still_path'], - include: [{ - model: Season, - as: 'season', - attributes: ['id', 'name', 'season_number', 'entry_id'], - include: [{ - model: Entry, - as: 'entry', - attributes: ['id', 'title', 'poster_path', 'is_tvseries'], - where: { hidden: false, showInCalendar: true } - }] - }], - order: [['air_date', 'ASC']], - limit: 20 - }) + attributes: ["id", "name", "episode_number", "air_date", "still_path"], + include: [ + { + model: Season, + as: "season", + attributes: ["id", "name", "season_number", "entry_id"], + include: [ + { + model: Entry, + as: "entry", + attributes: ["id", "title", "poster_path", "is_tvseries"], + where: { hidden: false, showInCalendar: true }, + }, + ], + }, + ], + order: [["air_date", "ASC"]], + limit: 20, + }), ]); res.status(200).json({ - upcoming_movies: upcomingMovies.map(e => ({ + upcoming_movies: upcomingMovies.map((e) => ({ id: e.id, title: e.title, release_date: e.release_date, poster_path: e.poster_path, banner_path: e.banner_path, - runtime: e.runtime + runtime: e.runtime, })), - upcoming_episodes: nextEpisodes.map(ep => ({ + upcoming_episodes: nextEpisodes.map((ep) => ({ id: ep.id, name: ep.name, episode_number: ep.episode_number, @@ -349,8 +515,8 @@ class AiQueryController { series_title: ep.season?.entry?.title, series_id: ep.season?.entry?.id, season_number: ep.season?.season_number, - season_name: ep.season?.name - })) + season_name: ep.season?.name, + })), }); }); @@ -361,35 +527,88 @@ class AiQueryController { const entry = await Entry.findByPk(id, { include: [ - { model: EntryId, as: 'entryId', attributes: { exclude: ['id', 'entry_id'] } }, - { model: EntryRating, as: 'entryRating', attributes: { exclude: ['id', 'entry_id'] } }, - { model: Genre, as: 'genres', attributes: ['id', 'name'], through: { attributes: [] } }, - { model: Network, as: 'networks', attributes: ['id', 'name'], through: { attributes: [] } }, - { model: Collection, as: 'collections', attributes: ['id', 'name', 'isUserCollection', 'description'], through: { attributes: [] } }, { - model: Credit, as: 'credits', limit: 20, - include: [{ model: People, as: 'person', attributes: ['id', 'name', 'profile_path', 'known_for_department'] }] + model: EntryId, + as: "entryId", + attributes: { exclude: ["id", "entry_id"] }, }, { - model: Season, as: 'seasons', - include: [{ - model: Episode, as: 'episodes', - attributes: ['id', 'name', 'episode_number', 'runtime', 'air_date', 'still_path', 'overview'] - }] + model: EntryRating, + as: "entryRating", + attributes: { exclude: ["id", "entry_id"] }, }, - { model: Media, as: 'medias', where: { isSelected: true }, required: false } - ] + { + model: Genre, + as: "genres", + attributes: ["id", "name"], + through: { attributes: [] }, + }, + { + model: Network, + as: "networks", + attributes: ["id", "name"], + through: { attributes: [] }, + }, + { + model: Collection, + as: "collections", + attributes: ["id", "name", "isUserCollection", "description"], + through: { attributes: [] }, + }, + { + model: Credit, + as: "credits", + limit: 20, + include: [ + { + model: People, + as: "person", + attributes: [ + "id", + "name", + "profile_path", + "known_for_department", + ], + }, + ], + }, + { + model: Season, + as: "seasons", + include: [ + { + model: Episode, + as: "episodes", + attributes: [ + "id", + "name", + "episode_number", + "runtime", + "air_date", + "still_path", + "overview", + ], + }, + ], + }, + { + model: Media, + as: "medias", + where: { isSelected: true }, + required: false, + }, + ], }); if (!entry) { - return res.status(404).json({ error: 'Entry not found' }); + return res.status(404).json({ error: "Entry not found" }); } // Also get watch history const watchHistory = await EntrySeen.findAll({ where: { entry_id: id }, - order: [['date_seen', 'DESC']], - limit: 50 + order: [["date_seen", "DESC"]], + limit: 50, }); const result = entry.toJSON(); @@ -402,22 +621,26 @@ class AiQueryController { getGenreBreakdown = asyncWrapper(async (req, res) => { const genres = await Genre.findAll({ - include: [{ - model: Entry, - as: 'entries', - attributes: ['id', 'runtime', 'is_tvseries'], - through: { attributes: [] }, - where: { hidden: false } - }] + include: [ + { + model: Entry, + as: "entries", + attributes: ["id", "runtime", "is_tvseries"], + through: { attributes: [] }, + where: { hidden: false }, + }, + ], }); - const result = genres.map(g => ({ - id: g.id, - name: g.name, - entry_count: g.entries.length, - movie_count: g.entries.filter(e => !e.is_tvseries).length, - series_count: g.entries.filter(e => e.is_tvseries).length - })).filter(g => g.entry_count > 0) + const result = genres + .map((g) => ({ + id: g.id, + name: g.name, + entry_count: g.entries.length, + movie_count: g.entries.filter((e) => !e.is_tvseries).length, + series_count: g.entries.filter((e) => e.is_tvseries).length, + })) + .filter((g) => g.entry_count > 0) .sort((a, b) => b.entry_count - a.entry_count); res.status(200).json(result); @@ -427,26 +650,37 @@ class AiQueryController { getAllCollections = asyncWrapper(async (req, res) => { const collections = await Collection.findAll({ - attributes: ['id', 'name', 'description', 'isUserCollection', 'posterPath', 'backdropPath'], - include: [{ - model: Entry, - as: 'entries', - attributes: ['id'], - through: { attributes: [] }, - required: false - }], - order: [['name', 'ASC']] + attributes: [ + "id", + "name", + "description", + "isUserCollection", + "posterPath", + "backdropPath", + ], + include: [ + { + model: Entry, + as: "entries", + attributes: ["id"], + through: { attributes: [] }, + required: false, + }, + ], + order: [["name", "ASC"]], }); - res.status(200).json(collections.map(c => ({ - id: c.id, - name: c.name, - description: c.description, - is_user_collection: c.isUserCollection, - poster_path: c.posterPath, - backdrop_path: c.backdropPath, - entry_count: c.entries.length - }))); + res.status(200).json( + collections.map((c) => ({ + id: c.id, + name: c.name, + description: c.description, + is_user_collection: c.isUserCollection, + poster_path: c.posterPath, + backdrop_path: c.backdropPath, + entry_count: c.entries.length, + })), + ); }); // ── Task 12: Collection Detail ─────────────────────────────────────────── @@ -455,19 +689,30 @@ class AiQueryController { const { id } = req.params; const collection = await Collection.findByPk(id, { - include: [{ - model: Entry, - as: 'entries', - through: { attributes: ['order'] }, - include: [ - { model: EntryRating, as: 'entryRating', attributes: ['user_rating', 'tmdb_rating'] }, - { model: Genre, as: 'genres', attributes: ['name'], through: { attributes: [] } } - ] - }] + include: [ + { + model: Entry, + as: "entries", + through: { attributes: ["order"] }, + include: [ + { + model: EntryRating, + as: "entryRating", + attributes: ["user_rating", "tmdb_rating"], + }, + { + model: Genre, + as: "genres", + attributes: ["name"], + through: { attributes: [] }, + }, + ], + }, + ], }); if (!collection) { - return res.status(404).json({ error: 'Collection not found' }); + return res.status(404).json({ error: "Collection not found" }); } res.status(200).json(collection); @@ -479,26 +724,53 @@ class AiQueryController { const seriesWithSeen = await Entry.findAll({ where: { is_tvseries: true, hidden: false }, include: [ - { model: EpisodeSeen, as: 'episodeSeens', attributes: [], required: true, duplicating: false }, { - model: Season, as: 'seasons', - include: [{ - model: Episode, as: 'episodes', - include: [{ model: EpisodeSeen, as: 'episodeSeens', attributes: ['id'], required: false }] - }] + model: EpisodeSeen, + as: "episodeSeens", + attributes: [], + required: true, + duplicating: false, }, - { model: EntryRating, as: 'entryRating', attributes: ['user_rating'] } + { + model: Season, + as: "seasons", + include: [ + { + model: Episode, + as: "episodes", + include: [ + { + model: EpisodeSeen, + as: "episodeSeens", + attributes: ["id"], + required: false, + }, + ], + }, + ], + }, + { model: EntryRating, as: "entryRating", attributes: ["user_rating"] }, ], - distinct: true + distinct: true, }); const inProgress = seriesWithSeen - .map(s => { - const totalEpisodes = s.seasons?.reduce((sum, season) => - sum + (season.episodes?.length || 0), 0) || 0; - const seenEpisodes = s.seasons?.reduce((sum, season) => - sum + (season.episodes?.reduce((es, ep) => - es + ((ep.episodeSeens?.length || 0) > 0 ? 1 : 0), 0) || 0), 0) || 0; + .map((s) => { + const totalEpisodes = + s.seasons?.reduce( + (sum, season) => sum + (season.episodes?.length || 0), + 0, + ) || 0; + const seenEpisodes = + s.seasons?.reduce( + (sum, season) => + sum + + (season.episodes?.reduce( + (es, ep) => es + ((ep.episodeSeens?.length || 0) > 0 ? 1 : 0), + 0, + ) || 0), + 0, + ) || 0; return { id: s.id, @@ -508,11 +780,14 @@ class AiQueryController { user_rating: s.entryRating?.user_rating || null, total_episodes: totalEpisodes, seen_episodes: seenEpisodes, - progress_pct: totalEpisodes > 0 ? Math.round((seenEpisodes / totalEpisodes) * 100) : 0, - is_complete: totalEpisodes > 0 && seenEpisodes >= totalEpisodes + progress_pct: + totalEpisodes > 0 + ? Math.round((seenEpisodes / totalEpisodes) * 100) + : 0, + is_complete: totalEpisodes > 0 && seenEpisodes >= totalEpisodes, }; }) - .filter(s => !s.is_complete && s.seen_episodes > 0) + .filter((s) => !s.is_complete && s.seen_episodes > 0) .sort((a, b) => b.progress_pct - a.progress_pct); res.status(200).json(inProgress); @@ -523,57 +798,117 @@ class AiQueryController { getWatchTimeStats = asyncWrapper(async (req, res) => { const year = parseInt(req.query.year) || new Date().getFullYear(); - const [totalMovieMinutes, totalEpisodeMinutes, - monthlyMovieMinutes, monthlyEpisodeMinutes] = await Promise.all([ + const [ + totalMovieMinutes, + totalEpisodeMinutes, + monthlyMovieMinutes, + monthlyEpisodeMinutes, + ] = await Promise.all([ EntrySeen.findOne({ - include: [{ model: Entry, as: 'entry', where: { hidden: false }, attributes: [] }], - attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'total']] + include: [ + { + model: Entry, + as: "entry", + where: { hidden: false }, + attributes: [], + }, + ], + attributes: [ + [ + sequelize.fn( + "COALESCE", + sequelize.fn("SUM", sequelize.col("runtime")), + 0, + ), + "total", + ], + ], }), EpisodeSeen.findOne({ - include: [{ model: Episode, as: 'episode', attributes: [] }], - attributes: [[sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('runtime')), 0), 'total']] + include: [{ model: Episode, as: "episode", attributes: [] }], + attributes: [ + [ + sequelize.fn( + "COALESCE", + sequelize.fn("SUM", sequelize.col("runtime")), + 0, + ), + "total", + ], + ], }), EntrySeen.findAll({ - include: [{ model: Entry, as: 'entry', where: { hidden: false }, attributes: [] }], - attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + include: [ + { + model: Entry, + as: "entry", + where: { hidden: false }, + attributes: [], + }, ], - where: sequelize.where(sequelize.fn('YEAR', sequelize.col('date_seen')), year), - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + attributes: [ + [sequelize.fn("MONTH", sequelize.col("date_seen")), "month"], + [sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"], + ], + where: sequelize.where( + sequelize.fn("YEAR", sequelize.col("date_seen")), + year, + ), + group: [sequelize.fn("MONTH", sequelize.col("date_seen"))], }), EpisodeSeen.findAll({ - include: [{ model: Episode, as: 'episode', attributes: [] }], + include: [{ model: Episode, as: "episode", attributes: [] }], attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + [sequelize.fn("MONTH", sequelize.col("date_seen")), "month"], + [sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"], ], - where: sequelize.where(sequelize.fn('YEAR', sequelize.col('date_seen')), year), - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] - }) + where: sequelize.where( + sequelize.fn("YEAR", sequelize.col("date_seen")), + year, + ), + group: [sequelize.fn("MONTH", sequelize.col("date_seen"))], + }), ]); const totalMovies = parseInt(totalMovieMinutes.dataValues.total) || 0; const totalEpisodes = parseInt(totalEpisodeMinutes.dataValues.total) || 0; const totalMinutes = totalMovies + totalEpisodes; - const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; + const months = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ]; const monthlyMap = {}; for (let m = 1; m <= 12; m++) { - monthlyMap[m] = { month: months[m - 1], movies: 0, episodes: 0, total: 0 }; + monthlyMap[m] = { + month: months[m - 1], + movies: 0, + episodes: 0, + total: 0, + }; } - monthlyMovieMinutes.forEach(r => { + monthlyMovieMinutes.forEach((r) => { const m = parseInt(r.dataValues.month); monthlyMap[m].movies = parseInt(r.dataValues.watchTime) || 0; }); - monthlyEpisodeMinutes.forEach(r => { + monthlyEpisodeMinutes.forEach((r) => { const m = parseInt(r.dataValues.month); monthlyMap[m].episodes = parseInt(r.dataValues.watchTime) || 0; }); - const monthly = Object.values(monthlyMap).map(m => ({ + const monthly = Object.values(monthlyMap).map((m) => ({ ...m, - total: m.movies + m.episodes + total: m.movies + m.episodes, })); res.status(200).json({ @@ -582,7 +917,7 @@ class AiQueryController { total_watch_time_hours: Math.round((totalMinutes / 60) * 10) / 10, movies_minutes: totalMovies, episodes_minutes: totalEpisodes, - monthly + monthly, }); }); @@ -592,26 +927,36 @@ class AiQueryController { const { id } = req.params; const person = await People.findByPk(id, { - include: [{ - model: Credit, - as: 'roles', - include: [{ - model: Entry, - as: 'entry', - attributes: ['id', 'title', 'is_tvseries', 'poster_path', 'release_date', 'favorit'], - where: { hidden: false }, - required: false - }] - }] + include: [ + { + model: Credit, + as: "roles", + include: [ + { + model: Entry, + as: "entry", + attributes: [ + "id", + "title", + "is_tvseries", + "poster_path", + "release_date", + "favorit", + ], + where: { hidden: false }, + required: false, + }, + ], + }, + ], }); if (!person) { - return res.status(404).json({ error: 'Person not found' }); + return res.status(404).json({ error: "Person not found" }); } res.status(200).json(person); }); - } module.exports = new AiQueryController(); diff --git a/backend/controllers/collectionController.js b/backend/controllers/collectionController.js index 01146a4..5c22a5f 100644 --- a/backend/controllers/collectionController.js +++ b/backend/controllers/collectionController.js @@ -1,24 +1,23 @@ -const { Sequelize } = require('sequelize'); -const Collection = require('../models/Collection'); -const UserCollectionEntry = require('../models/UserCollectionEntry'); -const Entry = require('../models/Entry'); -const EntryId = require('../models/EntryId'); -const EntryRating = require('../models/EntryRating'); -const Season = require('../models/Season'); -const Genre = require('../models/Genre'); -const Media = require('../models/Media'); +const { Sequelize } = require("sequelize"); +const Collection = require("../models/Collection"); +const UserCollectionEntry = require("../models/UserCollectionEntry"); +const Entry = require("../models/Entry"); +const EntryId = require("../models/EntryId"); +const EntryRating = require("../models/EntryRating"); +const Season = require("../models/Season"); +const Genre = require("../models/Genre"); +const Media = require("../models/Media"); -const { logToFile } = require('../services/logService'); -const collectionManager = require('../services/collectionManager'); -const mediaOptimizerService = require('../services/mediaOptimizerService'); -const collectionService = require('../services/collectionService'); +const { logToFile } = require("../services/logService"); +const collectionManager = require("../services/collectionManager"); +const mediaOptimizerService = require("../services/mediaOptimizerService"); +const collectionService = require("../services/collectionService"); const _mediaOptimizerService = mediaOptimizerService; const _collectionManager = collectionManager; const _collectionService = collectionService; class CollectionController { - constructor() { if (!CollectionController.instance) { CollectionController.instance = this; @@ -41,37 +40,41 @@ class CollectionController { include: [ { model: Entry, - as: 'entries', + as: "entries", include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, - { model: Genre, as: 'genres' }, + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, + { model: Genre, as: "genres" }, ], through: { model: UserCollectionEntry, - attributes: ['order'], // attributes (to include) from the join model + attributes: ["order"], // attributes (to include) from the join model }, }, - { model: Media, as: 'medias' }, + { model: Media, as: "medias" }, ], - order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order + order: [ + [Sequelize.literal("`entries->UserCollectionEntry`.`order`"), "ASC"], + ], // sort by 'order' in ascending order }); if (collection) { const collectionData = collection.get({ plain: true }); for (let i = 0; i < collectionData.entries.length; i++) { - const genres = collectionData.entries[i].genres.map(genre => genre.name); - collectionData.entries[i].genres = genres + const genres = collectionData.entries[i].genres.map( + (genre) => genre.name, + ); + collectionData.entries[i].genres = genres; } res.status(200).json(collectionData); } else { - res.status(404).json({ message: 'UserCollection not found' }); + res.status(404).json({ message: "UserCollection not found" }); } } catch (error) { - console.log(`Error getting collection info: `, error) + console.log(`Error getting collection info: `, error); res.status(500).json({ error: error.message }); } } @@ -81,7 +84,13 @@ class CollectionController { try { const { name, description, userRating, posterPath } = req.body; const isUserCollection = true; - const newUserCollection = await Collection.create({ name, description, userRating, posterPath, isUserCollection }); + const newUserCollection = await Collection.create({ + name, + description, + userRating, + posterPath, + isUserCollection, + }); res.status(201).json(newUserCollection); } catch (error) { res.status(400).json({ error: error.message }); @@ -95,7 +104,9 @@ class CollectionController { const { name, description, userRating } = req.body; const posterFile = req.files.poster ? req.files.poster[0] : undefined; - const backdropFile = req.files.backdrop ? req.files.backdrop[0] : undefined; + const backdropFile = req.files.backdrop + ? req.files.backdrop[0] + : undefined; let posterPath = posterFile ? posterFile.filename : undefined; let backdropPath = backdropFile ? backdropFile.filename : undefined; @@ -109,90 +120,113 @@ class CollectionController { if (posterPath) { // ? generating preview - _mediaOptimizerService.doGeneratePreview("collections", 'posters', posterPath).then((result) => { - const msg = `Collection Service | Generated Collection Preview`; - logToFile(msg); - }).catch((err) => { - const msg = `Collection Service | Error Generating Collection Preview`; - logToFile(msg); - logToFile(err); - }); + _mediaOptimizerService + .doGeneratePreview("collections", "posters", posterPath) + .then((result) => { + const msg = `Collection Service | Generated Collection Preview`; + logToFile(msg); + }) + .catch((err) => { + const msg = `Collection Service | Error Generating Collection Preview`; + logToFile(msg); + logToFile(err); + }); // Deselect existing posters for this collection await Media.update( { isSelected: false }, - { where: { mediaable: 'collection', mediaableId: collectionId, type: 'poster', isSelected: true } } + { + where: { + mediaable: "collection", + mediaableId: collectionId, + type: "poster", + isSelected: true, + }, + }, ); await Media.create({ - mediaable: 'collection', + mediaable: "collection", mediaableId: collectionId, - type: 'poster', + type: "poster", path: posterPath, isLocal: true, isSelected: true, - isCustom: true - }) + isCustom: true, + }); } if (backdropPath) { // ? generating preview - _mediaOptimizerService.doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => { - const msg = `Collection Routes | Generated Collection Preview`; - logToFile(msg); - }).catch((err) => { - const msg = `Collection Routes | Error Generating Collection Preview`; - logToFile(msg); - logToFile(err); - }); + _mediaOptimizerService + .doGeneratePreview("collections", "backdrops", backdropPath) + .then((result) => { + const msg = `Collection Routes | Generated Collection Preview`; + logToFile(msg); + }) + .catch((err) => { + const msg = `Collection Routes | Error Generating Collection Preview`; + logToFile(msg); + logToFile(err); + }); // Deselect existing backdrops for this collection await Media.update( { isSelected: false }, - { where: { mediaable: 'collection', mediaableId: collectionId, type: 'backdrop', isSelected: true } } + { + where: { + mediaable: "collection", + mediaableId: collectionId, + type: "backdrop", + isSelected: true, + }, + }, ); // ? inserting data await Media.create({ - mediaable: 'collection', + mediaable: "collection", mediaableId: collectionId, - type: 'backdrop', + type: "backdrop", path: backdropPath, isLocal: true, isSelected: true, - isCustom: true - }) + isCustom: true, + }); } const oldCollection = await Collection.findByPk(collectionId, { - include: [{ - model: Entry, - as: 'entries', - include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, - { model: Genre, as: 'genres' }, - ], - through: { - model: UserCollectionEntry, - attributes: ['order'], // attributes (to include) from the join model + include: [ + { + model: Entry, + as: "entries", + include: [ + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, + { model: Genre, as: "genres" }, + ], + through: { + model: UserCollectionEntry, + attributes: ["order"], // attributes (to include) from the join model + }, }, - }, - { model: Media, as: 'medias' }, + { model: Media, as: "medias" }, ], - order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order + order: [ + [Sequelize.literal("`entries->UserCollectionEntry`.`order`"), "ASC"], + ], // sort by 'order' in ascending order }); if (!oldCollection) - res.status(404).json({ message: 'Collection not found' }); + res.status(404).json({ message: "Collection not found" }); await oldCollection.update(updateData); res.status(200).json(oldCollection); } catch (error) { - console.log(`UserCollection update (put) error: `, error) + console.log(`UserCollection update (put) error: `, error); res.status(500).json({ error: error.message }); } } @@ -202,21 +236,25 @@ class CollectionController { const collectionId = req.params.id; const oldCollection = await Collection.findByPk(collectionId); - const collection = await _collectionManager.fetchAndSaveCollection(oldCollection.tmdbId); + const collection = await _collectionManager.fetchAndSaveCollection( + oldCollection.tmdbId, + ); if (collection) { const collectionData = collection.get({ plain: true }); for (let i = 0; i < collectionData.entries.length; i++) { - const genres = collectionData.entries[i].genres.map(genre => genre.name); - collectionData.entries[i].genres = genres + const genres = collectionData.entries[i].genres.map( + (genre) => genre.name, + ); + collectionData.entries[i].genres = genres; } res.status(200).json(collectionData); } else { - res.status(404).json({ message: 'Collection not found' }); + res.status(404).json({ message: "Collection not found" }); } } catch (error) { - console.log(`UserCollection update (put) error: `, error) + console.log(`UserCollection update (put) error: `, error); res.status(500).json({ error: error.message }); } } @@ -231,37 +269,41 @@ class CollectionController { include: [ { model: Entry, - as: 'entries', + as: "entries", include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, - { model: Genre, as: 'genres' }, + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, + { model: Genre, as: "genres" }, ], through: { model: UserCollectionEntry, - attributes: ['order'], // attributes (to include) from the join model + attributes: ["order"], // attributes (to include) from the join model }, }, - { model: Media, as: 'medias' }, + { model: Media, as: "medias" }, ], - order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order + order: [ + [Sequelize.literal("`entries->UserCollectionEntry`.`order`"), "ASC"], + ], // sort by 'order' in ascending order }); if (collection) { const collectionData = collection.get({ plain: true }); for (let i = 0; i < collectionData.entries.length; i++) { - const genres = collectionData.entries[i].genres.map(genre => genre.name); - collectionData.entries[i].genres = genres + const genres = collectionData.entries[i].genres.map( + (genre) => genre.name, + ); + collectionData.entries[i].genres = genres; } res.status(200).json(collectionData); } else { - res.status(404).json({ message: 'Collection not found' }); + res.status(404).json({ message: "Collection not found" }); } } catch (error) { - console.log(`UserCollection update (put) error: `, error) + console.log(`UserCollection update (put) error: `, error); res.status(500).json({ error: error.message }); } } @@ -269,11 +311,13 @@ class CollectionController { // todo: move to collection service async deleteCollection(req, res) { try { - const deleted = await Collection.destroy({ where: { id: req.params.id } }); + const deleted = await Collection.destroy({ + where: { id: req.params.id }, + }); if (deleted) { res.status(204).send(); } else { - res.status(404).json({ message: 'UserCollection not found' }); + res.status(404).json({ message: "UserCollection not found" }); } } catch (error) { res.status(500).json({ error: error.message }); @@ -287,12 +331,15 @@ class CollectionController { const newUserCollectionEntry = await UserCollectionEntry.create({ user_collection_id: collectionId, - entry_id: entryId + entry_id: entryId, }); // ? set a default poster if none exists const userCollection = await Collection.findByPk(collectionId); - if (!userCollection.poster_path || userCollection.poster_path.trim() == '') { + if ( + !userCollection.poster_path || + userCollection.poster_path.trim() == "" + ) { const entry = await Entry.findByPk(entryId); userCollection.poster_path = entry.poster_path; await userCollection.save(); @@ -300,7 +347,7 @@ class CollectionController { res.status(201).json(newUserCollectionEntry); } catch (error) { - console.log(error) + console.log(error); res.status(400).json({ error: error.message }); } } @@ -315,18 +362,20 @@ class CollectionController { const collectionEntry = await UserCollectionEntry.findOne({ where: { user_collection_id: collectionId, - entry_id: entryId - } + entry_id: entryId, + }, }); if (!collectionEntry) { - res.status(404).json({ message: 'UserCollectionEntry not found.' }); + res.status(404).json({ message: "UserCollectionEntry not found." }); } // ? updating await collectionEntry.update({ order: newOrder }); - res.status(200).json({ message: 'UserCollectionEntry order updated successfully.' }); + res + .status(200) + .json({ message: "UserCollectionEntry order updated successfully." }); } catch (error) { console.log(`Error Updating UserCollectionEntry order: `, error); res.status(500).json({ error: error.message }); @@ -340,15 +389,15 @@ class CollectionController { const deleted = await UserCollectionEntry.findOne({ where: { user_collection_id: collectionId, - entry_id: entryId - } + entry_id: entryId, + }, }); if (deleted) { await deleted.destroy(); res.status(204).send(); } else { - res.status(404).json({ message: 'CollectionEntry not found.' }); + res.status(404).json({ message: "CollectionEntry not found." }); } } catch (error) { res.status(500).json({ error: error.message }); @@ -362,14 +411,19 @@ class CollectionController { try { const result = await sequelize.transaction(async (t) => { // Step 1: Create the userCollection - const newUserCollection = await Collection.create(listDetails, { transaction: t }); + const newUserCollection = await Collection.create(listDetails, { + transaction: t, + }); // Step 2: Add an entry to the newly created userCollection - const newUserCollectionEntry = await UserCollectionEntry.create({ - userCollectionId: newUserCollection.id, - entryId: entryId, - entryOrder: entryOrder - }, { transaction: t }); + const newUserCollectionEntry = await UserCollectionEntry.create( + { + userCollectionId: newUserCollection.id, + entryId: entryId, + entryOrder: entryOrder, + }, + { transaction: t }, + ); return { newUserCollection, newUserCollectionEntry }; }); @@ -377,11 +431,15 @@ class CollectionController { // If the transaction is successful, send back the created userCollection and entry relationship res.status(201).json(result); } catch (error) { - console.error('Failed to create userCollection and add entry:', error); - res.status(500).json({ message: 'Failed to create userCollection and add entry', error: error.message }); + console.error("Failed to create userCollection and add entry:", error); + res + .status(500) + .json({ + message: "Failed to create userCollection and add entry", + error: error.message, + }); } } - } module.exports = new CollectionController(); diff --git a/backend/controllers/entryController.js b/backend/controllers/entryController.js index 3b0c47b..5209bfa 100644 --- a/backend/controllers/entryController.js +++ b/backend/controllers/entryController.js @@ -1,16 +1,15 @@ -const EntryRating = require('../models/EntryRating'); -const collectionManager = require('../services/collectionManager'); -const entryManager = require('../services/entryManager'); +const EntryRating = require("../models/EntryRating"); +const collectionManager = require("../services/collectionManager"); +const entryManager = require("../services/entryManager"); const entryService = require("../services/entryService"); -const tmdbService = require('../services/tmdbService'); -const asyncWrapper = require('../utils/asyncWrapper'); +const tmdbService = require("../services/tmdbService"); +const asyncWrapper = require("../utils/asyncWrapper"); const _collectionManager = collectionManager; const _entryManager = entryManager; const _entryService = entryService; class EntryController { - constructor() { if (!EntryController.instance) { EntryController.instance = this; @@ -37,7 +36,10 @@ class EntryController { fetchAndSaveNewEntry = asyncWrapper(async (req, res) => { const { tmdb_id, is_tvserie } = req.body; - const createdEntry = await _entryManager.fetchAndSaveNewEntry(tmdb_id, is_tvserie); + const createdEntry = await _entryManager.fetchAndSaveNewEntry( + tmdb_id, + is_tvserie, + ); res.status(201).json(createdEntry); }); @@ -46,7 +48,11 @@ class EntryController { const { id } = req.params; const { entryData } = req.body; - const updatedEntry = await _entryService.updateEntryById(id, entryData, true); + const updatedEntry = await _entryService.updateEntryById( + id, + entryData, + true, + ); res.status(201).json(updatedEntry); }); @@ -56,7 +62,10 @@ class EntryController { const { id } = req.params; const { entryRatings } = req.body; - const updatedEntryRatings = await _entryService.updateEntryRatings(id, entryRatings); + const updatedEntryRatings = await _entryService.updateEntryRatings( + id, + entryRatings, + ); res.status(200).json(updatedEntryRatings); }); @@ -66,7 +75,10 @@ class EntryController { const { id } = req.params; const { entryIds } = req.body; - const updatedEntryIds = await _entryService.updateEntryRatings(id, entryIds); + const updatedEntryIds = await _entryService.updateEntryRatings( + id, + entryIds, + ); res.status(200).json(updatedEntryIds); }); @@ -90,10 +102,10 @@ class EntryController { getEntrySeasons = asyncWrapper(async (req, res) => { const { id } = req.params; - const seasons = await _entryService.getEntrySeasons(id) + const seasons = await _entryService.getEntrySeasons(id); if (seasons.length == 0) { - res.status(204).json({ message: 'Provided entry has no seasons' }); + res.status(204).json({ message: "Provided entry has no seasons" }); } res.status(200).json(seasons); @@ -110,7 +122,7 @@ class EntryController { refrechEntry = asyncWrapper(async (req, res, next) => { const { id } = req.params; - const entry = await _entryManager.refrechEntryById(id) + const entry = await _entryManager.refrechEntryById(id); res.status(201).json(entry); }); @@ -132,7 +144,8 @@ class EntryController { const { type } = req.params; const { page } = req.query; const data = await tmdbService.fetchTrending(type, page || 1); - if (!data) return res.status(500).json({ message: 'Failed to fetch trending data' }); + if (!data) + return res.status(500).json({ message: "Failed to fetch trending data" }); res.status(200).json(data); }); @@ -141,16 +154,19 @@ class EntryController { const { type } = req.params; const { page } = req.query; const data = await tmdbService.fetchPopular(type, page || 1); - if (!data) return res.status(500).json({ message: 'Failed to fetch popular data' }); + if (!data) + return res.status(500).json({ message: "Failed to fetch popular data" }); res.status(200).json(data); }); // * GET - TMDB SEARCH getTmdbSearch = asyncWrapper(async (req, res) => { const { query, page } = req.query; - if (!query) return res.status(400).json({ message: 'Query parameter is required' }); + if (!query) + return res.status(400).json({ message: "Query parameter is required" }); const data = await tmdbService.searchMulti(query, page || 1); - if (!data) return res.status(500).json({ message: 'Failed to search TMDB' }); + if (!data) + return res.status(500).json({ message: "Failed to search TMDB" }); res.status(200).json(data); }); @@ -159,7 +175,10 @@ class EntryController { const { type } = req.params; const { page } = req.query; const data = await tmdbService.fetchTopRated(type, page || 1); - if (!data) return res.status(500).json({ message: 'Failed to fetch top rated data' }); + if (!data) + return res + .status(500) + .json({ message: "Failed to fetch top rated data" }); res.status(200).json(data); }); @@ -167,16 +186,18 @@ class EntryController { getTmdbUpcoming = asyncWrapper(async (req, res) => { const { page } = req.query; const data = await tmdbService.fetchUpcoming(page || 1); - if (!data) return res.status(500).json({ message: 'Failed to fetch upcoming data' }); + if (!data) + return res.status(500).json({ message: "Failed to fetch upcoming data" }); res.status(200).json(data); }); // * GET - TMDB PREVIEW (fetch details without saving to library) getTmdbPreview = asyncWrapper(async (req, res) => { const { type, tmdbId } = req.params; - const is_tvserie = type === 'tv'; + const is_tvserie = type === "tv"; const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie); - if (!data) return res.status(404).json({ message: 'Entry not found on TMDB' }); + if (!data) + return res.status(404).json({ message: "Entry not found on TMDB" }); // Fetch credits in parallel const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie); @@ -187,10 +208,10 @@ class EntryController { for (const c of creditsData.cast) { credits.push({ id: c.credit_id || c.id, - cast_type: 'cast', + cast_type: "cast", character: is_tvserie - ? (c.roles?.[0]?.character || c.character || null) - : (c.character || null), + ? c.roles?.[0]?.character || c.character || null + : c.character || null, people_id: c.id, people: { id: c.id, @@ -208,9 +229,12 @@ class EntryController { title: data.title || data.name, original_title: data.original_title || data.original_name || null, release_date: data.release_date || data.first_air_date || null, - runtime: data.runtime || (data.episode_run_time?.[0]) || null, + runtime: data.runtime || data.episode_run_time?.[0] || null, storyline: data.overview || null, - country: data.origin_country?.[0] || data.production_countries?.[0]?.iso_3166_1 || null, + country: + data.origin_country?.[0] || + data.production_countries?.[0]?.iso_3166_1 || + null, is_tvseries: is_tvserie, status: data.status || null, poster_path: data.poster_path || null, diff --git a/backend/controllers/entrySeenController.js b/backend/controllers/entrySeenController.js index e510a93..16461af 100644 --- a/backend/controllers/entrySeenController.js +++ b/backend/controllers/entrySeenController.js @@ -1,8 +1,7 @@ const Entry = require("../models/Entry"); -const EntrySeen = require('../models/EntrySeen'); +const EntrySeen = require("../models/EntrySeen"); class EntrySeenController { - constructor() { if (!EntrySeenController.instance) { EntrySeenController.instance = this; @@ -19,7 +18,7 @@ class EntrySeenController { const entrySeen = await EntrySeen.findByPk(req.params.id); if (!entrySeen) { - res.status(404).json({ message: 'Entry seen record not found.' }); + res.status(404).json({ message: "Entry seen record not found." }); } res.status(200).json(entrySeen); @@ -35,7 +34,11 @@ class EntrySeenController { } // Create a new EntrySeen record - const newEntrySeen = await EntrySeen.create({ entry_id, date_seen, seen_with }); + const newEntrySeen = await EntrySeen.create({ + entry_id, + date_seen, + seen_with, + }); res.status(201).json(newEntrySeen); } @@ -43,26 +46,30 @@ class EntrySeenController { const { entryId } = req.params; const entrySeens = await EntrySeen.findAll({ where: { entry_id: entryId }, - order: [['date_seen', 'DESC']] + order: [["date_seen", "DESC"]], }); if (entrySeens.length > 0) { res.status(200).json(entrySeens); } else { - res.status(404).json({ message: 'No records found for the given entry ID.' }); + res + .status(404) + .json({ message: "No records found for the given entry ID." }); } - } async updateEntrySeen(req, res) { const { date_seen, seen_with } = req.body; - const updated = await EntrySeen.update({ date_seen, seen_with }, { where: { id: req.params.id } }); + const updated = await EntrySeen.update( + { date_seen, seen_with }, + { where: { id: req.params.id } }, + ); if (updated[0] > 0) { const updatedEntrySeen = await EntrySeen.findByPk(req.params.id); res.status(200).json(updatedEntrySeen); } else { - res.status(404).json({ message: 'Entry seen record not found.' }); + res.status(404).json({ message: "Entry seen record not found." }); } } @@ -70,7 +77,7 @@ class EntrySeenController { const entrySeen = await EntrySeen.findByPk(req.params.id); if (!entrySeen) - res.status(404).json({ message: 'Entry seen record not found.' }); + res.status(404).json({ message: "Entry seen record not found." }); const deleted = await entrySeen.destroy(); @@ -78,7 +85,6 @@ class EntrySeenController { res.status(204).send(); } } - } module.exports = new EntrySeenController(); diff --git a/backend/controllers/episodeController.js b/backend/controllers/episodeController.js index bae3a1c..c642190 100644 --- a/backend/controllers/episodeController.js +++ b/backend/controllers/episodeController.js @@ -3,7 +3,6 @@ const episodeService = require("../services/episodeService"); const _episodeService = episodeService; class EpisodeController { - constructor() { if (!EpisodeController.instance) { EpisodeController.instance = this; @@ -14,13 +13,15 @@ class EpisodeController { async getEpisodesBetweenDates(req, res) { const { startDate, endDate } = req.params; try { - const episodes = await _episodeService.getEpisodesBetweenDates(startDate, endDate) + const episodes = await _episodeService.getEpisodesBetweenDates( + startDate, + endDate, + ); res.status(200).json(episodes); } catch (error) { res.status(500).json({ error: error.message }); } } - } module.exports = new EpisodeController(); diff --git a/backend/controllers/episodeSeenController.js b/backend/controllers/episodeSeenController.js index f3b93db..64754a7 100644 --- a/backend/controllers/episodeSeenController.js +++ b/backend/controllers/episodeSeenController.js @@ -4,7 +4,6 @@ const EpisodeSeen = require("../models/EpisodeSeen"); const Season = require("../models/Season"); class EpisodeSeenController { - constructor() { if (!EpisodeSeenController.instance) { EpisodeSeenController.instance = this; @@ -26,7 +25,7 @@ class EpisodeSeenController { const episodeSeen = await EpisodeSeen.findByPk(req.params.id); if (!episodeSeen) { - res.status(404).json({ message: 'Episode seen record not found.' }); + res.status(404).json({ message: "Episode seen record not found." }); } res.status(200).json(episodeSeen); @@ -40,15 +39,18 @@ class EpisodeSeenController { const { entry_id, episode_id, date_seen, seen_with } = req.body; const entry = await Entry.findByPk(entry_id); - if (!entry) - return res.status(404).json({ error: "Entry not found" }); + if (!entry) return res.status(404).json({ error: "Entry not found" }); const episode = await Episode.findByPk(episode_id); - if (!episode) - return res.status(404).json({ error: "Episode not found" }); + if (!episode) return res.status(404).json({ error: "Episode not found" }); // Create a new EpisodeSeen record - const newEpisodeSeen = await EpisodeSeen.create({ entry_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); } catch (error) { res.status(400).json({ error: error.message }); @@ -61,13 +63,15 @@ class EpisodeSeenController { const { episodeId } = req.params; const episodeSeens = await EpisodeSeen.findAll({ where: { episode_id: episodeId }, - order: [['date_seen', 'DESC']] + 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 episode ID.' }); + res + .status(404) + .json({ message: "No records found for the given episode ID." }); } } catch (error) { res.status(500).json({ error: error.message }); @@ -79,24 +83,29 @@ class EpisodeSeenController { 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'], - }], + include: [ + { + model: Episode, + include: [ + { + model: Season, + attributes: ["season_number"], + }, + ], + attributes: ["episode_number"], + }, + ], order: [ - ['date_seen', 'DESC'], - [{ model: Episode }, { model: Season }, 'season_number', 'DESC'], + ["date_seen", "DESC"], + [{ model: Episode }, { model: Season }, "season_number", "DESC"], // [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this - [Episode, 'episode_number', 'DESC']] + [Episode, "episode_number", "DESC"], + ], }); res.status(200).json(episodeSeens); } catch (error) { - console.log(`error getting episode seen of an entry: `, error) + console.log(`error getting episode seen of an entry: `, error); res.status(500).json({ error: error.message }); } } @@ -105,16 +114,18 @@ class EpisodeSeenController { try { const { date_seen, seen_with, episode_id } = req.body; - const episodeSeen = await EpisodeSeen.findByPk(req.params.id) + const episodeSeen = await EpisodeSeen.findByPk(req.params.id); if (!episodeSeen) - return res.status(404).json({ message: 'Episode seen record not found.' }); + return res + .status(404) + .json({ message: "Episode seen record not found." }); const updated = await episodeSeen.update({ date_seen, seen_with }); if (updated) { res.status(200).json(updated); } else { - res.status(404).json({ message: 'Episode seen record not found.' }); + res.status(404).json({ message: "Episode seen record not found." }); } } catch (error) { res.status(500).json({ error: error.message }); @@ -126,19 +137,17 @@ class EpisodeSeenController { // ? 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.' }); + res.status(404).json({ message: "Episode seen record not found." }); // ?deleting the episode seen const deleted = await oldEpisodeSeen.destroy(); - if (deleted) - res.status(204).send(); + if (deleted) res.status(204).send(); } catch (error) { res.status(500).json({ error: error.message }); - console.log(error) + console.log(error); } } - } module.exports = new EpisodeSeenController(); diff --git a/backend/controllers/importController.js b/backend/controllers/importController.js index dd95eed..4b187d6 100644 --- a/backend/controllers/importController.js +++ b/backend/controllers/importController.js @@ -1,4 +1,8 @@ -const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require("../services/importerService"); +const { + bulkImportMovies, + bulkImportTmdb, + bulkImportEpisodes, +} = require("../services/importerService"); class ImportController { constructor() { diff --git a/backend/controllers/killerController.js b/backend/controllers/killerController.js index 6f97b6c..60ce032 100644 --- a/backend/controllers/killerController.js +++ b/backend/controllers/killerController.js @@ -1,5 +1,4 @@ class KillerController { - constructor() { if (!KillerController.instance) { KillerController.instance = this; @@ -8,11 +7,10 @@ class KillerController { } async killBackend(req, res) { - console.log("Killing backend.") + console.log("Killing backend."); res.status(200).json({ message: "Backend killed." }); console.log(kill); } - } module.exports = new KillerController(); diff --git a/backend/controllers/mediaController.js b/backend/controllers/mediaController.js index 4e4d50f..207e509 100644 --- a/backend/controllers/mediaController.js +++ b/backend/controllers/mediaController.js @@ -1,19 +1,18 @@ -const path = require('path'); -const fs = require('fs'); +const path = require("path"); +const fs = require("fs"); -const Entry = require('../models/Entry'); -const Media = require('../models/Media'); -const Collection = require('../models/Collection'); +const Entry = require("../models/Entry"); +const Media = require("../models/Media"); +const Collection = require("../models/Collection"); -const configService = require('../services/configService.js'); -const { logToFile } = require('../services/logService'); -const mediaOptimizerService = require('../services/mediaOptimizerService.js'); -const asyncWrapper = require('../utils/asyncWrapper'); +const configService = require("../services/configService.js"); +const { logToFile } = require("../services/logService"); +const mediaOptimizerService = require("../services/mediaOptimizerService.js"); +const asyncWrapper = require("../utils/asyncWrapper"); const _mediaOptimizerService = mediaOptimizerService; class MediaController { - constructor() { if (!MediaController.instance) { MediaController.instance = this; @@ -21,7 +20,6 @@ class MediaController { return MediaController.instance; } getMedias = asyncWrapper(async (req, res) => { - const allCustomMedia = await Media.findAll({ where: { isCustom: true, @@ -29,15 +27,15 @@ class MediaController { include: [ { model: Entry, - as: 'entry', - required: false // This ensures a LEFT OUTER JOIN + as: "entry", + required: false, // This ensures a LEFT OUTER JOIN }, { model: Collection, - as: 'collection', - required: false // This ensures a LEFT OUTER JOIN - } - ] + as: "collection", + required: false, // This ensures a LEFT OUTER JOIN + }, + ], }); res.status(200).json(allCustomMedia); @@ -46,37 +44,57 @@ class MediaController { getMedia(req, res, next) { const { category, type, size, fileName } = req.params; - if (!['entries', 'collections', 'franchises', 'seasons', 'episodes', 'peoples'].includes(category)) { - return res.status(404).send('Category Not Found'); + if ( + ![ + "entries", + "collections", + "franchises", + "seasons", + "episodes", + "peoples", + ].includes(category) + ) { + return res.status(404).send("Category Not Found"); } - if (!['backdrops', 'posters', 'logos', 'stills', 'profiles', 'others'].includes(type)) { - return res.status(404).send('Type Not Found'); + if ( + ![ + "backdrops", + "posters", + "logos", + "stills", + "profiles", + "others", + ].includes(type) + ) { + return res.status(404).send("Type Not Found"); } const settings = configService.getSettings(); const dataPath = settings.userDataPath; - const mediaPath = path.join(dataPath, 'images', category, type); + const mediaPath = path.join(dataPath, "images", category, type); // const mediaPath = path.join(__dirname, '..', `data/images/${category}/${type}`); // * preparing to serve the preview // ? basicaly im checking if the file requested is a preview file // ? if so I make sure to change the extention to '_preview.jpg' (bcs all previews are jpg) let filePath = path.join(mediaPath, fileName); - if (size == 'preview') { - const previewFileName = fileName.split('.')[0] + (type == 'logos' ? '_preview.png' : '_preview.jpg') + if (size == "preview") { + const previewFileName = + fileName.split(".")[0] + + (type == "logos" ? "_preview.png" : "_preview.jpg"); filePath = path.join(mediaPath, previewFileName); } fs.access(filePath, fs.constants.F_OK, (err) => { // * generating a preview if it doesn't exist // ? then if the preview doesn't exist I generate a new one - // ? by taking the file name and removing '_preview' from it to get + // ? by taking the file name and removing '_preview' from it to get // ? the original file name, and starting from that I join it to the media path // ? and generate a preview file, but still return 202 http code since the file // ? is still generating - if (err && size == 'preview') { + if (err && size == "preview") { // const originalPath = path.join(mediaPath, fileName); // const previewFileName = fileName.split('.')[0] + '_preview.jpg' // const previewPath = path.join(mediaPath, previewFileName); @@ -85,14 +103,17 @@ class MediaController { // if (type == 'backdrops') previewWidth = 780; // if (type == 'logos') previewWidth = 300; - _mediaOptimizerService.doGeneratePreview(category, type, fileName).then((result) => { - const stream = fs.createReadStream(filePath); - stream.pipe(res); - logToFile(`Media Route | Generated Preview`); - }).catch((err) => { - logToFile(`Media Route | Error Generating Preview`); - logToFile(err); - }); + _mediaOptimizerService + .doGeneratePreview(category, type, fileName) + .then((result) => { + const stream = fs.createReadStream(filePath); + stream.pipe(res); + logToFile(`Media Route | Generated Preview`); + }) + .catch((err) => { + logToFile(`Media Route | Error Generating Preview`); + logToFile(err); + }); // const stream = fs.createReadStream(filePath); // stream.pipe(res); // return res.status(202).send('Preview is still generating. Please try again later.'); @@ -108,7 +129,6 @@ class MediaController { } }); } - } module.exports = new MediaController(); diff --git a/backend/controllers/peopleController.js b/backend/controllers/peopleController.js index 6f4b4c0..43553bc 100644 --- a/backend/controllers/peopleController.js +++ b/backend/controllers/peopleController.js @@ -1,6 +1,6 @@ const peopleService = require("../services/peopleService"); const peopleManager = require("../services/peopleManager"); -const tmdbService = require('../services/tmdbService'); +const tmdbService = require("../services/tmdbService"); const _peopleService = peopleService; const _peopleManager = peopleManager; @@ -60,7 +60,9 @@ class PeopleController { async fetchAndSavePersonByTmdbId(req, res) { const { tmdb_id, pinned } = req.body; - const person = await _peopleService.fetchAndSavePersonByTmdbId(tmdb_id, { pinned: !!pinned }); + const person = await _peopleService.fetchAndSavePersonByTmdbId(tmdb_id, { + pinned: !!pinned, + }); res.status(201).json(person); } @@ -73,7 +75,7 @@ class PeopleController { async getPersonCredits(req, res) { const { id } = req.params; const person = await _peopleService.getPersonById(id); - if (!person) return res.status(404).json({ message: 'Person not found' }); + if (!person) return res.status(404).json({ message: "Person not found" }); res.status(200).json(person.roles ?? []); } @@ -81,10 +83,15 @@ class PeopleController { const { id } = req.params; const person = await _peopleService.getPersonById(id); if (!person || !person.tmdb_id) { - return res.status(404).json({ message: 'Person not found or missing TMDB ID' }); + return res + .status(404) + .json({ message: "Person not found or missing TMDB ID" }); } const data = await tmdbService.fetchPersonCombinedCredits(person.tmdb_id); - if (!data) return res.status(500).json({ message: 'Failed to fetch filmography from TMDB' }); + if (!data) + return res + .status(500) + .json({ message: "Failed to fetch filmography from TMDB" }); res.status(200).json(data); } @@ -93,7 +100,9 @@ class PeopleController { const person = await _peopleService.getPersonById(id); if (person && person.tmdb_id) { - const updatedPerson = await _peopleService.fetchAndSavePersonByTmdbId(person.tmdb_id); + const updatedPerson = await _peopleService.fetchAndSavePersonByTmdbId( + person.tmdb_id, + ); res.status(200).json(updatedPerson); } else { res.status(404).json({ message: "Person not found or missing TMDB ID" }); @@ -103,31 +112,41 @@ class PeopleController { async getTmdbPopularPeople(req, res) { const { page } = req.query; const data = await tmdbService.fetchPopularPeople(page || 1); - if (!data) return res.status(500).json({ message: 'Failed to fetch popular people' }); + if (!data) + return res + .status(500) + .json({ message: "Failed to fetch popular people" }); res.status(200).json(data); } async searchTmdbPeople(req, res) { const { query, page } = req.query; - if (!query) return res.status(400).json({ message: 'Query parameter is required' }); + if (!query) + return res.status(400).json({ message: "Query parameter is required" }); const data = await tmdbService.searchPeople(query, page || 1); - if (!data) return res.status(500).json({ message: 'Failed to search TMDB people' }); + if (!data) + return res.status(500).json({ message: "Failed to search TMDB people" }); res.status(200).json(data); } async getTmdbPersonPreview(req, res) { const { tmdbId } = req.params; const personData = await tmdbService.fetchPersonDetails(tmdbId); - if (!personData) return res.status(404).json({ message: 'Person not found on TMDB' }); + if (!personData) + return res.status(404).json({ message: "Person not found on TMDB" }); const filmography = await tmdbService.fetchPersonCombinedCredits(tmdbId); // Check if person already exists in local DB let localId = null; try { - const localPerson = await _peopleService.getPersonByTmdbId(parseInt(tmdbId)); + const localPerson = await _peopleService.getPersonByTmdbId( + parseInt(tmdbId), + ); if (localPerson) localId = localPerson.id; - } catch (_) { /* not found */ } + } catch (_) { + /* not found */ + } const preview = { tmdb_id: personData.id, diff --git a/backend/controllers/pingController.js b/backend/controllers/pingController.js index 0943c15..7dbfe6e 100644 --- a/backend/controllers/pingController.js +++ b/backend/controllers/pingController.js @@ -1,5 +1,4 @@ class PingController { - constructor() { if (!PingController.instance) { PingController.instance = this; @@ -8,11 +7,10 @@ class PingController { } ping(req, res) { - console.log("Ping Pong...") - - res.status(200).json({ message: 'pong' }); - } + console.log("Ping Pong..."); + res.status(200).json({ message: "pong" }); + } } module.exports = new PingController(); diff --git a/backend/controllers/seasonController.js b/backend/controllers/seasonController.js index 4e2c224..7617e37 100644 --- a/backend/controllers/seasonController.js +++ b/backend/controllers/seasonController.js @@ -2,9 +2,7 @@ const Episode = require("../models/Episode"); const EpisodeSeen = require("../models/EpisodeSeen"); const Season = require("../models/Season"); - class SeasonController { - constructor() { if (!SeasonController.instance) { SeasonController.instance = this; @@ -33,16 +31,18 @@ class SeasonController { async getSeaonById(req, res) { try { const season = await Season.findByPk(req.params.id, { - include: [{ - model: Episode, - as: 'episodes' - }] + include: [ + { + model: Episode, + as: "episodes", + }, + ], }); if (season) { res.send(season); } else { - res.status(404).send('Season not found'); + res.status(404).send("Season not found"); } } catch (error) { res.status(500).send(error.message); @@ -53,19 +53,19 @@ class SeasonController { try { const episodes = await Episode.findAll({ where: { - season_id: req.params.id + season_id: req.params.id, }, include: [{ model: EpisodeSeen }], order: [ - ['episode_number', 'ASC'], - [EpisodeSeen, 'date_seen', 'ASC'], + ["episode_number", "ASC"], + [EpisodeSeen, "date_seen", "ASC"], ], }); if (episodes) { res.send(episodes); } else { - res.status(404).send('Episodes not found'); + res.status(404).send("Episodes not found"); } } catch (error) { res.status(500).send(error.message); @@ -75,13 +75,13 @@ class SeasonController { async updateSeason(req, res) { try { const [updated] = await Season.update(req.body, { - where: { id: req.params.id } + where: { id: req.params.id }, }); if (updated) { const updatedSeason = await Season.findByPk(req.params.id); res.send(updatedSeason); } else { - res.status(404).send('Season not found'); + res.status(404).send("Season not found"); } } catch (error) { res.status(500).send(error.message); @@ -91,18 +91,17 @@ class SeasonController { async deleteSeason(req, res) { try { const deleted = await Season.destroy({ - where: { id: req.params.id } + where: { id: req.params.id }, }); if (deleted) { - res.status(204).send('Season deleted'); + res.status(204).send("Season deleted"); } else { - res.status(404).send('Season not found'); + res.status(404).send("Season not found"); } } catch (error) { res.status(500).send(error.message); } } - } module.exports = new SeasonController(); diff --git a/backend/controllers/settingsController.js b/backend/controllers/settingsController.js index 5a52304..8509d3c 100644 --- a/backend/controllers/settingsController.js +++ b/backend/controllers/settingsController.js @@ -1,9 +1,8 @@ -const configService = require('../services/configService'); +const configService = require("../services/configService"); const _configService = configService; class SettingsController { - constructor() { if (!SettingsController.instance) { SettingsController.instance = this; @@ -17,7 +16,7 @@ class SettingsController { res.status(200).json(settings); } catch (err) { - res.status(500).send('Error retrieving settings'); + res.status(500).send("Error retrieving settings"); } } @@ -28,7 +27,6 @@ class SettingsController { res.status(200).send(configService.getSettings()); } - } module.exports = new SettingsController(); diff --git a/backend/controllers/statisticsController.js b/backend/controllers/statisticsController.js index 3eaebf6..4b4b975 100644 --- a/backend/controllers/statisticsController.js +++ b/backend/controllers/statisticsController.js @@ -1,12 +1,11 @@ -const sequelize = require('../config/database'); -const { Op } = require('sequelize'); -const Entry = require('../models/Entry'); -const EntrySeen = require('../models/EntrySeen'); -const Episode = require('../models/Episode'); -const EpisodeSeen = require('../models/EpisodeSeen'); +const sequelize = require("../config/database"); +const { Op } = require("sequelize"); +const Entry = require("../models/Entry"); +const EntrySeen = require("../models/EntrySeen"); +const Episode = require("../models/Episode"); +const EpisodeSeen = require("../models/EpisodeSeen"); class StatisticsController { - constructor() { if (!StatisticsController.instance) { StatisticsController.instance = this; @@ -16,27 +15,23 @@ class StatisticsController { async getAllTimeWatchTime(req, res) { const totalWatchTimeSeries = await EpisodeSeen.findOne({ - include: [ - { model: Episode, as: 'episode', attributes: [] } - ], + include: [{ model: Episode, as: "episode", attributes: [] }], attributes: [ - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + [sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"], ], }); const totalWatchTimeMovies = await EntrySeen.findOne({ - include: [ - { model: Entry, as: 'entry', attributes: [] } - ], + include: [{ model: Entry, as: "entry", attributes: [] }], attributes: [ - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + [sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"], ], }); const totalWatchTime = { series: totalWatchTimeSeries.dataValues.watchTime, - movies: totalWatchTimeMovies.dataValues.watchTime - } + movies: totalWatchTimeMovies.dataValues.watchTime, + }; return res.status(200).json(totalWatchTime); } @@ -45,41 +40,37 @@ class StatisticsController { const { year } = req.params; const totalWatchTimeSeries = await EpisodeSeen.findAll({ - include: [ - { model: Episode, as: 'episode', attributes: [] } - ], + include: [{ model: Episode, as: "episode", attributes: [] }], attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + [sequelize.fn("MONTH", sequelize.col("date_seen")), "month"], + [sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"], ], where: { date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)], + }, }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + group: [sequelize.fn("MONTH", sequelize.col("date_seen"))], }); const totalWatchTimeMovies = await EntrySeen.findAll({ - include: [ - { model: Entry, as: 'entry', attributes: [] } - ], + include: [{ model: Entry, as: "entry", attributes: [] }], attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + [sequelize.fn("MONTH", sequelize.col("date_seen")), "month"], + [sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"], ], where: { date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)], + }, }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + group: [sequelize.fn("MONTH", sequelize.col("date_seen"))], }); const totalWatchTime = { series: totalWatchTimeSeries, - movies: totalWatchTimeMovies - } + movies: totalWatchTimeMovies, + }; return res.status(200).json(totalWatchTime); } @@ -89,33 +80,33 @@ class StatisticsController { const { year } = req.params; const seriesCount = await EpisodeSeen.findAll({ attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + [sequelize.fn("MONTH", sequelize.col("date_seen")), "month"], + [sequelize.fn("COUNT", sequelize.col("*")), "count"], ], where: { date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)], + }, }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + group: [sequelize.fn("MONTH", sequelize.col("date_seen"))], }); const moviesCount = await EntrySeen.findAll({ attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + [sequelize.fn("MONTH", sequelize.col("date_seen")), "month"], + [sequelize.fn("COUNT", sequelize.col("*")), "count"], ], where: { date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)], + }, }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + group: [sequelize.fn("MONTH", sequelize.col("date_seen"))], }); res.status(200).json({ series: seriesCount, movies: moviesCount }); } catch (error) { - console.log(error) + console.log(error); res.status(500).json({ error: error.message }); } } @@ -126,20 +117,20 @@ class StatisticsController { // Only count records with EXACT accuracy const episodeDays = await EpisodeSeen.findAll({ attributes: [ - [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen')), 'day'], - [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen")), "day"], + [sequelize.fn("COUNT", sequelize.col("*")), "count"], ], - where: { accuracy: 'EXACT' }, - group: [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen'))] + where: { accuracy: "EXACT" }, + group: [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen"))], }); const movieDays = await EntrySeen.findAll({ attributes: [ - [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen')), 'day'], - [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen")), "day"], + [sequelize.fn("COUNT", sequelize.col("*")), "count"], ], - where: { accuracy: 'EXACT' }, - group: [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen'))] + where: { accuracy: "EXACT" }, + group: [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen"))], }); res.status(200).json({ episodes: episodeDays, movies: movieDays }); @@ -148,7 +139,6 @@ class StatisticsController { res.status(500).json({ error: error.message }); } } - } module.exports = new StatisticsController(); diff --git a/backend/errors/BadRequestError.js b/backend/errors/BadRequestError.js index 8e3855d..8237c1d 100644 --- a/backend/errors/BadRequestError.js +++ b/backend/errors/BadRequestError.js @@ -1,4 +1,4 @@ -const CustomError = require('./CustomError'); +const CustomError = require("./CustomError"); /** * Represents an error for HTTP 400 Bad Request. @@ -14,4 +14,4 @@ class BadRequestError extends CustomError { } } -module.exports = BadRequestError; \ No newline at end of file +module.exports = BadRequestError; diff --git a/backend/errors/ConflictError.js b/backend/errors/ConflictError.js index 61a8732..3da2ba4 100644 --- a/backend/errors/ConflictError.js +++ b/backend/errors/ConflictError.js @@ -1,4 +1,4 @@ -const CustomError = require('./CustomError'); +const CustomError = require("./CustomError"); /** * Represents an error for HTTP 409 Conflict. diff --git a/backend/errors/CustomError.js b/backend/errors/CustomError.js index 217b262..5f96c69 100644 --- a/backend/errors/CustomError.js +++ b/backend/errors/CustomError.js @@ -14,4 +14,4 @@ class CustomError extends Error { } } -module.exports = CustomError; \ No newline at end of file +module.exports = CustomError; diff --git a/backend/errors/ForbiddenError.js b/backend/errors/ForbiddenError.js index b8633d4..39c37dd 100644 --- a/backend/errors/ForbiddenError.js +++ b/backend/errors/ForbiddenError.js @@ -1,4 +1,4 @@ -const CustomError = require('./CustomError'); +const CustomError = require("./CustomError"); /** * Represents an error for HTTP 403 Forbidden. diff --git a/backend/errors/InternalServerError.js b/backend/errors/InternalServerError.js index 4aef166..79e23e4 100644 --- a/backend/errors/InternalServerError.js +++ b/backend/errors/InternalServerError.js @@ -1,4 +1,4 @@ -const CustomError = require('./CustomError'); +const CustomError = require("./CustomError"); /** * Represents an error for HTTP 500 Internal Server Error. diff --git a/backend/errors/NotFoundError.js b/backend/errors/NotFoundError.js index c792b47..09c3881 100644 --- a/backend/errors/NotFoundError.js +++ b/backend/errors/NotFoundError.js @@ -1,4 +1,4 @@ -const CustomError = require('./CustomError'); +const CustomError = require("./CustomError"); /** * Represents an error for HTTP 404 Not Found. @@ -14,4 +14,4 @@ class NotFoundError extends CustomError { } } -module.exports = NotFoundError; \ No newline at end of file +module.exports = NotFoundError; diff --git a/backend/errors/UnauthorizedError.js b/backend/errors/UnauthorizedError.js index af26d37..729b35d 100644 --- a/backend/errors/UnauthorizedError.js +++ b/backend/errors/UnauthorizedError.js @@ -1,4 +1,4 @@ -const CustomError = require('./CustomError'); +const CustomError = require("./CustomError"); /** * Represents an error for HTTP 401 Unauthorized. @@ -14,4 +14,4 @@ class UnauthorizedError extends CustomError { } } -module.exports = UnauthorizedError; \ No newline at end of file +module.exports = UnauthorizedError; diff --git a/backend/errors/ValidationError.js b/backend/errors/ValidationError.js index d4704b1..4b99b7b 100644 --- a/backend/errors/ValidationError.js +++ b/backend/errors/ValidationError.js @@ -1,4 +1,4 @@ -const CustomError = require('./CustomError'); +const CustomError = require("./CustomError"); /** * Represents an error for HTTP 422 Unprocessable Entity. @@ -14,4 +14,4 @@ class ValidationError extends CustomError { } } -module.exports = ValidationError; \ No newline at end of file +module.exports = ValidationError; diff --git a/backend/middleware/errorHandler.js b/backend/middleware/errorHandler.js index 5d66e09..c15831e 100644 --- a/backend/middleware/errorHandler.js +++ b/backend/middleware/errorHandler.js @@ -1,46 +1,52 @@ -const CustomError = require('../errors/CustomError'); -const { logToFile } = require('../services/logService'); +const CustomError = require("../errors/CustomError"); +const { logToFile } = require("../services/logService"); module.exports = (err, req, res, next) => { // Log the error for debugging purposes console.log(`📌 Error caught in middleware:`, err); if (err instanceof CustomError) { - logToFile(`Custom Error (${err.statusCode()}) - ${req.method} ${req.path}: ${err.message}`); + logToFile( + `Custom Error (${err.statusCode()}) - ${req.method} ${req.path}: ${err.message}`, + ); res.status(err.statusCode()).json({ message: err.message, - error: process.env.NODE_ENV === 'development' ? err.stack : undefined + error: process.env.NODE_ENV === "development" ? err.stack : undefined, }); - } else if (err.name === 'ValidationError') { + } else if (err.name === "ValidationError") { // Handle Sequelize validation errors logToFile(`Validation Error - ${req.method} ${req.path}: ${err.message}`); res.status(400).json({ - message: 'Validation Error', + message: "Validation Error", details: err.errors || err.message, - error: process.env.NODE_ENV === 'development' ? err.stack : undefined + error: process.env.NODE_ENV === "development" ? err.stack : undefined, }); - } else if (err.name === 'SequelizeUniqueConstraintError') { + } else if (err.name === "SequelizeUniqueConstraintError") { // Handle Sequelize unique constraint errors - logToFile(`Unique Constraint Error - ${req.method} ${req.path}: ${err.message}`); + logToFile( + `Unique Constraint Error - ${req.method} ${req.path}: ${err.message}`, + ); res.status(409).json({ - message: 'Duplicate entry detected', - error: process.env.NODE_ENV === 'development' ? err.stack : undefined + message: "Duplicate entry detected", + error: process.env.NODE_ENV === "development" ? err.stack : undefined, }); - } else if (err.name === 'SequelizeForeignKeyConstraintError') { + } else if (err.name === "SequelizeForeignKeyConstraintError") { // Handle foreign key constraint errors logToFile(`Foreign Key Error - ${req.method} ${req.path}: ${err.message}`); res.status(400).json({ - message: 'Invalid reference to related data', - error: process.env.NODE_ENV === 'development' ? err.stack : undefined + message: "Invalid reference to related data", + error: process.env.NODE_ENV === "development" ? err.stack : undefined, }); } else { // Handle all other errors - const errorMessage = err.message || 'Internal server error'; - logToFile(`Unexpected Error - ${req.method} ${req.path}: ${errorMessage}\nStack: ${err.stack}`); + const errorMessage = err.message || "Internal server error"; + logToFile( + `Unexpected Error - ${req.method} ${req.path}: ${errorMessage}\nStack: ${err.stack}`, + ); res.status(500).json({ - message: 'Internal server error', - error: process.env.NODE_ENV === 'development' ? err.stack : undefined + message: "Internal server error", + error: process.env.NODE_ENV === "development" ? err.stack : undefined, }); } -}; \ No newline at end of file +}; diff --git a/backend/models/Collection.js b/backend/models/Collection.js index 9d289a9..d2c2cbd 100644 --- a/backend/models/Collection.js +++ b/backend/models/Collection.js @@ -1,22 +1,24 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const Collection = sequelize.define("userCollection", - { - id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, - tmdbId: { type: DataTypes.STRING(30), field: 'tmdb_id' }, - imdbId: { type: DataTypes.STRING(30), field: 'imdb_id' }, - tvdbId: { type: DataTypes.STRING(30), field: 'tvdb_id' }, +const Collection = sequelize.define("userCollection", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, + tmdbId: { type: DataTypes.STRING(30), field: "tmdb_id" }, + imdbId: { type: DataTypes.STRING(30), field: "imdb_id" }, + tvdbId: { type: DataTypes.STRING(30), field: "tvdb_id" }, - name: { type: DataTypes.STRING(150) }, - description: { type: DataTypes.STRING(3000) }, - isUserCollection: { type: DataTypes.BOOLEAN, defaultValue: false, field: 'is_user_collection' }, - userRating: { type: DataTypes.FLOAT, field: 'user_rating' }, + name: { type: DataTypes.STRING(150) }, + description: { type: DataTypes.STRING(3000) }, + isUserCollection: { + type: DataTypes.BOOLEAN, + defaultValue: false, + field: "is_user_collection", + }, + userRating: { type: DataTypes.FLOAT, field: "user_rating" }, - posterPath: { type: DataTypes.STRING(200), field: 'poster_path' }, - backdropPath: { type: DataTypes.STRING(200), field: 'backdrop_path' }, - isLocal: { type: DataTypes.BOOLEAN, defaultValue: false, field: 'is_local' } - } -); + posterPath: { type: DataTypes.STRING(200), field: "poster_path" }, + backdropPath: { type: DataTypes.STRING(200), field: "backdrop_path" }, + isLocal: { type: DataTypes.BOOLEAN, defaultValue: false, field: "is_local" }, +}); -module.exports = Collection; \ No newline at end of file +module.exports = Collection; diff --git a/backend/models/Credit.js b/backend/models/Credit.js index b86b31d..81f6bb1 100644 --- a/backend/models/Credit.js +++ b/backend/models/Credit.js @@ -1,26 +1,28 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const Credit = sequelize.define("credits", - { - id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, +const Credit = sequelize.define("credits", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, - tmdb_credit_id: { type: DataTypes.STRING(100) }, + tmdb_credit_id: { type: DataTypes.STRING(100) }, - adult: { type: DataTypes.BOOLEAN, defaultValue: false }, - profile_path: { type: DataTypes.STRING(200), field: 'profile_path' }, + adult: { type: DataTypes.BOOLEAN, defaultValue: false }, + profile_path: { type: DataTypes.STRING(200), field: "profile_path" }, - character: { type: DataTypes.STRING(500) }, - order: { type: DataTypes.INTEGER }, - episode_count: { type: DataTypes.INTEGER, defaultValue: null }, + character: { type: DataTypes.STRING(500) }, + order: { type: DataTypes.INTEGER }, + episode_count: { type: DataTypes.INTEGER, defaultValue: null }, - cast_type: { type: DataTypes.ENUM('cast', 'crew'), field: 'cast_type', defaultValue: 'cast' }, - department: { type: DataTypes.STRING(100) }, - job: { type: DataTypes.STRING(500) }, + cast_type: { + type: DataTypes.ENUM("cast", "crew"), + field: "cast_type", + defaultValue: "cast", + }, + department: { type: DataTypes.STRING(100) }, + job: { type: DataTypes.STRING(500) }, - entry_id: { type: DataTypes.INTEGER, field: 'entry_id' }, - people_id: { type: DataTypes.INTEGER, field: 'people_id' }, - } -); + entry_id: { type: DataTypes.INTEGER, field: "entry_id" }, + people_id: { type: DataTypes.INTEGER, field: "people_id" }, +}); module.exports = Credit; diff --git a/backend/models/EntryGenre.js b/backend/models/EntryGenre.js index 3df1211..b13d325 100644 --- a/backend/models/EntryGenre.js +++ b/backend/models/EntryGenre.js @@ -1,29 +1,32 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const EntryGenre = sequelize.define('entryGenre', +const EntryGenre = sequelize.define( + "entryGenre", { genre_id: { type: DataTypes.INTEGER, primaryKey: true, references: { - model: 'Genres', - key: 'id' - } + model: "Genres", + key: "id", + }, }, entry_id: { type: DataTypes.INTEGER, primaryKey: true, references: { - model: 'Entries', - key: 'id' - } - } + model: "Entries", + key: "id", + }, + }, }, { - primaryKey: ['genre_id', 'entry_id'], - }, { - timestamps: false, -}); + primaryKey: ["genre_id", "entry_id"], + }, + { + timestamps: false, + }, +); -module.exports = EntryGenre; \ No newline at end of file +module.exports = EntryGenre; diff --git a/backend/models/EntryId.js b/backend/models/EntryId.js index 3ba861a..922557b 100644 --- a/backend/models/EntryId.js +++ b/backend/models/EntryId.js @@ -1,22 +1,24 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const EntryId = sequelize.define("entryId", +const EntryId = sequelize.define( + "entryId", { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, entry_id: { type: DataTypes.INTEGER, references: { - model: 'Entries', - key: 'id' - } + model: "Entries", + key: "id", + }, }, tmdb_id: { type: DataTypes.STRING(30) }, imdb_id: { type: DataTypes.STRING(30) }, tvdb_id: { type: DataTypes.STRING(30) }, - }, { - timestamps: false, -} + }, + { + timestamps: false, + }, ); -module.exports = EntryId; \ No newline at end of file +module.exports = EntryId; diff --git a/backend/models/EntryNetwork.js b/backend/models/EntryNetwork.js index 850ea79..ea3df8a 100644 --- a/backend/models/EntryNetwork.js +++ b/backend/models/EntryNetwork.js @@ -1,31 +1,32 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const EntryNetwork = sequelize.define('entryNetwork', +const EntryNetwork = sequelize.define( + "entryNetwork", { network_id: { type: DataTypes.INTEGER, primaryKey: true, references: { - model: 'Networks', - key: 'id' - } + model: "Networks", + key: "id", + }, }, entry_id: { type: DataTypes.INTEGER, primaryKey: true, references: { - model: 'Entries', - key: 'id' - } + model: "Entries", + key: "id", + }, }, order: { - type: DataTypes.INTEGER - } + type: DataTypes.INTEGER, + }, }, { - primaryKey: ['network_id', 'entry_id'], - } + primaryKey: ["network_id", "entry_id"], + }, ); -module.exports = EntryNetwork; \ No newline at end of file +module.exports = EntryNetwork; diff --git a/backend/models/EntryRating.js b/backend/models/EntryRating.js index 612b896..02136c2 100644 --- a/backend/models/EntryRating.js +++ b/backend/models/EntryRating.js @@ -1,24 +1,25 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); - -const EntryRating = sequelize.define("entryRating", +const EntryRating = sequelize.define( + "entryRating", { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, entry_id: { type: DataTypes.INTEGER, references: { - model: 'Entries', - key: 'id' - } + model: "Entries", + key: "id", + }, }, user_rating: { type: DataTypes.FLOAT }, tmdb_rating: { type: DataTypes.FLOAT }, imdb_rating: { type: DataTypes.FLOAT }, rotten_tomatoes_rating: { type: DataTypes.FLOAT }, - }, { - timestamps: false, -} + }, + { + timestamps: false, + }, ); -module.exports = EntryRating; \ No newline at end of file +module.exports = EntryRating; diff --git a/backend/models/EntrySeen.js b/backend/models/EntrySeen.js index 52e57f9..200bc15 100644 --- a/backend/models/EntrySeen.js +++ b/backend/models/EntrySeen.js @@ -1,29 +1,29 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); - -const EntrySeen = sequelize.define("entrySeen", +const EntrySeen = sequelize.define( + "entrySeen", { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, entry_id: { type: DataTypes.INTEGER, references: { - model: 'Entries', - key: 'id' - } + model: "Entries", + key: "id", + }, }, date_seen: { type: DataTypes.DATE }, seen_with: { type: DataTypes.STRING(50) }, accuracy: { - type: DataTypes.ENUM('EXACT', 'ESTIMATED', 'UNKNOWN'), - defaultValue: 'EXACT', + type: DataTypes.ENUM("EXACT", "ESTIMATED", "UNKNOWN"), + defaultValue: "EXACT", }, - - }, { - timestamps: false, -} + }, + { + timestamps: false, + }, ); module.exports = EntrySeen; diff --git a/backend/models/Episode.js b/backend/models/Episode.js index 2d74f9d..d4107eb 100644 --- a/backend/models/Episode.js +++ b/backend/models/Episode.js @@ -1,38 +1,35 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const Episode = sequelize.define("episode", - { - id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, +const Episode = sequelize.define("episode", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, - tmdb_id: { type: DataTypes.STRING(30) }, - imdb_id: { type: DataTypes.STRING(30) }, - tvdb_id: { type: DataTypes.STRING(30) }, + tmdb_id: { type: DataTypes.STRING(30) }, + imdb_id: { type: DataTypes.STRING(30) }, + tvdb_id: { type: DataTypes.STRING(30) }, - season_id: { - type: DataTypes.INTEGER, - references: { - model: 'Seasons', - key: 'id' - } + season_id: { + type: DataTypes.INTEGER, + references: { + model: "Seasons", + key: "id", }, + }, - name: { type: DataTypes.STRING(500) }, - overview: { type: DataTypes.STRING(3000) }, - episode_number: { type: DataTypes.INTEGER }, - episode_type: { type: DataTypes.STRING(60) }, - runtime: { type: DataTypes.INTEGER }, - air_date: { type: DataTypes.DATE }, + name: { type: DataTypes.STRING(500) }, + overview: { type: DataTypes.STRING(3000) }, + episode_number: { type: DataTypes.INTEGER }, + episode_type: { type: DataTypes.STRING(60) }, + runtime: { type: DataTypes.INTEGER }, + air_date: { type: DataTypes.DATE }, - user_rating: { type: DataTypes.FLOAT }, - tmdb_rating: { type: DataTypes.FLOAT }, + user_rating: { type: DataTypes.FLOAT }, + tmdb_rating: { type: DataTypes.FLOAT }, - still_path: { type: DataTypes.STRING(200) }, + still_path: { type: DataTypes.STRING(200) }, - date_first_seen: { type: DataTypes.DATEONLY }, - date_last_seen: { type: DataTypes.DATEONLY } + date_first_seen: { type: DataTypes.DATEONLY }, + date_last_seen: { type: DataTypes.DATEONLY }, +}); - } -); - -module.exports = Episode; \ No newline at end of file +module.exports = Episode; diff --git a/backend/models/EpisodeSeen.js b/backend/models/EpisodeSeen.js index 1ddb298..889fb0a 100644 --- a/backend/models/EpisodeSeen.js +++ b/backend/models/EpisodeSeen.js @@ -1,34 +1,30 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); +const EpisodeSeen = sequelize.define("episodeSeen", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, -const EpisodeSeen = sequelize.define("episodeSeen", - { - id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, - - entry_id: { - type: DataTypes.INTEGER, - references: { - model: 'Entries', - key: 'id' - } + entry_id: { + type: DataTypes.INTEGER, + references: { + model: "Entries", + key: "id", }, - episode_id: { - type: DataTypes.INTEGER, - references: { - model: 'Episodes', - key: 'id' - } + }, + episode_id: { + type: DataTypes.INTEGER, + references: { + model: "Episodes", + key: "id", }, + }, - date_seen: { type: DataTypes.DATE }, - seen_with: { type: DataTypes.STRING(50) }, - accuracy: { - type: DataTypes.ENUM('EXACT', 'ESTIMATED', 'UNKNOWN'), - defaultValue: 'EXACT', - }, - - } -); + date_seen: { type: DataTypes.DATE }, + seen_with: { type: DataTypes.STRING(50) }, + accuracy: { + type: DataTypes.ENUM("EXACT", "ESTIMATED", "UNKNOWN"), + defaultValue: "EXACT", + }, +}); module.exports = EpisodeSeen; diff --git a/backend/models/Franchise.js b/backend/models/Franchise.js index ad8c71c..35d7391 100644 --- a/backend/models/Franchise.js +++ b/backend/models/Franchise.js @@ -1,15 +1,17 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const Franchise = sequelize.define("franchise", +const Franchise = sequelize.define( + "franchise", { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, title: { type: DataTypes.STRING(50) }, overview: { type: DataTypes.STRING(300) }, - user_rating: { type: DataTypes.FLOAT } - }, { - timestamps: false, -} + user_rating: { type: DataTypes.FLOAT }, + }, + { + timestamps: false, + }, ); -module.exports = Franchise; \ No newline at end of file +module.exports = Franchise; diff --git a/backend/models/Genre.js b/backend/models/Genre.js index 3159153..178fe26 100644 --- a/backend/models/Genre.js +++ b/backend/models/Genre.js @@ -1,14 +1,16 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const Genre = sequelize.define("genre", +const Genre = sequelize.define( + "genre", { id: { type: DataTypes.INTEGER, primaryKey: true }, name: { type: DataTypes.STRING(30) }, - }, { - timestamps: false, -} + }, + { + timestamps: false, + }, ); -module.exports = Genre; \ No newline at end of file +module.exports = Genre; diff --git a/backend/models/Media.js b/backend/models/Media.js index fd235ee..64cf641 100644 --- a/backend/models/Media.js +++ b/backend/models/Media.js @@ -1,21 +1,31 @@ -const { DataTypes, Sequelize } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes, Sequelize } = require("sequelize"); +const sequelize = require("../config/database"); -const Media = sequelize.define("media", - { - id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, +const Media = sequelize.define("media", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, - mediaable: { type: Sequelize.STRING }, - mediaableId: { type: Sequelize.INTEGER, field: 'mediaable_id' }, + mediaable: { type: Sequelize.STRING }, + mediaableId: { type: Sequelize.INTEGER, field: "mediaable_id" }, - type: { type: DataTypes.STRING(50) }, - path: { type: DataTypes.STRING(200) }, + type: { type: DataTypes.STRING(50) }, + path: { type: DataTypes.STRING(200) }, - isLocal: { type: DataTypes.BOOLEAN, field: 'is_local' }, - isSelected: { type: DataTypes.BOOLEAN, field: 'is_selected', defaultValue: false }, - isCustom: { type: DataTypes.BOOLEAN, field: 'is_custom', defaultValue: false }, - isFavorit: { type: DataTypes.BOOLEAN, field: 'is_favorit', defaultValue: false }, - } -); + isLocal: { type: DataTypes.BOOLEAN, field: "is_local" }, + isSelected: { + type: DataTypes.BOOLEAN, + field: "is_selected", + defaultValue: false, + }, + isCustom: { + type: DataTypes.BOOLEAN, + field: "is_custom", + defaultValue: false, + }, + isFavorit: { + type: DataTypes.BOOLEAN, + field: "is_favorit", + defaultValue: false, + }, +}); -module.exports = Media; \ No newline at end of file +module.exports = Media; diff --git a/backend/models/Network.js b/backend/models/Network.js index 42d5599..dba8512 100644 --- a/backend/models/Network.js +++ b/backend/models/Network.js @@ -1,18 +1,16 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const Network = sequelize.define("network", - { - id: { type: DataTypes.INTEGER, primaryKey: true }, +const Network = sequelize.define("network", { + id: { type: DataTypes.INTEGER, primaryKey: true }, - name: { type: DataTypes.STRING(30) }, - originCountry: { type: DataTypes.STRING(100), field: 'origin_country' }, - homepage: { type: DataTypes.STRING(100), field: 'homepage' }, + name: { type: DataTypes.STRING(30) }, + originCountry: { type: DataTypes.STRING(100), field: "origin_country" }, + homepage: { type: DataTypes.STRING(100), field: "homepage" }, - logoPath: { type: DataTypes.STRING(200), field: 'logo_path' }, - posterPath: { type: DataTypes.STRING(200), field: 'poster_path' }, - backdropPath: { type: DataTypes.STRING(200), field: 'backdrop_path' }, - } -); + logoPath: { type: DataTypes.STRING(200), field: "logo_path" }, + posterPath: { type: DataTypes.STRING(200), field: "poster_path" }, + backdropPath: { type: DataTypes.STRING(200), field: "backdrop_path" }, +}); -module.exports = Network; \ No newline at end of file +module.exports = Network; diff --git a/backend/models/People.js b/backend/models/People.js index c6781da..7163046 100644 --- a/backend/models/People.js +++ b/backend/models/People.js @@ -1,35 +1,36 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const People = sequelize.define("peoples", - { - id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, +const People = sequelize.define("peoples", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, - tmdb_id: { type: DataTypes.STRING(100) }, + tmdb_id: { type: DataTypes.STRING(100) }, - name: { type: DataTypes.STRING(100) }, - birthday: { type: DataTypes.DATEONLY }, - deathday: { type: DataTypes.DATEONLY, allowNull: true }, - gender: { type: DataTypes.INTEGER }, + name: { type: DataTypes.STRING(100) }, + birthday: { type: DataTypes.DATEONLY }, + deathday: { type: DataTypes.DATEONLY, allowNull: true }, + gender: { type: DataTypes.INTEGER }, - biography: { type: DataTypes.TEXT }, - place_of_birth: { type: DataTypes.STRING(100), field: 'place_of_birth' }, + biography: { type: DataTypes.TEXT }, + place_of_birth: { type: DataTypes.STRING(100), field: "place_of_birth" }, - adult: { type: DataTypes.BOOLEAN, defaultValue: false }, - popularity: { type: DataTypes.FLOAT }, + adult: { type: DataTypes.BOOLEAN, defaultValue: false }, + popularity: { type: DataTypes.FLOAT }, - known_for_department: { type: DataTypes.STRING(50), field: 'known_for_department' }, - homepage: { type: DataTypes.STRING(200), allowNull: true }, + known_for_department: { + type: DataTypes.STRING(50), + field: "known_for_department", + }, + homepage: { type: DataTypes.STRING(200), allowNull: true }, - imdb_id: { type: DataTypes.STRING(20), field: 'imdb_id' }, - profile_path: { type: DataTypes.STRING(200), field: 'profile_path' }, + imdb_id: { type: DataTypes.STRING(20), field: "imdb_id" }, + profile_path: { type: DataTypes.STRING(200), field: "profile_path" }, - last_fetch: { type: DataTypes.DATEONLY, field: 'last_fetch' }, - profile_update: { type: DataTypes.DATEONLY, field: 'profile_update' }, - fully_fetched: { type: DataTypes.BOOLEAN, defaultValue: false }, - favorite: { type: DataTypes.BOOLEAN, defaultValue: false }, - pinned: { type: DataTypes.BOOLEAN, defaultValue: false }, - } -); + last_fetch: { type: DataTypes.DATEONLY, field: "last_fetch" }, + profile_update: { type: DataTypes.DATEONLY, field: "profile_update" }, + fully_fetched: { type: DataTypes.BOOLEAN, defaultValue: false }, + favorite: { type: DataTypes.BOOLEAN, defaultValue: false }, + pinned: { type: DataTypes.BOOLEAN, defaultValue: false }, +}); module.exports = People; diff --git a/backend/models/Season.js b/backend/models/Season.js index b576bb4..6cc008b 100644 --- a/backend/models/Season.js +++ b/backend/models/Season.js @@ -1,34 +1,32 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const Season = sequelize.define("season", - { - id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, +const Season = sequelize.define("season", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, - tmdb_id: { type: DataTypes.STRING(30) }, - imdb_id: { type: DataTypes.STRING(30) }, + tmdb_id: { type: DataTypes.STRING(30) }, + imdb_id: { type: DataTypes.STRING(30) }, - entry_id: { - type: DataTypes.INTEGER, - references: { - model: 'Entries', - key: 'id' - } + entry_id: { + type: DataTypes.INTEGER, + references: { + model: "Entries", + key: "id", }, + }, - name: { type: DataTypes.STRING(500) }, - overview: { type: DataTypes.STRING(3000) }, - season_number: { type: DataTypes.INTEGER }, - episode_count: { type: DataTypes.INTEGER }, - air_date: { type: DataTypes.DATE }, + name: { type: DataTypes.STRING(500) }, + overview: { type: DataTypes.STRING(3000) }, + season_number: { type: DataTypes.INTEGER }, + episode_count: { type: DataTypes.INTEGER }, + air_date: { type: DataTypes.DATE }, - user_rating: { type: DataTypes.FLOAT }, - tmdb_rating: { type: DataTypes.FLOAT }, - imdb_rating: { type: DataTypes.FLOAT }, + user_rating: { type: DataTypes.FLOAT }, + tmdb_rating: { type: DataTypes.FLOAT }, + imdb_rating: { type: DataTypes.FLOAT }, - poster_path: { type: DataTypes.STRING(200) }, - banner_path: { type: DataTypes.STRING(200) }, - } -); + poster_path: { type: DataTypes.STRING(200) }, + banner_path: { type: DataTypes.STRING(200) }, +}); -module.exports = Season; \ No newline at end of file +module.exports = Season; diff --git a/backend/models/UserCollectionEntry.js b/backend/models/UserCollectionEntry.js index 0518fab..62cd226 100644 --- a/backend/models/UserCollectionEntry.js +++ b/backend/models/UserCollectionEntry.js @@ -1,30 +1,32 @@ -const { DataTypes } = require('sequelize'); -const sequelize = require('../config/database'); +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); -const UserCollectionEntry = sequelize.define('userCollectionEntry', +const UserCollectionEntry = sequelize.define( + "userCollectionEntry", { user_collection_id: { type: DataTypes.INTEGER, primaryKey: true, references: { - model: 'UserCollections', - key: 'id' - } + model: "UserCollections", + key: "id", + }, }, entry_id: { type: DataTypes.INTEGER, primaryKey: true, references: { - model: 'Entries', - key: 'id' - } + model: "Entries", + key: "id", + }, }, order: { - type: DataTypes.INTEGER - } + type: DataTypes.INTEGER, + }, }, { - primaryKey: ['user_collection_id', 'entry_id'], - }); + primaryKey: ["user_collection_id", "entry_id"], + }, +); -module.exports = UserCollectionEntry; \ No newline at end of file +module.exports = UserCollectionEntry; diff --git a/backend/routes/ai-query.routes.js b/backend/routes/ai-query.routes.js index 6b96adb..149d5ef 100644 --- a/backend/routes/ai-query.routes.js +++ b/backend/routes/ai-query.routes.js @@ -1,42 +1,51 @@ -const express = require('express'); +const express = require("express"); const aiQueryRouter = express.Router(); -const aiQueryController = require('../controllers/aiQueryController'); +const aiQueryController = require("../controllers/aiQueryController"); // ! /ai-query // * Watch history -aiQueryRouter.get('/recently-watched/movies', aiQueryController.getRecentlyWatchedMovies); -aiQueryRouter.get('/recently-watched/episodes', aiQueryController.getRecentlyWatchedEpisodes); +aiQueryRouter.get( + "/recently-watched/movies", + aiQueryController.getRecentlyWatchedMovies, +); +aiQueryRouter.get( + "/recently-watched/episodes", + aiQueryController.getRecentlyWatchedEpisodes, +); // * Library lists -aiQueryRouter.get('/watchlist', aiQueryController.getWatchlist); -aiQueryRouter.get('/favorites', aiQueryController.getFavorites); +aiQueryRouter.get("/watchlist", aiQueryController.getWatchlist); +aiQueryRouter.get("/favorites", aiQueryController.getFavorites); // * Library overview & search -aiQueryRouter.get('/library/overview', aiQueryController.getLibraryOverview); -aiQueryRouter.get('/library/search', aiQueryController.searchLibrary); +aiQueryRouter.get("/library/overview", aiQueryController.getLibraryOverview); +aiQueryRouter.get("/library/search", aiQueryController.searchLibrary); // * Upcoming -aiQueryRouter.get('/upcoming', aiQueryController.getUpcoming); +aiQueryRouter.get("/upcoming", aiQueryController.getUpcoming); // * Entry detail -aiQueryRouter.get('/entry/:id', aiQueryController.getEntryDetail); +aiQueryRouter.get("/entry/:id", aiQueryController.getEntryDetail); // * Genres -aiQueryRouter.get('/genres/breakdown', aiQueryController.getGenreBreakdown); +aiQueryRouter.get("/genres/breakdown", aiQueryController.getGenreBreakdown); // * Collections -aiQueryRouter.get('/collections', aiQueryController.getAllCollections); -aiQueryRouter.get('/collections/:id', aiQueryController.getCollectionDetail); +aiQueryRouter.get("/collections", aiQueryController.getAllCollections); +aiQueryRouter.get("/collections/:id", aiQueryController.getCollectionDetail); // * TV series -aiQueryRouter.get('/tv-series/in-progress', aiQueryController.getInProgressSeries); +aiQueryRouter.get( + "/tv-series/in-progress", + aiQueryController.getInProgressSeries, +); // * Stats -aiQueryRouter.get('/stats/watching-time', aiQueryController.getWatchTimeStats); +aiQueryRouter.get("/stats/watching-time", aiQueryController.getWatchTimeStats); // * People -aiQueryRouter.get('/person/:id', aiQueryController.getPersonDetail); +aiQueryRouter.get("/person/:id", aiQueryController.getPersonDetail); module.exports = aiQueryRouter; diff --git a/backend/routes/collection.routes.js b/backend/routes/collection.routes.js index b9915b3..2bd65a2 100644 --- a/backend/routes/collection.routes.js +++ b/backend/routes/collection.routes.js @@ -1,45 +1,59 @@ -const express = require('express'); +const express = require("express"); const collectionRouter = express.Router(); -const collectionController = require('../controllers/collectionController'); -const { collectionPicturesUpload } = require('../services/mutlerStorageLocations'); +const collectionController = require("../controllers/collectionController"); +const { + collectionPicturesUpload, +} = require("../services/mutlerStorageLocations"); // ! /collections // * GET - ALL COLLECTIONS -collectionRouter.get('/', collectionController.getCollections); +collectionRouter.get("/", collectionController.getCollections); // * GET - COLLECTION BY ID -collectionRouter.get('/:id', collectionController.getCollectionById); +collectionRouter.get("/:id", collectionController.getCollectionById); // * POST - CREATE COLLECTION -collectionRouter.post('/', collectionController.createCollection); +collectionRouter.post("/", collectionController.createCollection); // * PUT - UPDATE COLLECTION const upload = collectionPicturesUpload.fields([ - { name: 'poster', maxCount: 1 }, - { name: 'backdrop', maxCount: 1 } + { name: "poster", maxCount: 1 }, + { name: "backdrop", maxCount: 1 }, ]); -collectionRouter.put('/:id', upload, collectionController.updateCollection); +collectionRouter.put("/:id", upload, collectionController.updateCollection); // * PUT - REFRESH COLLECTION -collectionRouter.put('/:id/refresh', collectionController.refrechCollection); +collectionRouter.put("/:id/refresh", collectionController.refrechCollection); // * PUT - GET COLLECTION PARTS -collectionRouter.put('/:id/parts', collectionController.getCollectionParts); +collectionRouter.put("/:id/parts", collectionController.getCollectionParts); // * DELETE - DELETE COLLECTION -collectionRouter.delete('/:id', collectionController.deleteCollection); +collectionRouter.delete("/:id", collectionController.deleteCollection); // * POST - ADD ENTRY TO A COLLECTION -collectionRouter.post('/:collectionId/entries/:entryId', collectionController.addEntryToCollection); +collectionRouter.post( + "/:collectionId/entries/:entryId", + collectionController.addEntryToCollection, +); // * PATCH - UPDATE ENTRY ORDER IN COLLECTION -collectionRouter.patch('/:collectionId/entries/:entryId', collectionController.updateCollectionEntryOrder); +collectionRouter.patch( + "/:collectionId/entries/:entryId", + collectionController.updateCollectionEntryOrder, +); // * DELETE - REMOVE AN ENTRY FROM A COLLECTION -collectionRouter.delete('/:collectionId/entries/:entryId', collectionController.removeEntryFromCollection); +collectionRouter.delete( + "/:collectionId/entries/:entryId", + collectionController.removeEntryFromCollection, +); // * POST - CREATE COLLECTION WITH ENTRY -collectionRouter.post('/collection-with-entry', collectionController.createCollectionWithEntry); +collectionRouter.post( + "/collection-with-entry", + collectionController.createCollectionWithEntry, +); module.exports = collectionRouter; diff --git a/backend/routes/entry-seen.routes.js b/backend/routes/entry-seen.routes.js index d3d1b72..86f6dbd 100644 --- a/backend/routes/entry-seen.routes.js +++ b/backend/routes/entry-seen.routes.js @@ -1,25 +1,28 @@ -const express = require('express'); +const express = require("express"); const entrySeenRouter = express.Router(); -const entrySeenController = require('../controllers/entrySeenController'); +const entrySeenController = require("../controllers/entrySeenController"); // ! /entry-seen // * GET - ALL ENTRY SEEN -entrySeenRouter.get('/', entrySeenController.getEntrySeens); +entrySeenRouter.get("/", entrySeenController.getEntrySeens); // * GET - ENTRY SEEN BY ENTRY ID (must be before /:id to avoid conflict) -entrySeenRouter.get('/by-entry/:entryId', entrySeenController.getEntrySeensByEntryId); +entrySeenRouter.get( + "/by-entry/:entryId", + entrySeenController.getEntrySeensByEntryId, +); // * GET - ENTRY SEEN BY ID -entrySeenRouter.get('/:id', entrySeenController.getEntrySeenById); +entrySeenRouter.get("/:id", entrySeenController.getEntrySeenById); // * POST - CREATE ENTRY SEEN -entrySeenRouter.post('/', entrySeenController.createEntrySeen); +entrySeenRouter.post("/", entrySeenController.createEntrySeen); // * PUT - UPDATE ENTRY SEEN -entrySeenRouter.put('/:id', entrySeenController.updateEntrySeen); +entrySeenRouter.put("/:id", entrySeenController.updateEntrySeen); // * DELETE - ENTRY SEEN -entrySeenRouter.delete('/:id', entrySeenController.deleteEntrySeen); +entrySeenRouter.delete("/:id", entrySeenController.deleteEntrySeen); module.exports = entrySeenRouter; diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index 5b0ce02..4184fe8 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -1,104 +1,108 @@ -const express = require('express'); +const express = require("express"); const entryRouter = express.Router(); -const { entryPicturesUpload } = require('../services/mutlerStorageLocations'); -const Entry = require('../models/Entry'); -const Media = require('../models/Media'); -const { logToFile } = require('../services/logService'); +const { entryPicturesUpload } = require("../services/mutlerStorageLocations"); +const Entry = require("../models/Entry"); +const Media = require("../models/Media"); +const { logToFile } = require("../services/logService"); -const entryController = require('../controllers/entryController'); -const mediaOptimizerService = require('../services/mediaOptimizerService'); +const entryController = require("../controllers/entryController"); +const mediaOptimizerService = require("../services/mediaOptimizerService"); // ! /entries // ! TMDB PROXY ROUTES (must be before /:id to avoid matching) -entryRouter.get('/tmdb/trending/:type', entryController.getTmdbTrending); -entryRouter.get('/tmdb/popular/:type', entryController.getTmdbPopular); -entryRouter.get('/tmdb/top-rated/:type', entryController.getTmdbTopRated); -entryRouter.get('/tmdb/upcoming/movie', entryController.getTmdbUpcoming); -entryRouter.get('/tmdb/search', entryController.getTmdbSearch); -entryRouter.get('/tmdb/preview/:type/:tmdbId', entryController.getTmdbPreview); +entryRouter.get("/tmdb/trending/:type", entryController.getTmdbTrending); +entryRouter.get("/tmdb/popular/:type", entryController.getTmdbPopular); +entryRouter.get("/tmdb/top-rated/:type", entryController.getTmdbTopRated); +entryRouter.get("/tmdb/upcoming/movie", entryController.getTmdbUpcoming); +entryRouter.get("/tmdb/search", entryController.getTmdbSearch); +entryRouter.get("/tmdb/preview/:type/:tmdbId", entryController.getTmdbPreview); -entryRouter.get('/sync-series', entryController.syncSeries); +entryRouter.get("/sync-series", entryController.syncSeries); -entryRouter.get('/', entryController.getAllEntries); -entryRouter.get('/:id', entryController.getEntryById); -entryRouter.post('/', entryController.fetchAndSaveNewEntry); -entryRouter.put('/:id', entryController.updateEntry); -entryRouter.put('/:id/ratings', entryController.updateEntryRatings); -entryRouter.put('/:id/ids', entryController.updateEntryIds); -entryRouter.delete('/:id', entryController.deleteEntry); +entryRouter.get("/", entryController.getAllEntries); +entryRouter.get("/:id", entryController.getEntryById); +entryRouter.post("/", entryController.fetchAndSaveNewEntry); +entryRouter.put("/:id", entryController.updateEntry); +entryRouter.put("/:id/ratings", entryController.updateEntryRatings); +entryRouter.put("/:id/ids", entryController.updateEntryIds); +entryRouter.delete("/:id", entryController.deleteEntry); -entryRouter.get('/:id/seasons', entryController.getEntrySeasons); -entryRouter.get('/:id/credits', entryController.getEntryCredits); -entryRouter.put('/:id/refresh', entryController.refrechEntry); -entryRouter.put('/:id/fetch-collection', entryController.fetchEntryCollection); +entryRouter.get("/:id/seasons", entryController.getEntrySeasons); +entryRouter.get("/:id/credits", entryController.getEntryCredits); +entryRouter.put("/:id/refresh", entryController.refrechEntry); +entryRouter.put("/:id/fetch-collection", entryController.fetchEntryCollection); // ! ENTRY MEDIA // * POST - ADD NEW ENTRY MEDIA (poster/backdrop/logo) const upload = entryPicturesUpload.fields([ - { name: 'poster', maxCount: 1 }, - { name: 'backdrop', maxCount: 1 }, - { name: 'logo', maxCount: 1 } + { name: "poster", maxCount: 1 }, + { name: "backdrop", maxCount: 1 }, + { name: "logo", maxCount: 1 }, ]); -entryRouter.post('/:id/media', upload, async (req, res) => { +entryRouter.post("/:id/media", upload, async (req, res) => { const { id } = req.params; if (!req.files) { - return res.status(400).json({ message: 'No files uploaded' }); + return res.status(400).json({ message: "No files uploaded" }); } const entry = await Entry.findByPk(id); if (!entry) { - return res.status(404).json({ message: 'Entry not found' }); + return res.status(404).json({ message: "Entry not found" }); } // Function to handle media creation based on uploaded file type - const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]); + const fileType = ["poster", "backdrop", "logo"].find( + (type) => req.files[type], + ); if (!fileType) { - return res.status(400).json({ message: 'Invalid media type' }); + return res.status(400).json({ message: "Invalid media type" }); } const file = req.files[fileType][0]; const createdMedia = await Media.create({ - mediaable: 'entry', + mediaable: "entry", mediaableId: id, type: fileType, path: file.filename, isLocal: true, isSelected: false, - isCustom: true + isCustom: true, }); // ? generating low resolution preview - mediaOptimizerService.doGeneratePreview('entries', fileType + 's', file.filename).then((result) => { - const stream = fs.createReadStream(filePath); - stream.pipe(res); + mediaOptimizerService + .doGeneratePreview("entries", fileType + "s", file.filename) + .then((result) => { + const stream = fs.createReadStream(filePath); + stream.pipe(res); - const msg = `Media Route | Generated Entry Preview` - logToFile(msg); - }).catch((err) => { - const msg = `Media Route | Error Generating Entry Preview` - logToFile(msg); - }); + const msg = `Media Route | Generated Entry Preview`; + logToFile(msg); + }) + .catch((err) => { + const msg = `Media Route | Error Generating Entry Preview`; + logToFile(msg); + }); return res.status(200).json(createdMedia); - }); // * PUT - SET ENTRY MEDIA AS SELECTED -entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => { +entryRouter.put("/:entryId/media/:mediaId", upload, async (req, res) => { const entryId = req.params.entryId; const mediaId = req.params.mediaId; const entry = await Entry.findByPk(entryId); if (!entry) { - return res.status(404).json({ message: 'Entry not found' }); + return res.status(404).json({ message: "Entry not found" }); } const media = await Media.findByPk(mediaId); if (!media) { - return res.status(404).json({ message: 'Media not found' }); + return res.status(404).json({ message: "Media not found" }); } // ? setting all other media to not selected @@ -107,11 +111,11 @@ entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => { { isSelected: false }, { where: { - mediaable: 'entry', + mediaable: "entry", mediaableId: entryId, - type: media.type - } - } + type: media.type, + }, + }, ); const updatedMedia = await media.update({ isSelected: true }); @@ -119,7 +123,7 @@ entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => { }); // * DELETE - DELETE AND ENTRY MEDIA -entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => { +entryRouter.delete("/:entryId/media/:mediaId", async (req, res) => { const mediaId = req.params.mediaId; // ? just before deleting we need to check if the deleted media was the one selected @@ -128,11 +132,11 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => { if (media && media.isSelected) { let otherMedia = await Media.findOne({ where: { - mediaable: 'entry', + mediaable: "entry", mediaableId: media.mediaableId, type: media.type, - isSelected: false - } + isSelected: false, + }, }); // ? if found select the first one @@ -141,10 +145,9 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => { } } - await Media.destroy({ where: { id: mediaId } }) + await Media.destroy({ where: { id: mediaId } }); res.status(200).json(); }); - module.exports = entryRouter; diff --git a/backend/routes/episode-seen.routes.js b/backend/routes/episode-seen.routes.js index 86bc747..2ce806e 100644 --- a/backend/routes/episode-seen.routes.js +++ b/backend/routes/episode-seen.routes.js @@ -1,28 +1,34 @@ -const express = require('express'); +const express = require("express"); const episodeSeenRouter = express.Router(); -const episodeSeenController = require('../controllers/episodeSeenController'); +const episodeSeenController = require("../controllers/episodeSeenController"); // ! /episode-seen // * POST - CREATE ENTRY SEEN -episodeSeenRouter.post('/', episodeSeenController.createEpisodeSeen); +episodeSeenRouter.post("/", episodeSeenController.createEpisodeSeen); // * GET - ALL EPISODE SEEN -episodeSeenRouter.get('/', episodeSeenController.getEpisodesSeen); +episodeSeenRouter.get("/", episodeSeenController.getEpisodesSeen); // * GET - EPISODE SEEN BY EPISODE ID (must come before /:id) -episodeSeenRouter.get('/by-episode/:episodeId', episodeSeenController.getEpisodeSeensByEpisodeId); +episodeSeenRouter.get( + "/by-episode/:episodeId", + episodeSeenController.getEpisodeSeensByEpisodeId, +); // * GET - EPISODE SEEN BY ENTRY ID (must come before /:id) -episodeSeenRouter.get('/by-entry/:entryId', episodeSeenController.getEpisodeSeensByEntryId); +episodeSeenRouter.get( + "/by-entry/:entryId", + episodeSeenController.getEpisodeSeensByEntryId, +); // * GET - EPISODE SEEN BY ID -episodeSeenRouter.get('/:id', episodeSeenController.getEpisodeSeenById); +episodeSeenRouter.get("/:id", episodeSeenController.getEpisodeSeenById); // * PUT - UPDATE EPISODE SEEN -episodeSeenRouter.put('/:id', episodeSeenController.updateEpisodeSeen); +episodeSeenRouter.put("/:id", episodeSeenController.updateEpisodeSeen); // * DELETE - EPISODE SEEN -episodeSeenRouter.delete('/:id', episodeSeenController.deleteEpisodeSeen); +episodeSeenRouter.delete("/:id", episodeSeenController.deleteEpisodeSeen); module.exports = episodeSeenRouter; diff --git a/backend/routes/episode.routes.js b/backend/routes/episode.routes.js index 87c0e01..59cf00b 100644 --- a/backend/routes/episode.routes.js +++ b/backend/routes/episode.routes.js @@ -1,8 +1,11 @@ -const express = require('express'); -const episodeController = require('../controllers/episodeController'); +const express = require("express"); +const episodeController = require("../controllers/episodeController"); const episodeRouter = express.Router(); // ! /episodes -episodeRouter.get('/month/:startDate/:endDate', episodeController.getEpisodesBetweenDates); +episodeRouter.get( + "/month/:startDate/:endDate", + episodeController.getEpisodesBetweenDates, +); module.exports = episodeRouter; diff --git a/backend/routes/import.routes.js b/backend/routes/import.routes.js index ccc89e7..eb49737 100644 --- a/backend/routes/import.routes.js +++ b/backend/routes/import.routes.js @@ -1,11 +1,14 @@ -const express = require('express'); +const express = require("express"); const importRouter = express.Router(); -const importController = require('../controllers/importController'); +const importController = require("../controllers/importController"); // ! /import -importRouter.post('/movies', importController.importMovies); -importRouter.post('/tmdb', importController.importTMBD); -importRouter.post('/episodes-watch-history', importController.importEpisodeWatchHistory); +importRouter.post("/movies", importController.importMovies); +importRouter.post("/tmdb", importController.importTMBD); +importRouter.post( + "/episodes-watch-history", + importController.importEpisodeWatchHistory, +); module.exports = importRouter; diff --git a/backend/routes/killer.routes.js b/backend/routes/killer.routes.js index d0e4ca2..ef43a37 100644 --- a/backend/routes/killer.routes.js +++ b/backend/routes/killer.routes.js @@ -1,11 +1,11 @@ -const express = require('express'); -const killerController = require('../controllers/killerController'); +const express = require("express"); +const killerController = require("../controllers/killerController"); const killerRouter = express.Router(); // ! /killer // * POST -killerRouter.post('/', killerController.killBackend); +killerRouter.post("/", killerController.killBackend); // * GET -killerRouter.get('/', killerController.killBackend); +killerRouter.get("/", killerController.killBackend); module.exports = killerRouter; diff --git a/backend/routes/media.routes.js b/backend/routes/media.routes.js index e32e4cf..330384b 100644 --- a/backend/routes/media.routes.js +++ b/backend/routes/media.routes.js @@ -1,12 +1,12 @@ -const express = require('express'); +const express = require("express"); const mediaRouter = express.Router(); -const mediaController = require('../controllers/mediaController.js'); +const mediaController = require("../controllers/mediaController.js"); // ! /media -mediaRouter.get('/', mediaController.getMedias); +mediaRouter.get("/", mediaController.getMedias); // ? Routes : media access routes -mediaRouter.get('/:category/:type/:size/:fileName', mediaController.getMedia); +mediaRouter.get("/:category/:type/:size/:fileName", mediaController.getMedia); module.exports = mediaRouter; diff --git a/backend/routes/people.routes.js b/backend/routes/people.routes.js index ecfdeb9..b7ffec4 100644 --- a/backend/routes/people.routes.js +++ b/backend/routes/people.routes.js @@ -1,56 +1,60 @@ -const express = require('express'); +const express = require("express"); const peopleRouter = express.Router(); -const { peoplePicturesUpload } = require('../services/mutlerStorageLocations'); -const mediaOptimizerService = require('../services/mediaOptimizerService'); -const peopleController = require('../controllers/peopleController'); +const { peoplePicturesUpload } = require("../services/mutlerStorageLocations"); +const mediaOptimizerService = require("../services/mediaOptimizerService"); +const peopleController = require("../controllers/peopleController"); // ! /people // ! TMDB PROXY ROUTES (must be before /:id to avoid matching) -peopleRouter.get('/tmdb/popular', peopleController.getTmdbPopularPeople); -peopleRouter.get('/tmdb/search', peopleController.searchTmdbPeople); -peopleRouter.get('/tmdb/preview/:tmdbId', peopleController.getTmdbPersonPreview); +peopleRouter.get("/tmdb/popular", peopleController.getTmdbPopularPeople); +peopleRouter.get("/tmdb/search", peopleController.searchTmdbPeople); +peopleRouter.get( + "/tmdb/preview/:tmdbId", + peopleController.getTmdbPersonPreview, +); // Get all people -peopleRouter.get('/', peopleController.getAllPeople); +peopleRouter.get("/", peopleController.getAllPeople); // Get popular people -peopleRouter.get('/popular', peopleController.getPopularPeople); +peopleRouter.get("/popular", peopleController.getPopularPeople); // Search people -peopleRouter.get('/search', peopleController.searchPeople); +peopleRouter.get("/search", peopleController.searchPeople); // Get person by ID -peopleRouter.get('/:id', peopleController.getPersonById); +peopleRouter.get("/:id", peopleController.getPersonById); // Get person credits (from DB) -peopleRouter.get('/:id/credits', peopleController.getPersonCredits); +peopleRouter.get("/:id/credits", peopleController.getPersonCredits); // Get person TMDB filmography (all TMDB credits including non-library entries) -peopleRouter.get('/:id/tmdb-filmography', peopleController.getPersonTmdbFilmography); +peopleRouter.get( + "/:id/tmdb-filmography", + peopleController.getPersonTmdbFilmography, +); // Create a new person -peopleRouter.post('/', peopleController.createPerson); +peopleRouter.post("/", peopleController.createPerson); // Fetch and save person from TMDB -peopleRouter.post('/fetch', peopleController.fetchAndSavePersonByTmdbId); +peopleRouter.post("/fetch", peopleController.fetchAndSavePersonByTmdbId); // Update a person -peopleRouter.put('/:id', peopleController.updatePerson); +peopleRouter.put("/:id", peopleController.updatePerson); // Refresh person data from TMDB -peopleRouter.put('/:id/refresh', peopleController.refreshPerson); +peopleRouter.put("/:id/refresh", peopleController.refreshPerson); // Delete a person -peopleRouter.delete('/:id', peopleController.deletePerson); +peopleRouter.delete("/:id", peopleController.deletePerson); // Person media upload handler -const upload = peoplePicturesUpload.fields([ - { name: 'profile', maxCount: 1 } -]); +const upload = peoplePicturesUpload.fields([{ name: "profile", maxCount: 1 }]); // Upload person profile picture -peopleRouter.post('/:id/media', upload, async (req, res) => { +peopleRouter.post("/:id/media", upload, async (req, res) => { try { const personId = req.params.id; let result = { success: true, files: [] }; @@ -62,12 +66,16 @@ peopleRouter.post('/:id/media', upload, async (req, res) => { const fileName = profileFile.filename; // Generate preview for profile picture - const previewPath = await mediaOptimizerService.doGeneratePreview('people', 'profiles', fileName); + const previewPath = await mediaOptimizerService.doGeneratePreview( + "people", + "profiles", + fileName, + ); result.files.push({ - type: 'profile', + type: "profile", original: fileName, - preview: previewPath ? path.basename(previewPath) : null + preview: previewPath ? path.basename(previewPath) : null, }); } diff --git a/backend/routes/ping.routes.js b/backend/routes/ping.routes.js index 7d8a5af..5119b34 100644 --- a/backend/routes/ping.routes.js +++ b/backend/routes/ping.routes.js @@ -1,8 +1,8 @@ -const express = require('express'); -const PingController = require('../controllers/PingController'); +const express = require("express"); +const PingController = require("../controllers/PingController"); const pingRouter = express.Router(); // ! /ping -pingRouter.get('/', PingController.ping); +pingRouter.get("/", PingController.ping); module.exports = pingRouter; diff --git a/backend/routes/routes.js b/backend/routes/routes.js index cd26d52..651deb1 100644 --- a/backend/routes/routes.js +++ b/backend/routes/routes.js @@ -1,36 +1,35 @@ -const express = require('express'); -const collectionRouter = require('./collection.routes'); -const entrySeenRouter = require('./entry-seen.routes'); -const entryRouter = require('./entry.routes'); -const seasonRouter = require('./season.routes'); -const episodeSeenRouter = require('./episode-seen.routes'); -const settingsRouter = require('./settings.routes'); -const maintenanceRouter = require('./maintenance.routes'); -const statisticsRouter = require('./statistics.routes'); -const mediaRouter = require('./media.routes'); -const episodeRouter = require('./episode.routes'); -const pingRouter = require('./ping.routes'); -const importRouter = require('./import.routes'); -const peopleRouter = require('./people.routes'); -const aiQueryRouter = require('./ai-query.routes'); - -const router = express.Router(); -router.use('/media', mediaRouter); -router.use('/entries', entryRouter); -router.use('/collections', collectionRouter); -router.use('/entry-seen', entrySeenRouter); - -router.use('/seasons', seasonRouter); -router.use('/episodes', episodeRouter); -router.use('/episode-seen', episodeSeenRouter); - - -router.use('/import', importRouter); -router.use('/statistics', statisticsRouter); -router.use('/settings', settingsRouter); -router.use('/maintenance', maintenanceRouter); -router.use('/ping', pingRouter); -router.use('/people', peopleRouter); -router.use('/ai-query', aiQueryRouter); - -module.exports = router; \ No newline at end of file +const express = require("express"); +const collectionRouter = require("./collection.routes"); +const entrySeenRouter = require("./entry-seen.routes"); +const entryRouter = require("./entry.routes"); +const seasonRouter = require("./season.routes"); +const episodeSeenRouter = require("./episode-seen.routes"); +const settingsRouter = require("./settings.routes"); +const maintenanceRouter = require("./maintenance.routes"); +const statisticsRouter = require("./statistics.routes"); +const mediaRouter = require("./media.routes"); +const episodeRouter = require("./episode.routes"); +const pingRouter = require("./ping.routes"); +const importRouter = require("./import.routes"); +const peopleRouter = require("./people.routes"); +const aiQueryRouter = require("./ai-query.routes"); + +const router = express.Router(); +router.use("/media", mediaRouter); +router.use("/entries", entryRouter); +router.use("/collections", collectionRouter); +router.use("/entry-seen", entrySeenRouter); + +router.use("/seasons", seasonRouter); +router.use("/episodes", episodeRouter); +router.use("/episode-seen", episodeSeenRouter); + +router.use("/import", importRouter); +router.use("/statistics", statisticsRouter); +router.use("/settings", settingsRouter); +router.use("/maintenance", maintenanceRouter); +router.use("/ping", pingRouter); +router.use("/people", peopleRouter); +router.use("/ai-query", aiQueryRouter); + +module.exports = router; diff --git a/backend/routes/season.routes.js b/backend/routes/season.routes.js index b494498..626412e 100644 --- a/backend/routes/season.routes.js +++ b/backend/routes/season.routes.js @@ -1,25 +1,25 @@ -const express = require('express'); +const express = require("express"); const seasonRouter = express.Router(); -const seasonController = require('../controllers/seasonController'); +const seasonController = require("../controllers/seasonController"); // ! /seasons // * POST - Create a new season -seasonRouter.post('/', seasonController.createSeason); +seasonRouter.post("/", seasonController.createSeason); // * GET - Retrieve all seasons -seasonRouter.get('/', seasonController.getSeasons); +seasonRouter.get("/", seasonController.getSeasons); // * GET - Retrieve a specific season by id -seasonRouter.get('/:id', seasonController.getSeaonById); +seasonRouter.get("/:id", seasonController.getSeaonById); // * GET - Retrieve episodes of a season -seasonRouter.get('/:id/episodes', seasonController.getSeasonEpisodes); +seasonRouter.get("/:id/episodes", seasonController.getSeasonEpisodes); // * PUT - Update a season -seasonRouter.put('/:id', seasonController.updateSeason); +seasonRouter.put("/:id", seasonController.updateSeason); // * DELETE - Delete a season -seasonRouter.delete('/:id', seasonController.deleteSeason); +seasonRouter.delete("/:id", seasonController.deleteSeason); -module.exports = seasonRouter; \ No newline at end of file +module.exports = seasonRouter; diff --git a/backend/routes/settings.routes.js b/backend/routes/settings.routes.js index 37895f2..4d20dd8 100644 --- a/backend/routes/settings.routes.js +++ b/backend/routes/settings.routes.js @@ -1,10 +1,10 @@ -const express = require('express'); +const express = require("express"); const settingsRouter = express.Router(); -const settingsController = require('../controllers/settingsController'); +const settingsController = require("../controllers/settingsController"); // ! /settings -settingsRouter.get('/', settingsController.getSettings); -settingsRouter.put('/', settingsController.updateSettings); +settingsRouter.get("/", settingsController.getSettings); +settingsRouter.put("/", settingsController.updateSettings); module.exports = settingsRouter; diff --git a/backend/routes/statistics.routes.js b/backend/routes/statistics.routes.js index 2f1e6fe..b3e7455 100644 --- a/backend/routes/statistics.routes.js +++ b/backend/routes/statistics.routes.js @@ -1,19 +1,28 @@ -const express = require('express'); +const express = require("express"); const statisticsRouter = express.Router(); -const statisticsController = require('../controllers/statisticsController'); +const statisticsController = require("../controllers/statisticsController"); // ! /statistics // * GET - All Time, Watch Time -statisticsRouter.get('/watch-time', statisticsController.getAllTimeWatchTime); +statisticsRouter.get("/watch-time", statisticsController.getAllTimeWatchTime); // * GET - Yearly Watch Time -statisticsRouter.get('/watch-time/year/:year', statisticsController.getYearlyWatchTime); +statisticsRouter.get( + "/watch-time/year/:year", + statisticsController.getYearlyWatchTime, +); // * GET - Yearly Watch Count Grouped By Month -statisticsRouter.get('/watch-count/year/:year', statisticsController.getYearlyWatchCountGroupByMonth); +statisticsRouter.get( + "/watch-count/year/:year", + statisticsController.getYearlyWatchCountGroupByMonth, +); // * GET - Watch Day Distribution (DAYOFWEEK) -statisticsRouter.get('/watch-weekday', statisticsController.getWatchdayDistribution); +statisticsRouter.get( + "/watch-weekday", + statisticsController.getWatchdayDistribution, +); module.exports = statisticsRouter; diff --git a/backend/server.js b/backend/server.js index 4fc1f37..ea4862e 100644 --- a/backend/server.js +++ b/backend/server.js @@ -1,36 +1,36 @@ -const express = require('express'); -const bodyParser = require('body-parser'); -const routes = require('./routes/routes.js'); -const sequelize = require('./config/database.js'); +const express = require("express"); +const bodyParser = require("body-parser"); +const routes = require("./routes/routes.js"); +const sequelize = require("./config/database.js"); const app = express(); // Global error handling for unhandled promise rejections -process.on('unhandledRejection', (reason, promise) => { - console.log('Unhandled Rejection at:', promise, 'reason:', reason); +process.on("unhandledRejection", (reason, promise) => { + console.log("Unhandled Rejection at:", promise, "reason:", reason); // Application specific logging, throwing an error, or other logic here }); // Global error handling for uncaught exceptions -process.on('uncaughtException', (error) => { - console.log('Uncaught Exception:', error); +process.on("uncaughtException", (error) => { + console.log("Uncaught Exception:", error); // Application specific logging, throwing an error, or other logic here process.exit(1); // Exit the process to avoid undefined state }); -const relations = require('./config/relations.js'); -const sequelizeHooks = require('./config/sequelizeHooks.js'); -const { initializeData } = require('./config/dataInitializer.js'); -const killerRouter = require('./routes/killer.routes.js'); -const errorHandler = require('./middleware/errorHandler'); -const configService = require('./services/configService.js'); -const { logToFile } = require('./services/logService.js'); -const { generatePreview } = require('./services/mediaService.js'); +const relations = require("./config/relations.js"); +const sequelizeHooks = require("./config/sequelizeHooks.js"); +const { initializeData } = require("./config/dataInitializer.js"); +const killerRouter = require("./routes/killer.routes.js"); +const errorHandler = require("./middleware/errorHandler"); +const configService = require("./services/configService.js"); +const { logToFile } = require("./services/logService.js"); +const { generatePreview } = require("./services/mediaService.js"); // ? variables -let settings = configService.getSettings() +let settings = configService.getSettings(); const PORT = settings["backPort"] || 4000; -const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}'); +const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || "{}"); // ? Middleware app.use(bodyParser.json()); // for parsing application/json @@ -38,31 +38,31 @@ app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x // * CORS Middleware to allow requests from any origin app.use((req, res, next) => { - res.header('Access-Control-Allow-Origin', '*'); + res.header("Access-Control-Allow-Origin", "*"); res.header( - 'Access-Control-Allow-Headers', - 'Origin, X-Requested-With, Content-Type, Accept, Authorization' + "Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept, Authorization", ); - if (req.method === 'OPTIONS') { - res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); + if (req.method === "OPTIONS") { + res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET"); return res.status(200).json({}); } next(); }); // ? other api routes -app.use('/api/v1', routes); +app.use("/api/v1", routes); // ? Error handling middleware app.use(errorHandler); // ? KILLER ROUTE: used to crash the backend -app.use('/killer', killerRouter); +app.use("/killer", killerRouter); // * Start the server const doUpdate = false; const doForce = false; -console.log('Server started'); +console.log("Server started"); console.log(`Syncing database schema...`); sequelize // .sync({force: true}) // will drop all tables and recreate them. @@ -75,7 +75,7 @@ sequelize console.log(`Backend server running on http://localhost:${PORT}/`); }); }) - .catch(err => { - console.log("____________SEQUELIZE SYNC ERROR____________") - console.log(err) - }); \ No newline at end of file + .catch((err) => { + console.log("____________SEQUELIZE SYNC ERROR____________"); + console.log(err); + }); diff --git a/backend/services/collectionManager.js b/backend/services/collectionManager.js index 422e88c..84d4d0c 100644 --- a/backend/services/collectionManager.js +++ b/backend/services/collectionManager.js @@ -19,7 +19,6 @@ const _mediaDownloaderService = mediaDownloaderService; const _mediaOptimizerService = mediaOptimizerService; class CollectionManager { - constructor() { if (!CollectionManager.instance) { CollectionManager.instance = this; @@ -43,7 +42,8 @@ class CollectionManager { } // * 2 - insert/update collection - const [oldCollection, createdCollection] = await _collectionService.createOrUpdateCollection(collectionData); + const [oldCollection, createdCollection] = + await _collectionService.createOrUpdateCollection(collectionData); // * 3 - link related entries to the collection let collection = oldCollection || createdCollection; @@ -51,57 +51,62 @@ class CollectionManager { throw new NotFoundError("Collection not found"); } - const partIds = collectionData.parts.map(part => part.id); + const partIds = collectionData.parts.map((part) => part.id); const entries = await Entry.findAll({ - include: [{ - model: EntryId, - as: 'entryId', - where: { - tmdb_id: { - [Sequelize.Op.in]: partIds - } - } - }] + include: [ + { + model: EntryId, + as: "entryId", + where: { + tmdb_id: { + [Sequelize.Op.in]: partIds, + }, + }, + }, + ], }); await collection.setEntries(entries); // * 4 - download collection media // ? downloading - const downloadedImages = await _mediaDownloaderService.downloadCollectionMedia(collection); + const downloadedImages = + await _mediaDownloaderService.downloadCollectionMedia(collection); // ? generating preview & inserting data for (const image of downloadedImages) { - // ? generating preview - _mediaOptimizerService.doGeneratePreview('collections', image.type + 's', image.path).then((result) => { - const msg = `Collection Service | Generated Collection Preview`; - console.log(msg); - logToFile(msg); - }).catch((err) => { - const msg = `Collection Service | Error Generating Collection Preview`; - console.log(msg); - console.log(err); - logToFile(msg); - logToFile(err); - }); + // ? generating preview + _mediaOptimizerService + .doGeneratePreview("collections", image.type + "s", image.path) + .then((result) => { + const msg = `Collection Service | Generated Collection Preview`; + console.log(msg); + logToFile(msg); + }) + .catch((err) => { + const msg = `Collection Service | Error Generating Collection Preview`; + console.log(msg); + console.log(err); + logToFile(msg); + logToFile(err); + }); // ? inserting data await Media.create({ - mediaable: 'collection', + mediaable: "collection", mediaableId: collection.id, type: image.type, path: image.path, isLocal: true, - isSelected: true - }) + isSelected: true, + }); } // * 5 - return the collection return await _collectionService.getCollectionById(collection.id); } - /** * Fetches the corresponding collection for a given entry (movie) if it is missing. * If the entry belongs to a collection, the collection is fetched and saved. @@ -118,15 +123,16 @@ class CollectionManager { } const oldEntry = await Entry.findByPk(id, { - include: [ - { model: EntryId, as: 'entryId' } - ] - }) + include: [{ model: EntryId, as: "entryId" }], + }); if (!oldEntry) { throw new NotFoundError("Entry not found"); } - const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); + const entryData = await fetchEntryData( + oldEntry.entryId.tmdb_id, + oldEntry.is_tvseries, + ); if (!entryData) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } @@ -172,19 +178,21 @@ class CollectionManager { // * 3 - fetch missing entries and save them and linked already // * existing ones to the collection - const partIds = collectionData.parts.map(part => part.id); + const partIds = collectionData.parts.map((part) => part.id); // ? get all the related entries that are already in the library const entries = await Entry.findAll({ - include: [{ - model: EntryId, - as: 'entryId', - where: { - tmdb_id: { - [Sequelize.Op.in]: partIds - } - } - }] + include: [ + { + model: EntryId, + as: "entryId", + where: { + tmdb_id: { + [Sequelize.Op.in]: partIds, + }, + }, + }, + ], }); // ? link entries already existing in the library @@ -194,8 +202,12 @@ class CollectionManager { collectionData.parts.forEach(async (part) => { if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) { const isTvSeries = false; - const _entryManager = require('./entryManager.js'); - const entry = await _entryManager.fetchAndSaveNewEntry(part.id, isTvSeries, false) + const _entryManager = require("./entryManager.js"); + const entry = await _entryManager.fetchAndSaveNewEntry( + part.id, + isTvSeries, + false, + ); await collection.addEntries([entry.id]); } @@ -203,4 +215,4 @@ class CollectionManager { } } -module.exports = new CollectionManager(); \ No newline at end of file +module.exports = new CollectionManager(); diff --git a/backend/services/collectionService.js b/backend/services/collectionService.js index 90d7e80..49ac680 100644 --- a/backend/services/collectionService.js +++ b/backend/services/collectionService.js @@ -8,9 +8,7 @@ const Media = require("../models/Media"); const Season = require("../models/Season"); const UserCollectionEntry = require("../models/UserCollectionEntry"); - class CollectionService { - constructor() { if (!CollectionService.instance) { CollectionService.instance = this; @@ -22,12 +20,13 @@ class CollectionService { const collections = await Collection.findAll({ include: [ { - model: Entry, as: 'entries', - include: { model: Media, as: 'medias' } + model: Entry, + as: "entries", + include: { model: Media, as: "medias" }, }, - { model: Media, as: 'medias' } + { model: Media, as: "medias" }, ], - order: [['name', 'ASC']] + order: [["name", "ASC"]], }); return collections; @@ -35,22 +34,26 @@ class CollectionService { async getCollectionById(id) { const collection = await Collection.findByPk(id, { - include: [{ - model: Entry, - as: 'entries', - include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, - { model: Genre, as: 'genres' }, - ], - through: { - model: UserCollectionEntry, - attributes: ['order'], // attributes (to include) from the join model + include: [ + { + model: Entry, + as: "entries", + include: [ + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, + { model: Genre, as: "genres" }, + ], + through: { + model: UserCollectionEntry, + attributes: ["order"], // attributes (to include) from the join model + }, }, - }], - order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order + ], + order: [ + [Sequelize.literal("`entries->UserCollectionEntry`.`order`"), "ASC"], + ], // sort by 'order' in ascending order }); return collection; @@ -63,12 +66,11 @@ class CollectionService { name: collectionData.name, posterPath: collectionData.poster_path, backdropPath: collectionData.backdrop_path, - description: collectionData.overview + description: collectionData.overview, }, - include: [{ model: Media, as: 'medias' }] + include: [{ model: Media, as: "medias" }], }); } - } -module.exports = new CollectionService(); \ No newline at end of file +module.exports = new CollectionService(); diff --git a/backend/services/configService.js b/backend/services/configService.js index ae9b81b..5e36410 100644 --- a/backend/services/configService.js +++ b/backend/services/configService.js @@ -1,20 +1,20 @@ -const fs = require('fs'); -const path = require('path'); +const fs = require("fs"); +const path = require("path"); const defaultSettings = { - userDataPath: '', - tmdbApiUrl: '', - tmdbApiKey: '', - frontPort: '', - backPort: '', - portableMode: '', + userDataPath: "", + tmdbApiUrl: "", + tmdbApiKey: "", + frontPort: "", + backPort: "", + portableMode: "", - libraryViewMode: 'grid', - favoritViewMode: 'grid', - watchlistViewMode: 'grid', - CollectionsViewMode: 'grid', - CollectionItemsViewMode: 'grid', - episodesViewMode: 'grid' + libraryViewMode: "grid", + favoritViewMode: "grid", + watchlistViewMode: "grid", + CollectionsViewMode: "grid", + CollectionItemsViewMode: "grid", + episodesViewMode: "grid", }; class ConfigService { @@ -31,7 +31,7 @@ class ConfigService { } getSettingsFilePath() { - return path.join(this.getUserDataPath(), 'settings.json'); + return path.join(this.getUserDataPath(), "settings.json"); } getSettings() { @@ -43,19 +43,22 @@ class ConfigService { const parsedSettings = JSON.parse(settingsData); return { ...defaultSettings, ...parsedSettings }; } catch (err) { - console.error('Error reading settings file:', err); - console.log('Creating default settings file...'); + console.error("Error reading settings file:", err); + console.log("Creating default settings file..."); let newSettingsFile = { ...defaultSettings }; - let defaultDataPath = path.join(this.getUserDataPath(), 'data') + let defaultDataPath = path.join(this.getUserDataPath(), "data"); newSettingsFile.userDataPath = defaultDataPath; newSettingsFile.backPort = 4000; fs.mkdirSync(defaultDataPath, { recursive: true }); - fs.writeFileSync(settingsFilePath, JSON.stringify(newSettingsFile, null, 2)); - console.log('Default settings file created.'); + fs.writeFileSync( + settingsFilePath, + JSON.stringify(newSettingsFile, null, 2), + ); + console.log("Default settings file created."); return defaultSettings; } @@ -65,9 +68,16 @@ class ConfigService { const settingsFilePath = this.getSettingsFilePath(); const oldSettings = this.getSettings(); - let updatedSettings = { ...defaultSettings, ...oldSettings, ...newSettings }; + let updatedSettings = { + ...defaultSettings, + ...oldSettings, + ...newSettings, + }; fs.mkdirSync(updatedSettings.userDataPath, { recursive: true }); // making sure the newly set data path is created before saving the new config - fs.writeFileSync(settingsFilePath, JSON.stringify(updatedSettings, null, 2)); + fs.writeFileSync( + settingsFilePath, + JSON.stringify(updatedSettings, null, 2), + ); } getMediaFolder() { @@ -77,14 +87,39 @@ class ConfigService { const settings = this.getSettings(); const dataPath = settings.userDataPath; - const posterDir = path.join(dataPath, 'images', 'entries', 'posters'); - const backdropDir = path.join(dataPath, 'images', 'entries', 'backdrops'); - const logoDir = path.join(dataPath, 'images', 'entries', 'logos'); - const collectionsPostersDir = path.join(dataPath, 'images', 'collections', 'posters'); - const collectionsBackdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops'); - const seasonsPostersDir = path.join(dataPath, 'images', 'seasons', 'posters'); - const episodesStillsDir = path.join(dataPath, 'images', 'episodes', 'stills'); - const peopleProfilesDir = path.join(dataPath, 'images', 'peoples', 'profiles'); + const posterDir = path.join(dataPath, "images", "entries", "posters"); + const backdropDir = path.join(dataPath, "images", "entries", "backdrops"); + const logoDir = path.join(dataPath, "images", "entries", "logos"); + const collectionsPostersDir = path.join( + dataPath, + "images", + "collections", + "posters", + ); + const collectionsBackdropsDir = path.join( + dataPath, + "images", + "collections", + "backdrops", + ); + const seasonsPostersDir = path.join( + dataPath, + "images", + "seasons", + "posters", + ); + const episodesStillsDir = path.join( + dataPath, + "images", + "episodes", + "stills", + ); + const peopleProfilesDir = path.join( + dataPath, + "images", + "peoples", + "profiles", + ); fs.mkdirSync(posterDir, { recursive: true }); fs.mkdirSync(backdropDir, { recursive: true }); @@ -103,10 +138,9 @@ class ConfigService { getTmdbApiKey() { return this.settings.tmdbApiKey; } - } // const instance = new ConfigService(); // Object.freeze(instance); -module.exports = new ConfigService(); \ No newline at end of file +module.exports = new ConfigService(); diff --git a/backend/services/episodeService.js b/backend/services/episodeService.js index 0797295..46e723a 100644 --- a/backend/services/episodeService.js +++ b/backend/services/episodeService.js @@ -1,6 +1,6 @@ const moment = require("../utils/moment"); -const { Op } = require("sequelize") +const { Op } = require("sequelize"); const Episode = require("../models/Episode"); const Season = require("../models/Season"); const Entry = require("../models/Entry"); @@ -10,7 +10,6 @@ const Media = require("../models/Media"); const BadRequestError = require("../errors/BadRequestError"); class EpisodeService { - constructor() { if (!EpisodeService.instance) { EpisodeService.instance = this; @@ -27,37 +26,37 @@ class EpisodeService { throw new BadRequestError("end Date not provided"); } - const formatedStartDate = moment(startDate).format('YYYY-MM-DD'); - const formatedEndDate = moment(endDate).format('YYYY-MM-DD'); + const formatedStartDate = moment(startDate).format("YYYY-MM-DD"); + const formatedEndDate = moment(endDate).format("YYYY-MM-DD"); // fetch episodes that aired within the current month, only from entries with showInCalendar enabled const episodes = await Episode.findAll({ where: { air_date: { - [Op.between]: [formatedStartDate, formatedEndDate] + [Op.between]: [formatedStartDate, formatedEndDate], }, }, include: [ { model: Season, - as: 'season', + as: "season", include: { model: Entry, - as: 'entry', + as: "entry", where: { showInCalendar: true }, include: [ - { model: EntryId, as: 'entryId' }, + { model: EntryId, as: "entryId" }, { model: Media, - as: 'medias', + as: "medias", }, ], - } - } - ] + }, + }, + ], }); - const modifiedEpisodes = episodes.map(episode => { + const modifiedEpisodes = episodes.map((episode) => { const episodeJSON = episode.toJSON(); if (episodeJSON.season && episodeJSON.season.entry) { episodeJSON.entry = episodeJSON.season.entry; @@ -68,7 +67,6 @@ class EpisodeService { return modifiedEpisodes; } - } module.exports = new EpisodeService(); diff --git a/backend/services/importerService.js b/backend/services/importerService.js index 036b279..0c7b3f5 100644 --- a/backend/services/importerService.js +++ b/backend/services/importerService.js @@ -15,15 +15,13 @@ async function bulkImportMovies(movies) { const waitTime = 10000; let entries = []; - let overAllFetches = 0 + let overAllFetches = 0; let currenFetch = 0; // ? gettings all entries from db const entriesFromDb = await Entry.findAll({ - include: [ - { model: EntryId, as: 'entryId' } - ] - }) + include: [{ model: EntryId, as: "entryId" }], + }); // ? creating a dict from the entries const entriesDict = entriesFromDb.reduce((dict, entry) => { @@ -32,20 +30,30 @@ async function bulkImportMovies(movies) { }, {}); for (const movie of movies) { - if (entriesDict[movie.tmdbId]) { - console.log(`Entry already exists: ${entriesDict[movie.tmdbId].title} (${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: "" }); + 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 - } - }); + await EntryRating.update( + { user_rating: movie.userRating }, + { + where: { + entry_id: entriesDict[movie.tmdbId].id, + }, + }, + ); } } else { const data = await fetchEntryData(movie.tmdbId, false); @@ -55,20 +63,27 @@ async function bulkImportMovies(movies) { const entry = await saveEntry(data); // ? adding date seen - await EntrySeen.create({ entry_id: entry.id, date_seen: movie.dateSeen, seen_with: "" }); + 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 - } - }); + await EntryRating.update( + { user_rating: movie.userRating }, + { + where: { + entry_id: entry.id, + }, + }, + ); } - entries.push(entry) + entries.push(entry); // ? wait 100ms between each tmdb fetch - await new Promise(resolve => setTimeout(resolve, fetchInterval)); + await new Promise((resolve) => setTimeout(resolve, fetchInterval)); console.log(`${currenFetch} imported id: ${movie.tmdbId}`); currenFetch++; overAllFetches++; @@ -76,31 +91,28 @@ async function bulkImportMovies(movies) { // ? stop 10 seconds after 35 tmdb fetch if (currenFetch == maxFetches) { console.log(`Now waiting ${waitTime / 1000} seconds...`); - await new Promise(resolve => setTimeout(resolve, waitTime)); + 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 overAllFetches = 0; let currentFetch = 0; // ? gettings all entries from db const entriesFromDb = await Entry.findAll({ - include: [ - { model: EntryId, as: 'entryId' } - ] - }) + include: [{ model: EntryId, as: "entryId" }], + }); // ? creating a dict from the entries const entriesDict = entriesFromDb.reduce((dict, entry) => { @@ -112,7 +124,9 @@ async function bulkImportTmdb(movies) { for (const movie of movies) { if (entriesDict[movie]) { - console.log(`Entry already exists: ${entriesDict[movie].title} (${movie})`) + console.log( + `Entry already exists: ${entriesDict[movie].title} (${movie})`, + ); created.push(movie); } else { if (created.includes(movie)) continue; // * skip doubles @@ -122,20 +136,21 @@ async function bulkImportTmdb(movies) { console.log(`${currentFetch} data null for id: ${movie.id}`); } - // ? saving the entry const entry = await saveEntry(data); - entries.push(entry) - created.push(movie) + 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}`); + 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).`) + console.log(`With ${data.seasons.length} season(s).`); currentFetch++; overAllFetches++; @@ -143,42 +158,40 @@ async function bulkImportTmdb(movies) { // ? stop 10 seconds after 35 tmdb fetch if (currentFetch >= maxFetches) { console.log(`Now waiting ${waitTime / 1000} seconds...`); - await new Promise(resolve => setTimeout(resolve, waitTime)); + 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 - } - } - }) + [Op.ne]: 3, + }, + }, + }); // ? gettings all entries from db const entriesFromDb = await Entry.findAll({ where: { - is_tvseries: 1 + is_tvseries: 1, }, include: [ - { model: EntryId, as: 'entryId' }, + { model: EntryId, as: "entryId" }, { - model: Season, as: 'seasons', include: - [ - { model: Episode, as: 'episodes' } - ] - } - ] - }) + model: Season, + as: "seasons", + include: [{ model: Episode, as: "episodes" }], + }, + ], + }); // ? creating two dictionnaries names & ids const idsDict = entriesFromDb.reduce((dict, entry) => { @@ -198,14 +211,16 @@ async function bulkImportEpisodes(episodesSeen) { for (let i = 0; i < episodesSeen.length; i++) { let theEntry; - if (episodesSeen[i].type == 'id') { + if (episodesSeen[i].type == "id") { theEntry = idsDict[episodesSeen[i].id]; - } else if (episodesSeen[i].type == 'title') { + } 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})`); + console.log( + `No entry found for line ${i + 1} (${episodesSeen[i].id || episodesSeen[i].title})`, + ); continue; } @@ -221,18 +236,22 @@ async function bulkImportEpisodes(episodesSeen) { 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}`); + 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, '')}`; + 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 + seen_with: episodesSeen[i].seen_with, }); added[id] = true; rows++; @@ -243,11 +262,13 @@ async function bulkImportEpisodes(episodesSeen) { } } - console.log(`rows:${rows}, seasons:${seasons}, episodes:${episodes} (out of ${episodesSeen.length})`) + console.log( + `rows:${rows}, seasons:${seasons}, episodes:${episodes} (out of ${episodesSeen.length})`, + ); console.log(added); return rows; } catch (error) { - console.log(error) + console.log(error); } } @@ -255,4 +276,4 @@ module.exports = { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes, -}; \ No newline at end of file +}; diff --git a/backend/services/logService.js b/backend/services/logService.js index 4b4a729..fc4cfb3 100644 --- a/backend/services/logService.js +++ b/backend/services/logService.js @@ -1,14 +1,14 @@ // logService.js -const fs = require('fs'); -const util = require('util'); -const moment = require('../utils/moment'); +const fs = require("fs"); +const util = require("util"); +const moment = require("../utils/moment"); // Convert fs.writeFile to a promise-based function const writeFile = util.promisify(fs.writeFile); // Ensure the log file exists and is accessible -const logFilePath = 'showy.log'; -fs.open(logFilePath, 'a', (err, fd) => { +const logFilePath = "showy.log"; +fs.open(logFilePath, "a", (err, fd) => { if (err) { console.error("Failed to open log file:", err); } else { @@ -21,10 +21,10 @@ fs.open(logFilePath, 'a', (err, fd) => { // Asynchronous function to append a message to the log file async function logToFile(message) { try { - const time = moment().format('YYYY-MM-DD HH:mm:ss') + const time = moment().format("YYYY-MM-DD HH:mm:ss"); const formatedMsg = `[${time}] ${message}`; console.log(formatedMsg); - await writeFile(logFilePath, formatedMsg + '\n', { flag: 'a' }); + await writeFile(logFilePath, formatedMsg + "\n", { flag: "a" }); } catch (err) { console.error("Failed to write to log file:", err); } @@ -32,4 +32,4 @@ async function logToFile(message) { module.exports = { logToFile, -}; \ No newline at end of file +}; diff --git a/backend/services/mediaDownloaderService.js b/backend/services/mediaDownloaderService.js index 391ff2d..595bc91 100644 --- a/backend/services/mediaDownloaderService.js +++ b/backend/services/mediaDownloaderService.js @@ -1,10 +1,10 @@ -const path = require('path'); -const fs = require('fs'); -const { default: axios } = require('axios'); -const { v4: uuidv4 } = require('uuid'); +const path = require("path"); +const fs = require("fs"); +const { default: axios } = require("axios"); +const { v4: uuidv4 } = require("uuid"); const { logToFile } = require("./logService"); -const configService = require('./configService'); +const configService = require("./configService"); const _configService = configService; @@ -27,24 +27,52 @@ class MediaDownloaderService { const dataPath = _configService.getSettings().userDataPath; - const hasPoster = collection.medias && collection.medias.filter((m) => m.type == 'poster').length != 0; + const hasPoster = + collection.medias && + collection.medias.filter((m) => m.type == "poster").length != 0; if (collection.posterPath && !hasPoster) { - const postersDir = path.join(dataPath, 'images', 'collections', 'posters') - this.scheduleDownloads({ file_path: collection.posterPath }, 'poster', postersDir, downloadTasks, downloadedImages); + const postersDir = path.join( + dataPath, + "images", + "collections", + "posters", + ); + this.scheduleDownloads( + { file_path: collection.posterPath }, + "poster", + postersDir, + downloadTasks, + downloadedImages, + ); } - const hasBackdrop = collection.medias && collection.medias.filter((m) => m.type == 'backdrop').length != 0; + const hasBackdrop = + collection.medias && + collection.medias.filter((m) => m.type == "backdrop").length != 0; if (collection.backdropPath && !hasBackdrop) { - const backdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops') - this.scheduleDownloads({ file_path: collection.backdropPath }, 'backdrop', backdropsDir, downloadTasks, downloadedImages); + const backdropsDir = path.join( + dataPath, + "images", + "collections", + "backdrops", + ); + this.scheduleDownloads( + { file_path: collection.backdropPath }, + "backdrop", + backdropsDir, + downloadTasks, + downloadedImages, + ); } // Wait for all downloads to complete - await Promise.all(downloadTasks).then(() => { - console.log('Downloaded images:', downloadedImages); - }).catch(err => { - console.error('Error downloading entry images:', err); - }); + await Promise.all(downloadTasks) + .then(() => { + console.log("Downloaded images:", downloadedImages); + }) + .catch((err) => { + console.error("Error downloading entry images:", err); + }); return downloadedImages; } @@ -61,32 +89,56 @@ class MediaDownloaderService { const dataPath = _configService.getSettings().userDataPath; // Check if person already has a profile image - const hasProfile = person.medias && person.medias.filter((m) => m.type === 'profile').length !== 0; + const hasProfile = + person.medias && + person.medias.filter((m) => m.type === "profile").length !== 0; if (person.profile_path && !hasProfile) { - const profilesDir = path.join(dataPath, 'images', 'peoples', 'profiles'); - this.scheduleDownloads({ file_path: person.profile_path }, 'profile', profilesDir, downloadTasks, downloadedImages); + const profilesDir = path.join(dataPath, "images", "peoples", "profiles"); + this.scheduleDownloads( + { file_path: person.profile_path }, + "profile", + profilesDir, + downloadTasks, + downloadedImages, + ); } // Wait for all downloads to complete - await Promise.all(downloadTasks).then(() => { - console.log('Downloaded images:', downloadedImages); - }).catch(err => { - console.error('Error downloading entry images:', err); - }); + await Promise.all(downloadTasks) + .then(() => { + console.log("Downloaded images:", downloadedImages); + }) + .catch((err) => { + console.error("Error downloading entry images:", err); + }); return downloadedImages; } // Utility to find the preferred media (English if available, otherwise the first one) - findPreferredMedia(mediaArray, preferredLanguage = 'en') { - return mediaArray.find(media => media.iso_639_1 === preferredLanguage && !media.file_path.includes('.svg')) || mediaArray.find(media => !media.file_path.includes('.svg')) || mediaArray[0]; + findPreferredMedia(mediaArray, preferredLanguage = "en") { + return ( + mediaArray.find( + (media) => + media.iso_639_1 === preferredLanguage && + !media.file_path.includes(".svg"), + ) || + mediaArray.find((media) => !media.file_path.includes(".svg")) || + mediaArray[0] + ); } // Adjusted scheduleDownloads to accept local arrays - scheduleDownloads(media, mediaType, mediaDir, downloadTasks, downloadedImages) { + scheduleDownloads( + media, + mediaType, + mediaDir, + downloadTasks, + downloadedImages, + ) { const uniqueFilename = uuidv4(); - const extension = media.file_path.split('.').pop(); + const extension = media.file_path.split(".").pop(); const url = `https://image.tmdb.org/t/p/original${media.file_path}`; const filename = `${uniqueFilename}.${extension}`; @@ -96,42 +148,46 @@ class MediaDownloaderService { downloadTasks.push( this.downloadImage(url, downloadPath) .then(() => { - logToFile(`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`) - downloadedImages.push({ type: mediaType, path: filename }) - }) - .catch(err => { - logToFile(`Media Service | failed to download: ${mediaType}, path:${downloadPath} url:${url}`) - logToFile(err) - console.error(`Error downloading ${mediaType}:`, err) + logToFile( + `Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`, + ); + downloadedImages.push({ type: mediaType, path: filename }); }) + .catch((err) => { + logToFile( + `Media Service | failed to download: ${mediaType}, path:${downloadPath} url:${url}`, + ); + logToFile(err); + console.error(`Error downloading ${mediaType}:`, err); + }), ); } async downloadImage(url, filePath) { const response = await axios({ url: url, - method: 'GET', - responseType: 'stream' + method: "GET", + responseType: "stream", }); const writer = fs.createWriteStream(filePath); response.data.pipe(writer); return new Promise((resolve, reject) => { - writer.on('finish', resolve); - writer.on('error', reject); + writer.on("finish", resolve); + writer.on("error", reject); }); } async downloadFile(url) { const response = await axios({ url: url, - method: 'GET', - responseType: 'stream' + method: "GET", + responseType: "stream", }); return response; } } -module.exports = new MediaDownloaderService(); \ No newline at end of file +module.exports = new MediaDownloaderService(); diff --git a/backend/services/mediaManager.js b/backend/services/mediaManager.js index e02458b..37bd424 100644 --- a/backend/services/mediaManager.js +++ b/backend/services/mediaManager.js @@ -1,5 +1,5 @@ -const path = require('path'); -const { v4: uuidv4 } = require('uuid'); +const path = require("path"); +const { v4: uuidv4 } = require("uuid"); const Entry = require("../models/Entry"); @@ -11,9 +11,9 @@ const tmdbService = require("./tmdbService"); const mediaService = require("./mediaService"); const mediaDownloaderService = require("./mediaDownloaderService"); const mediaOptimizerService = require("./mediaOptimizerService"); -const Season = require('../models/Season'); -const storageService = require('./storageService'); -const Media = require('../models/Media'); +const Season = require("../models/Season"); +const storageService = require("./storageService"); +const Media = require("../models/Media"); const _configService = configService; const _mediaService = mediaService; @@ -23,7 +23,6 @@ const _mediaDownloaderService = mediaDownloaderService; const _storageService = storageService; class MediaManager { - constructor() { if (!MediaManager.instance) { MediaManager.instance = this; @@ -32,7 +31,6 @@ class MediaManager { } async saveMedia(entryId, files) { - if (!files) { throw new BadRequestError("No media uploaded"); } @@ -42,7 +40,9 @@ class MediaManager { throw new NotFoundError("Entry not found"); } - const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]); + const fileType = ["poster", "backdrop", "logo"].find( + (type) => req.files[type], + ); if (!fileType) { throw new BadRequestError("Invalid media type"); @@ -51,31 +51,38 @@ class MediaManager { // * 1 - save the media into database const file = req.files[fileType][0]; const createdMedia = await _mediaService.createMedia({ - mediaable: 'entry', + mediaable: "entry", mediaableId: id, type: fileType, path: file.filename, isLocal: true, isSelected: false, - isCustom: true + isCustom: true, }); // * 2 - generating low resolution preview - _mediaOptimizerService.generatePreviewFiles('entries', fileType + 's', file.filename).then((result) => { - const stream = fs.createReadStream(filePath); - stream.pipe(res); + _mediaOptimizerService + .generatePreviewFiles("entries", fileType + "s", file.filename) + .then((result) => { + const stream = fs.createReadStream(filePath); + stream.pipe(res); - const msg = `Media Route | Generated Entry Preview` - logToFile(msg); - }).catch((err) => { - const msg = `Media Route | Error Generating Entry Preview` - logToFile(msg); - }); + const msg = `Media Route | Generated Entry Preview`; + logToFile(msg); + }) + .catch((err) => { + const msg = `Media Route | Error Generating Entry Preview`; + logToFile(msg); + }); return createdMedia; } - async getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos', 'backdrops']) { + async getEntryMedia( + tmdb_id, + is_tvserie, + includes = ["posters", "logos", "backdrops"], + ) { // Fetching entry media const mediaData = await _tmdbService.fetchEntryMedia(tmdb_id, is_tvserie); if (!mediaData) { @@ -93,28 +100,44 @@ class MediaManager { // Handling different media types const mediaTypes = [ - { type: 'posters', dir: path.join(dataPath, 'images', 'entries', 'posters') }, - { type: 'logos', dir: path.join(dataPath, 'images', 'entries', 'logos') }, - { type: 'backdrops', dir: path.join(dataPath, 'images', 'entries', 'backdrops') } + { + type: "posters", + dir: path.join(dataPath, "images", "entries", "posters"), + }, + { type: "logos", dir: path.join(dataPath, "images", "entries", "logos") }, + { + type: "backdrops", + dir: path.join(dataPath, "images", "entries", "backdrops"), + }, ]; mediaTypes.forEach(({ type, dir }) => { if (!includes.includes(type)) return; // ? the media type is not requested if (mediaData[type] && mediaData[type].length) { - const selectedMedia = _mediaDownloaderService.findPreferredMedia(mediaData[type]); + const selectedMedia = _mediaDownloaderService.findPreferredMedia( + mediaData[type], + ); if (selectedMedia) { - _mediaDownloaderService.scheduleDownloads(selectedMedia, type.slice(0, -1), dir, downloadTasks, downloadedImages); + _mediaDownloaderService.scheduleDownloads( + selectedMedia, + type.slice(0, -1), + dir, + downloadTasks, + downloadedImages, + ); } } }); // Wait for all downloads to complete - await Promise.all(downloadTasks).then(() => { - console.log('Downloaded images:', downloadedImages); - }).catch(err => { - console.error('Error downloading entry images:', err); - }); + await Promise.all(downloadTasks) + .then(() => { + console.log("Downloaded images:", downloadedImages); + }) + .catch((err) => { + console.error("Error downloading entry images:", err); + }); return downloadedImages; } @@ -125,23 +148,32 @@ class MediaManager { const file = await _mediaDownloaderService.downloadFile(url); const uniqueFilename = uuidv4(); - const extension = season.poster_path.split('.').pop(); + const extension = season.poster_path.split(".").pop(); const filename = `${uniqueFilename}.${extension}`; const dataPath = _configService.getSettings().userDataPath; - const fullFilePath = path.join(dataPath, 'images', 'seasons', 'posters', filename) + const fullFilePath = path.join( + dataPath, + "images", + "seasons", + "posters", + filename, + ); - _storageService.storeFile(file, fullFilePath).then(async () => { - await Media.create({ - mediaable: 'season', - mediaableId: season.id, - type: 'poster', - path: filename, - isLocal: true, - isSelected: true - }); - console.log(`File created for season: ${filename}`); - }).catch(); + _storageService + .storeFile(file, fullFilePath) + .then(async () => { + await Media.create({ + mediaable: "season", + mediaableId: season.id, + type: "poster", + path: filename, + isLocal: true, + isSelected: true, + }); + console.log(`File created for season: ${filename}`); + }) + .catch(); } async getEpisodenMedia(episode) { @@ -150,25 +182,33 @@ class MediaManager { const file = await _mediaDownloaderService.downloadFile(url); const uniqueFilename = uuidv4(); - const extension = episode.still_path.split('.').pop(); + const extension = episode.still_path.split(".").pop(); const filename = `${uniqueFilename}.${extension}`; const dataPath = _configService.getSettings().userDataPath; - const fullFilePath = path.join(dataPath, 'images', 'episodes', 'stills', filename) + const fullFilePath = path.join( + dataPath, + "images", + "episodes", + "stills", + filename, + ); - _storageService.storeFile(file, fullFilePath).then(async () => { - await Media.create({ - mediaable: 'episode', - mediaableId: episode.id, - type: 'still', - path: filename, - isLocal: true, - isSelected: true - }); - console.log(`File created for episode: ${filename}`); - }).catch(); + _storageService + .storeFile(file, fullFilePath) + .then(async () => { + await Media.create({ + mediaable: "episode", + mediaableId: episode.id, + type: "still", + path: filename, + isLocal: true, + isSelected: true, + }); + console.log(`File created for episode: ${filename}`); + }) + .catch(); } - } module.exports = new MediaManager(); diff --git a/backend/services/mediaOptimizerService.js b/backend/services/mediaOptimizerService.js index 305a32d..b999c73 100644 --- a/backend/services/mediaOptimizerService.js +++ b/backend/services/mediaOptimizerService.js @@ -1,12 +1,11 @@ -const path = require('path'); -const sharp = require('sharp'); +const path = require("path"); +const sharp = require("sharp"); -const configService = require('./configService'); +const configService = require("./configService"); const _configService = configService; class MediaOptimizerService { - constructor() { if (!MediaOptimizerService.instance) { MediaOptimizerService.instance = this; @@ -15,29 +14,44 @@ class MediaOptimizerService { } // todo rename this function to prepareAndGeneratePreview - doGeneratePreview(fileCategory, fileType, originalFileName, previewWidth = 0, previewQuality = 80) { + doGeneratePreview( + fileCategory, + fileType, + originalFileName, + previewWidth = 0, + previewQuality = 80, + ) { const dataPath = _configService.getSettings().userDataPath; - const mediaPath = path.join(dataPath, 'images', fileCategory, fileType); + const mediaPath = path.join(dataPath, "images", fileCategory, fileType); const originalPath = path.join(mediaPath, originalFileName); - const fileNameWithoutExt = originalFileName.split('.')[0]; - const previewFileName = fileNameWithoutExt + '_preview.jpg'; + const fileNameWithoutExt = originalFileName.split(".")[0]; + const previewFileName = fileNameWithoutExt + "_preview.jpg"; const previewPath = path.join(mediaPath, previewFileName); if (previewWidth == 0) { previewWidth = 342; // ? poster - if (fileType == 'backdrops') previewWidth = 780; - if (fileType == 'logos') previewWidth = 300; + if (fileType == "backdrops") previewWidth = 780; + if (fileType == "logos") previewWidth = 300; } - if (fileType == 'logos') { - return this.generatePreview(originalPath, previewPath.replace('.jpg', '.png'), previewWidth); + if (fileType == "logos") { + return this.generatePreview( + originalPath, + previewPath.replace(".jpg", ".png"), + previewWidth, + ); // return sharp(originalPath) // .resize({ width: previewWidth }) // .toFile(previewPath.replace('.jpg', '.png')); } else { - return this.generatePreview(originalPath, previewPath, previewWidth, previewQuality); + return this.generatePreview( + originalPath, + previewPath, + previewWidth, + previewQuality, + ); // return sharp(originalPath) // .resize({ width: previewWidth }) // .jpeg({ quality: previewQuality }) @@ -45,13 +59,17 @@ class MediaOptimizerService { } } - generatePreview(originalPath, previewPath, previewWidth, previewQuality = 80) { + generatePreview( + originalPath, + previewPath, + previewWidth, + previewQuality = 80, + ) { return sharp(originalPath) .resize({ width: previewWidth }) .jpeg({ quality: previewQuality }) .toFile(previewPath); } - } -module.exports = new MediaOptimizerService(); \ No newline at end of file +module.exports = new MediaOptimizerService(); diff --git a/backend/services/mediaService.js b/backend/services/mediaService.js index d0638b5..618657d 100644 --- a/backend/services/mediaService.js +++ b/backend/services/mediaService.js @@ -1,7 +1,6 @@ const Media = require("../models/Media"); class MediaService { - constructor() { if (!MediaService.instance) { MediaService.instance = this; @@ -14,7 +13,6 @@ class MediaService { return media; } - } -module.exports = new MediaService(); \ No newline at end of file +module.exports = new MediaService(); diff --git a/backend/services/models-services/entryService.js b/backend/services/models-services/entryService.js index b9c62dd..068aed3 100644 --- a/backend/services/models-services/entryService.js +++ b/backend/services/models-services/entryService.js @@ -1,23 +1,23 @@ -const moment = require('../../utils/moment.js'); +const moment = require("../../utils/moment.js"); -const { fetchSeasonData, fetchEntryData } = require('../tmdbService.js'); -const { getEntryMedia, doGeneratePreview } = require('../mediaService.js'); -const { logToFile } = require('../logService.js'); +const { fetchSeasonData, fetchEntryData } = require("../tmdbService.js"); +const { getEntryMedia, doGeneratePreview } = require("../mediaService.js"); +const { logToFile } = require("../logService.js"); -const NotFoundError = require('../../errors/NotFoundError.js'); -const InternalServerError = require('../../errors/InternalServerError.js'); +const NotFoundError = require("../../errors/NotFoundError.js"); +const InternalServerError = require("../../errors/InternalServerError.js"); -const { ValidationError, Op } = require('sequelize'); -const Collection = require('../../models/Collection.js'); -const Entry = require('../../models/Entry.js') -const EntryId = require('../../models/EntryId.js') -const EntryRating = require('../../models/EntryRating.js'); -const Season = require('../../models/Season.js'); -const EntryGenre = require('../../models/EntryGenre.js'); -const EntrySeen = require('../../models/EntrySeen.js'); -const Episode = require('../../models/Episode.js'); -const Media = require('../../models/Media.js'); -const Genre = require('../../models/Genre.js'); +const { ValidationError, Op } = require("sequelize"); +const Collection = require("../../models/Collection.js"); +const Entry = require("../../models/Entry.js"); +const EntryId = require("../../models/EntryId.js"); +const EntryRating = require("../../models/EntryRating.js"); +const Season = require("../../models/Season.js"); +const EntryGenre = require("../../models/EntryGenre.js"); +const EntrySeen = require("../../models/EntrySeen.js"); +const Episode = require("../../models/Episode.js"); +const Media = require("../../models/Media.js"); +const Genre = require("../../models/Genre.js"); async function saveEntry(data) { try { @@ -35,7 +35,10 @@ async function saveEntry(data) { tagline: data.tagline || null, storyline: data.overview, - country: data.production_countries.length > 0 ? data.production_countries[0].name : null, + country: + data.production_countries.length > 0 + ? data.production_countries[0].name + : null, is_tvseries: is_tvseries, watchlist: true, @@ -46,7 +49,7 @@ async function saveEntry(data) { poster_path: data.poster_path, banner_path: data.backdrop_path, - last_fetch: new Date() + last_fetch: new Date(), }); const savedEntry = await movie.save(); @@ -62,8 +65,8 @@ async function saveEntry(data) { data.genres.forEach(async (genre) => { await EntryGenre.create({ genre_id: genre.id, - entry_id: savedEntry.id - }) + entry_id: savedEntry.id, + }); }); // ? ratings @@ -95,7 +98,7 @@ async function saveEntry(data) { poster_path: seasonData.poster_path, banner_path: null, - }) + }); // * episodes let episodes = []; @@ -122,43 +125,41 @@ async function saveEntry(data) { // TODO fetch cast - savedSeason.setDataValue('episodes', episodes); - seasons.push(savedSeason) + savedSeason.setDataValue("episodes", episodes); + seasons.push(savedSeason); } - savedEntry.setDataValue('seasons', seasons); + savedEntry.setDataValue("seasons", seasons); } // + end of: seasons & episodes for tv series // ? cast - // ? media const downloadedImages = await getEntryMedia(data.id, is_tvseries); // console.log(`entry service, downloaded images: `, downloadedImages) for (const image of downloadedImages) { await Media.create({ - mediaable: 'entry', + mediaable: "entry", mediaableId: savedEntry.id, type: image.type, path: image.path, isLocal: true, - isSelected: true + isSelected: true, }); - doGeneratePreview('entries', image.type + 's', image.path); + doGeneratePreview("entries", image.type + "s", image.path); } + const currentGenresNames = await data.genres.map((genre) => genre.name); - const currentGenresNames = await data.genres.map(genre => genre.name); - - savedEntry.setDataValue('entryId', ids); - savedEntry.setDataValue('entryRating', ratings); - savedEntry.setDataValue('genres', currentGenresNames); + savedEntry.setDataValue("entryId", ids); + savedEntry.setDataValue("entryRating", ratings); + savedEntry.setDataValue("genres", currentGenresNames); return savedEntry; } catch (error) { console.log(`Error saving entry (in entry serive): `, error); - return null + return null; } } @@ -171,7 +172,10 @@ async function updateEntry(oldEntry, data) { tagline: data.tagline || null, storyline: data.overview, - country: data.production_countries.length > 0 ? data.production_countries[0].name : null, + country: + data.production_countries.length > 0 + ? data.production_countries[0].name + : null, status: data.status, @@ -190,11 +194,11 @@ async function updateEntry(oldEntry, data) { // update ratings const ratings = await oldEntry.entryRating.update({ - tmdb_rating: data.vote_average + tmdb_rating: data.vote_average, }); // update genres - const currentGenresIds = oldEntry.genres.map(genre => genre.id); + const currentGenresIds = oldEntry.genres.map((genre) => genre.id); let currentGenresNames = []; data.genres.forEach(async (genre) => { // add genres names to an array so it can be returned with the entry object @@ -206,12 +210,14 @@ async function updateEntry(oldEntry, data) { // otherwise assign the genre to the entry await EntryGenre.create({ genre_id: genre.id, - entry_id: savedEntry.id - }) + entry_id: savedEntry.id, + }); }); // fetch entry-seens - const entrySeens = await EntrySeen.findAll({ where: { entry_id: oldEntry.id } }); + const entrySeens = await EntrySeen.findAll({ + where: { entry_id: oldEntry.id }, + }); // TODO: refrech seasons if (oldEntry.is_tvseries) { @@ -224,8 +230,8 @@ async function updateEntry(oldEntry, data) { // Fetch existing season if it exists (using tmdb_id) let existingSeason = await Season.findOne({ where: { - tmdb_id: season.id - } + tmdb_id: season.id, + }, }); // If the season exists, update it; otherwise, create a new season @@ -269,7 +275,7 @@ async function updateEntry(oldEntry, data) { let existingEpisode = await Episode.findOne({ where: { tmdb_id: episode.id, - } + }, }); // If the episode exists, update it; otherwise, create a new episode @@ -309,19 +315,18 @@ async function updateEntry(oldEntry, data) { } // Update the episodes of the current season - existingSeason.setDataValue('episodes', updatedEpisodes); + existingSeason.setDataValue("episodes", updatedEpisodes); updatedSeasons.push(existingSeason); } // Update the seasons of the movie - savedEntry.setDataValue('seasons', updatedSeasons); + savedEntry.setDataValue("seasons", updatedSeasons); } - - savedEntry.setDataValue('entryId', ids); - savedEntry.setDataValue('entryRating', ratings); - savedEntry.setDataValue('genres', currentGenresNames); - savedEntry.setDataValue('entrySeen', entrySeens); + savedEntry.setDataValue("entryId", ids); + savedEntry.setDataValue("entryRating", ratings); + savedEntry.setDataValue("genres", currentGenresNames); + savedEntry.setDataValue("entrySeen", entrySeens); return savedEntry; } @@ -332,25 +337,24 @@ async function refrechEntry(entryId) { // ! note: the includes are required for the update const oldEntry = await Entry.findByPk(entryId, { include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: EntrySeen, as: 'entrySeen' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: EntrySeen, as: "entrySeen" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, { - model: Collection, as: 'collections', - include: [ - { model: Media, as: 'medias' } - ] + model: Collection, + as: "collections", + include: [{ model: Media, as: "medias" }], }, { model: Genre, - as: 'genres', - } + as: "genres", + }, ], order: [ - [{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list - ] + [{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"], // Order the entry-seen list + ], }); if (!oldEntry) { @@ -358,7 +362,10 @@ async function refrechEntry(entryId) { } // ? getting new data from TMDB - const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); + const entryData = await fetchEntryData( + oldEntry.entryId.tmdb_id, + oldEntry.is_tvseries, + ); if (entryData == null) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } @@ -373,14 +380,17 @@ async function refrechEntry(entryId) { tagline: entryData.tagline || null, storyline: entryData.overview, - country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null, + country: + entryData.production_countries.length > 0 + ? entryData.production_countries[0].name + : null, status: entryData.status, poster_path: entryData.poster_path, banner_path: entryData.backdrop_path, - last_fetch: new Date() + last_fetch: new Date(), }; const savedEntry = await oldEntry.update(newData); @@ -393,11 +403,11 @@ async function refrechEntry(entryId) { // * updating ratings await oldEntry.entryRating.update({ - tmdb_rating: entryData.vote_average + tmdb_rating: entryData.vote_average, }); // * updating genres - const currentGenresIds = oldEntry.genres.map(genre => genre.id); + const currentGenresIds = oldEntry.genres.map((genre) => genre.id); entryData.genres.forEach(async (genre) => { // if the entry already has this genre then skip if (currentGenresIds.includes(genre.id)) return; @@ -405,26 +415,28 @@ async function refrechEntry(entryId) { // otherwise assign the genre to the entry await EntryGenre.create({ genre_id: genre.id, - entry_id: savedEntry.id - }) + entry_id: savedEntry.id, + }); }); - // * For TV-Series (Seasons & Episodes) if (oldEntry.is_tvseries) { // ? Only refrech if the series's status is not 'Ended' - // ? and atleast 48 hours has passed + // ? and atleast 48 hours has passed // * Update or insert seasons for the entry for (const season of entryData.seasons) { // fetch new season data from tmdb - let seasonData = await fetchSeasonData(entryData.id, season.season_number); + let seasonData = await fetchSeasonData( + entryData.id, + season.season_number, + ); // Fetch existing season if it exists (using tmdb_id) let existingSeason = await Season.findOne({ where: { - tmdb_id: season.id - } + tmdb_id: season.id, + }, }); // If the season exists, update it; otherwise, create a new season @@ -464,7 +476,7 @@ async function refrechEntry(entryId) { let existingEpisode = await Episode.findOne({ where: { tmdb_id: episode.id, - } + }, }); // If the episode exists, update it; otherwise, create a new episode @@ -512,12 +524,12 @@ async function refrechEntry(entryId) { // ? count media by type let availableMedia = { - 'posters': 0, - 'logos': 0, - 'backdrops': 0 + posters: 0, + logos: 0, + backdrops: 0, }; for (let i = 0; i < oldEntry.medias.length; i++) { - availableMedia[oldEntry.medias[i].type + 's'] += 1; + availableMedia[oldEntry.medias[i].type + "s"] += 1; } // ? if the count of a media type == 0, the add the type to mediaToGet @@ -528,26 +540,32 @@ async function refrechEntry(entryId) { let downloadedImages; if (mediaToGet.length != 0) { - downloadedImages = await getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet); + downloadedImages = await getEntryMedia( + entryData.id, + oldEntry.is_tvseries, + mediaToGet, + ); } if (downloadedImages) { for (const image of downloadedImages) { await Media.create({ - mediaable: 'entry', + mediaable: "entry", mediaableId: oldEntry.id, type: image.type, path: image.path, isLocal: true, - isSelected: true + isSelected: true, }); } } // ? fetch collection if (entryData.belongs_to_collection) { - const collectionService = require('../collectionService.js'); - await collectionService.createOrUpdateCollection(entryData.belongs_to_collection.id); + const collectionService = require("../collectionService.js"); + await collectionService.createOrUpdateCollection( + entryData.belongs_to_collection.id, + ); } // + end of: refrech logic @@ -573,53 +591,49 @@ async function refrechEntry(entryId) { const updatedEntry = await Entry.findByPk(entryId, { include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: EntrySeen, as: 'entrySeen' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: EntrySeen, as: "entrySeen" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, { - model: Collection, as: 'collections', - include: [ - { model: Media, as: 'medias' } - ] + model: Collection, + as: "collections", + include: [{ model: Media, as: "medias" }], }, { model: Genre, - as: 'genres', - attributes: ['name'], // Only fetch the genre ID + as: "genres", + attributes: ["name"], // Only fetch the genre ID through: { - attributes: [] // Do not fetch any attributes from the join table - } - } + attributes: [], // Do not fetch any attributes from the join table + }, + }, ], order: [ - [{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list - ] + [{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"], // Order the entry-seen list + ], }); const plainEntry = updatedEntry.get({ plain: true }); - plainEntry.genres = plainEntry.genres.map(genre => genre.name); + plainEntry.genres = plainEntry.genres.map((genre) => genre.name); return plainEntry; } /** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today -*/ + */ async function SyncSeriesData() { - const today = moment().format('YYYY-MM-DD'); + const today = moment().format("YYYY-MM-DD"); const entries = await Entry.findAll({ where: { is_tvseries: true, autoSync: true, last_fetch: { - [Op.ne]: today + [Op.ne]: today, }, status: { - [Op.notIn]: [ - 'Ended', - 'Canceled' - ] + [Op.notIn]: ["Ended", "Canceled"], }, }, }); @@ -627,7 +641,7 @@ async function SyncSeriesData() { logToFile(`Started syncing ${entries.length} Tv-Series`); const results = await Promise.all( - entries.map(entry => SyncSerieData(entry.id)) + entries.map((entry) => SyncSerieData(entry.id)), ); logToFile(`Syncing Tv-Series Finished`); @@ -637,30 +651,31 @@ async function SyncSeriesData() { async function SyncSerieData(entryId) { const oldEntry = await Entry.findByPk(entryId, { include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: EntrySeen, as: 'entrySeen' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: EntrySeen, as: "entrySeen" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, { model: Genre, - as: 'genres', - attributes: ['id'], + as: "genres", + attributes: ["id"], through: { - attributes: [] - } - } - ] + attributes: [], + }, + }, + ], }); - logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`) + logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`); - if (!oldEntry) - throw NotFoundError('Entry Not Found'); - const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); + if (!oldEntry) throw NotFoundError("Entry Not Found"); + const entryData = await fetchEntryData( + oldEntry.entryId.tmdb_id, + oldEntry.is_tvseries, + ); - if (!entryData) - throw new ValidationError(`Couldn't Fetch Entry Data`); + if (!entryData) throw new ValidationError(`Couldn't Fetch Entry Data`); // ! 1 - Normal Data let newData = { @@ -671,14 +686,17 @@ async function SyncSerieData(entryId) { tagline: entryData.tagline || null, storyline: entryData.overview, - country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null, + country: + entryData.production_countries.length > 0 + ? entryData.production_countries[0].name + : null, status: entryData.status, poster_path: entryData.poster_path, banner_path: entryData.backdrop_path, - last_fetch: new Date() + last_fetch: new Date(), }; await oldEntry.update(newData); @@ -691,30 +709,39 @@ async function SyncSerieData(entryId) { // ! 3 - Ratings await oldEntry.entryRating.update({ - tmdb_rating: entryData.vote_average + tmdb_rating: entryData.vote_average, }); // ! 4 - Genres - const currentGenresIds = oldEntry.genres.map(genre => genre.id); + const currentGenresIds = oldEntry.genres.map((genre) => genre.id); entryData.genres.forEach(async (genre) => { // ? only assing the genre if its not already asigned if (!currentGenresIds.includes(genre.id)) { await EntryGenre.create({ genre_id: genre.id, - entry_id: oldEntry.id - }) + entry_id: oldEntry.id, + }); } }); // ! 5 - Seasons // ? only update the last seasons available + season 0 (specials) if (oldEntry.is_tvseries) { - const latestAvailableSeason = await Math.max(...oldEntry.seasons.map(s => s.season_number)); + const latestAvailableSeason = await Math.max( + ...oldEntry.seasons.map((s) => s.season_number), + ); for (const season of entryData.seasons) { - if (season.season_number != 0 && season.season_number != latestAvailableSeason) continue; + if ( + season.season_number != 0 && + season.season_number != latestAvailableSeason + ) + continue; // ? fetch new season data from tmdb - let seasonData = await fetchSeasonData(oldEntry.entryId.tmdb_id, season.season_number); + let seasonData = await fetchSeasonData( + oldEntry.entryId.tmdb_id, + season.season_number, + ); // * find or create the season const [oldSeason, createdSeason] = await Season.findOrCreate({ @@ -731,7 +758,7 @@ async function SyncSerieData(entryId) { tmdb_rating: seasonData.vote_average, poster_path: seasonData.poster_path, banner_path: null, - } + }, }); // ? if the season already exist then just update it with new data @@ -769,7 +796,7 @@ async function SyncSerieData(entryId) { air_date: episode.air_date, tmdb_rating: episode.vote_average, still_path: episode.still_path, - } + }, }); // ? if the episode already exist then just update it with new data @@ -802,4 +829,4 @@ module.exports = { refrechEntry, SyncSeriesData, SyncSerieData, -} \ No newline at end of file +}; diff --git a/backend/services/models-services/seasonService.js b/backend/services/models-services/seasonService.js index f2fd8aa..f41b61d 100644 --- a/backend/services/models-services/seasonService.js +++ b/backend/services/models-services/seasonService.js @@ -1,43 +1,29 @@ -const Entry = require('../../models/Entry.js') -const EntryId = require('../../models/EntryId.js') -const EntryRating = require('../../models/EntryRating.js'); -const Season = require('../../models/Season.js'); -const EntryGenre = require('../../models/EntryGenre.js'); -const EntrySeen = require('../../models/EntrySeen.js'); +const Entry = require("../../models/Entry.js"); +const EntryId = require("../../models/EntryId.js"); +const EntryRating = require("../../models/EntryRating.js"); +const Season = require("../../models/Season.js"); +const EntryGenre = require("../../models/EntryGenre.js"); +const EntrySeen = require("../../models/EntrySeen.js"); async function saveSeason(entryId) { // fetch data from tmdb - // save season to db - } - async function updateSeason(seasonId) { // fetch season form db - // fetch data from tmdb - // update fields - // save - } +async function getSeason() {} -async function getSeason() { - -} - - -async function deleteSeason() { - -} - +async function deleteSeason() {} module.exports = { saveSeason, updateSeason, getSeason, deleteSeason, -} \ No newline at end of file +}; diff --git a/backend/services/mutlerStorageLocations.js b/backend/services/mutlerStorageLocations.js index 431bb45..c74f7b5 100644 --- a/backend/services/mutlerStorageLocations.js +++ b/backend/services/mutlerStorageLocations.js @@ -1,67 +1,64 @@ -const multer = require('multer'); -const { v4: uuidv4 } = require('uuid'); -const path = require('path'); -const configService = require('./configService'); +const multer = require("multer"); +const { v4: uuidv4 } = require("uuid"); +const path = require("path"); +const configService = require("./configService"); // ? users const entryPicturesUpload = multer({ - storage: - multer.diskStorage({ - destination: function (req, file, cb) { - let folder = 'posters'; - if (file.fieldname == 'backdrop') folder = 'backdrops'; - if (file.fieldname == 'logo') folder = 'logos'; + storage: multer.diskStorage({ + destination: function (req, file, cb) { + let folder = "posters"; + if (file.fieldname == "backdrop") folder = "backdrops"; + if (file.fieldname == "logo") folder = "logos"; - const dataPath = configService.getSettings().userDataPath; + const dataPath = configService.getSettings().userDataPath; - cb(null, path.join(dataPath, 'images', 'entries', folder)); - }, - filename: function (req, file, cb) { - const uniqueFilename = uuidv4(); - const extension = file.originalname.split('.').pop(); - cb(null, `${uniqueFilename}.${extension}`); - } - }) + cb(null, path.join(dataPath, "images", "entries", folder)); + }, + filename: function (req, file, cb) { + const uniqueFilename = uuidv4(); + const extension = file.originalname.split(".").pop(); + cb(null, `${uniqueFilename}.${extension}`); + }, + }), }); const collectionPicturesUpload = multer({ - storage: - multer.diskStorage({ - destination: function (req, file, cb) { - let folder = 'posters'; - if (file.fieldname == 'backdrop') folder = 'backdrops'; - if (file.fieldname == 'logo') folder = 'logos'; + storage: multer.diskStorage({ + destination: function (req, file, cb) { + let folder = "posters"; + if (file.fieldname == "backdrop") folder = "backdrops"; + if (file.fieldname == "logo") folder = "logos"; - const dataPath = configService.getSettings().userDataPath; + const dataPath = configService.getSettings().userDataPath; - cb(null, path.join(dataPath, 'images', 'collections', folder)); - }, - filename: function (req, file, cb) { - const uniqueFilename = uuidv4(); - const extension = file.originalname.split('.').pop(); - cb(null, `${uniqueFilename}.${extension}`); - } - }) + cb(null, path.join(dataPath, "images", "collections", folder)); + }, + filename: function (req, file, cb) { + const uniqueFilename = uuidv4(); + const extension = file.originalname.split(".").pop(); + cb(null, `${uniqueFilename}.${extension}`); + }, + }), }); const peoplePicturesUpload = multer({ - storage: - multer.diskStorage({ - destination: function (req, file, cb) { - let folder = 'profiles'; - const dataPath = configService.getSettings().userDataPath; - cb(null, path.join(dataPath, 'images', 'people', folder)); - }, - filename: function (req, file, cb) { - const uniqueFilename = uuidv4(); - const extension = file.originalname.split('.').pop(); - cb(null, `${uniqueFilename}.${extension}`); - } - }) + storage: multer.diskStorage({ + destination: function (req, file, cb) { + let folder = "profiles"; + const dataPath = configService.getSettings().userDataPath; + cb(null, path.join(dataPath, "images", "people", folder)); + }, + filename: function (req, file, cb) { + const uniqueFilename = uuidv4(); + const extension = file.originalname.split(".").pop(); + cb(null, `${uniqueFilename}.${extension}`); + }, + }), }); module.exports = { entryPicturesUpload, collectionPicturesUpload, peoplePicturesUpload, -} \ No newline at end of file +}; diff --git a/backend/services/networkService.js b/backend/services/networkService.js index 665914d..31a4165 100644 --- a/backend/services/networkService.js +++ b/backend/services/networkService.js @@ -8,7 +8,6 @@ const Network = require("../models/Network"); const Season = require("../models/Season"); class NetworkService { - constructor() { if (!NetworkService.instance) { NetworkService.instance = this; @@ -20,11 +19,12 @@ class NetworkService { const networks = await Network.findAll({ include: [ { - model: Entry, as: 'entries', - include: { model: Media, as: 'medias' } - } + model: Entry, + as: "entries", + include: { model: Media, as: "medias" }, + }, ], - order: [['name', 'ASC']] + order: [["name", "ASC"]], }); return networks; @@ -32,17 +32,19 @@ class NetworkService { async getNetworkById(id) { const network = await Network.findByPk(id, { - include: [{ - model: Entry, - as: 'entries', - include: [ - { model: EntryId, as: 'entryId' }, - { model: EntryRating, as: 'entryRating' }, - { model: Season, as: 'seasons' }, - { model: Media, as: 'medias' }, - { model: Genre, as: 'genres' }, - ] - }] + include: [ + { + model: Entry, + as: "entries", + include: [ + { model: EntryId, as: "entryId" }, + { model: EntryRating, as: "entryRating" }, + { model: Season, as: "seasons" }, + { model: Media, as: "medias" }, + { model: Genre, as: "genres" }, + ], + }, + ], }); return network; @@ -61,10 +63,9 @@ class NetworkService { logoPath: networkData.logoPath, posterPath: networkData.posterPath, backdropPath: networkData.backdropPath, - } + }, }); } - } -module.exports = new NetworkService(); \ No newline at end of file +module.exports = new NetworkService(); diff --git a/backend/services/peopleManager.js b/backend/services/peopleManager.js index 58b15eb..6d8faee 100644 --- a/backend/services/peopleManager.js +++ b/backend/services/peopleManager.js @@ -15,7 +15,6 @@ const _mediaDownloaderService = mediaDownloaderService; const _mediaOptimizerService = mediaOptimizerService; class PeopleManager { - constructor() { if (!PeopleManager.instance) { PeopleManager.instance = this; @@ -36,7 +35,9 @@ class PeopleManager { // * 3 - fetch person data from TMDB const personData = await fetchPersonDetails(person.tmdb_id); if (!personData) { - throw new InternalServerError(`Couldn't fetch data from TMDB for person with ID: ${id}`); + throw new InternalServerError( + `Couldn't fetch data from TMDB for person with ID: ${id}`, + ); } // * 4 - update person with fetched data @@ -50,25 +51,29 @@ class PeopleManager { // * 5 - download person media // TODO: peopleManage: update the person media each year if (!person.medias || person.medias.length === 0) { - const downloadedImages = await _mediaDownloaderService.downloadPersonMedia(person); + const downloadedImages = + await _mediaDownloaderService.downloadPersonMedia(person); for (const image of downloadedImages) { - // ? generating preview - _mediaOptimizerService.doGeneratePreview('peoples', image.type + 's', image.path).then((result) => { - const msg = `People Service | Generated Person Preview`; - logToFile(msg); - }).catch((err) => { - const msg = `People Service | Error Generating Person Preview`; - logToFile(msg); - logToFile(err); - }); + // ? generating preview + _mediaOptimizerService + .doGeneratePreview("peoples", image.type + "s", image.path) + .then((result) => { + const msg = `People Service | Generated Person Preview`; + logToFile(msg); + }) + .catch((err) => { + const msg = `People Service | Error Generating Person Preview`; + logToFile(msg); + logToFile(err); + }); // ? inserting data await Media.create({ - mediaable: 'people', + mediaable: "people", mediaableId: person.id, type: image.type, path: image.path, isLocal: true, - isSelected: true + isSelected: true, }); } } @@ -76,7 +81,6 @@ class PeopleManager { // * 6 - return the person return await _peopleService.getPersonById(id); } - } -module.exports = new PeopleManager(); \ No newline at end of file +module.exports = new PeopleManager(); diff --git a/backend/services/peopleService.js b/backend/services/peopleService.js index 14adca2..79731c8 100644 --- a/backend/services/peopleService.js +++ b/backend/services/peopleService.js @@ -22,8 +22,8 @@ class PeopleService { async getAllPeople(includeCrew = false, { page, limit, search } = {}) { let where = { where: { - cast_type: 'cast' - } + cast_type: "cast", + }, }; if (includeCrew) { @@ -45,11 +45,11 @@ class PeopleService { include: { model: Entry, as: "entry", - include: { model: Media, as: "medias" } + include: { model: Media, as: "medias" }, }, - ...where + ...where, }, - { model: Media, as: 'medias' } + { model: Media, as: "medias" }, ], }; @@ -83,11 +83,11 @@ class PeopleService { include: { model: Entry, as: "entry", - include: { model: Media, as: "medias" } + include: { model: Media, as: "medias" }, }, }, - { model: Media, as: 'medias' } - ] + { model: Media, as: "medias" }, + ], }); if (!person) { @@ -107,11 +107,11 @@ class PeopleService { include: { model: Entry, as: "entry", - include: { model: Media, as: "medias" } - } + include: { model: Media, as: "medias" }, + }, }, - { model: Media, as: 'medias' } - ] + { model: Media, as: "medias" }, + ], }); return person; @@ -120,13 +120,11 @@ class PeopleService { async searchPeople(query) { const people = await People.findAll({ where: { - name: { [Op.like]: `%${query}%` } + name: { [Op.like]: `%${query}%` }, }, order: [["popularity", "DESC"]], limit: 20, - include: [ - { model: Media, as: 'medias' } - ] + include: [{ model: Media, as: "medias" }], }); return people; } @@ -134,7 +132,7 @@ class PeopleService { async createPerson(personData) { try { const existingPerson = await People.findOne({ - where: { tmdb_id: personData.tmdb_id } + where: { tmdb_id: personData.tmdb_id }, }); if (existingPerson) { @@ -165,14 +163,16 @@ class PeopleService { }, include: [ { - model: Credit, as: 'roles', + model: Credit, + as: "roles", include: { - model: Entry, as: 'entry', - include: [{ model: Media, as: 'medias' }] - } + model: Entry, + as: "entry", + include: [{ model: Media, as: "medias" }], + }, }, - { model: Media, as: 'medias' } - ] + { model: Media, as: "medias" }, + ], }); } @@ -235,7 +235,9 @@ class PeopleService { // Fetch person data from TMDB const personData = await fetchPersonData(tmdbId); if (!personData) { - throw new NotFoundError(`Person with TMDB ID ${tmdbId} not found in TMDB`); + throw new NotFoundError( + `Person with TMDB ID ${tmdbId} not found in TMDB`, + ); } // Create new person in database diff --git a/backend/services/storageService.js b/backend/services/storageService.js index 6563603..01fcf19 100644 --- a/backend/services/storageService.js +++ b/backend/services/storageService.js @@ -1,5 +1,5 @@ -const path = require('path'); -const fs = require('fs'); +const path = require("path"); +const fs = require("fs"); const configService = require("./configService"); const tmdbService = require("./tmdbService"); @@ -14,7 +14,6 @@ const _mediaOptimizerService = mediaOptimizerService; const _mediaDownloaderService = mediaDownloaderService; class StorageService { - constructor() { if (!StorageService.instance) { StorageService.instance = this; @@ -27,11 +26,10 @@ class StorageService { file.data.pipe(writer); return new Promise((resolve, reject) => { - writer.on('finish', resolve); - writer.on('error', reject); + writer.on("finish", resolve); + writer.on("error", reject); }); } - } module.exports = new StorageService(); diff --git a/backend/services/tmdbService.js b/backend/services/tmdbService.js index cc33b24..cc681a1 100644 --- a/backend/services/tmdbService.js +++ b/backend/services/tmdbService.js @@ -1,6 +1,6 @@ -const axios = require('axios'); -const { logToFile } = require('./logService'); -const configService = require('./configService'); +const axios = require("axios"); +const { logToFile } = require("./logService"); +const configService = require("./configService"); const TMDB_APIURL = configService.getTmdbApiUrl(); const TMDB_APIKEY = configService.getTmdbApiKey(); @@ -8,44 +8,41 @@ const TMDB_APIKEY = configService.getTmdbApiKey(); async function fetchEntryData(tmdb_id, is_tvserie) { try { let type = is_tvserie ? "tv" : "movie"; - let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US` - logToFile(`Fetching Entry Data From: ${url}`) + let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`; + logToFile(`Fetching Entry Data From: ${url}`); let data; - await axios.get(url) - .then((response) => { - if (response.status != 200) { - logToFile(`Error Fetching Data From: ${url}`) - return console.log('Error fetching the data.') - }; - data = response.data; - }) + await axios.get(url).then((response) => { + if (response.status != 200) { + logToFile(`Error Fetching Data From: ${url}`); + return console.log("Error fetching the data."); + } + data = response.data; + }); return data; } catch (error) { - console.log('Error fetching the entry data.', error) + console.log("Error fetching the entry data.", error); return null; } } - async function fetchSeasonData(tmdbTvId, seasonNumber) { // fetching the informations try { - let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US` - logToFile(`Fetching Season Data From: ${url}`) + let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`; + logToFile(`Fetching Season Data From: ${url}`); let data; - await axios.get(url) - .then((response) => { - if (response.status != 200) { - logToFile(`Error Fetching Data From: ${url}`) - return console.log('Error fetching the data.') - }; - data = response.data; - }) + await axios.get(url).then((response) => { + if (response.status != 200) { + logToFile(`Error Fetching Data From: ${url}`); + return console.log("Error fetching the data."); + } + data = response.data; + }); return data; } catch (error) { - console.log('Error fetching the data.') + console.log("Error fetching the data."); return null; } } @@ -53,42 +50,44 @@ async function fetchSeasonData(tmdbTvId, seasonNumber) { async function fetchEntryMedia(tmdb_id, is_tvserie) { try { let type = is_tvserie ? "tv" : "movie"; - let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}` - logToFile(`Fetching Entry Media Data From: ${url}`) + let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`; + logToFile(`Fetching Entry Media Data From: ${url}`); let data; - await axios.get(url) - .then((response) => { - if (response.status != 200) { - logToFile(`Error Fetching Data From: ${url}`) - return console.log('Error fetching the data.') - }; - data = response.data; - }) + await axios.get(url).then((response) => { + if (response.status != 200) { + logToFile(`Error Fetching Data From: ${url}`); + return console.log("Error fetching the data."); + } + data = response.data; + }); return data; } catch (error) { - console.log('Error fetching the entry media.', error) + console.log("Error fetching the entry media.", error); return null; } } async function fetchCollectionData(collectionId) { try { - let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US` - logToFile(`Fetching Collection Data From: ${url}`) + let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`; + logToFile(`Fetching Collection Data From: ${url}`); let data; - await axios.get(url) - .then((response) => { - if (response.status != 200) return console.log('Error fetching collection data from tmdb:', response); - data = response.data; - }) + await axios.get(url).then((response) => { + if (response.status != 200) + return console.log( + "Error fetching collection data from tmdb:", + response, + ); + data = response.data; + }); return data; } catch (error) { if (response.status != 200) { - logToFile(`Error Fetching Data From: ${url}`) - return console.log('Error fetching the data.') - }; + logToFile(`Error Fetching Data From: ${url}`); + return console.log("Error fetching the data."); + } return null; } } @@ -105,24 +104,23 @@ async function fetchEntryCredits(tmdb_id, is_tvserie) { let url = `${TMDB_APIURL}${type}/${tmdb_id}/credits?api_key=${TMDB_APIKEY}&language=en-US`; if (is_tvserie) { - url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US` + url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`; } logToFile(`Fetching Entry Credits From: ${url}`); let data; - await axios.get(url) - .then((response) => { - if (response.status != 200) { - logToFile(`Error Fetching Credits From: ${url}`); - return console.log('Error fetching the credits data.'); - }; - data = response.data; - }); + await axios.get(url).then((response) => { + if (response.status != 200) { + logToFile(`Error Fetching Credits From: ${url}`); + return console.log("Error fetching the credits data."); + } + data = response.data; + }); return data; } catch (error) { - console.log('Error fetching the entry credits.', error); + console.log("Error fetching the entry credits.", error); return null; } } @@ -138,18 +136,17 @@ async function fetchPersonDetails(tmdb_id) { logToFile(`Fetching Person Details From: ${url}`); let data; - await axios.get(url) - .then((response) => { - if (response.status != 200) { - logToFile(`Error Fetching Person Details From: ${url}`); - return console.log('Error fetching the person data.'); - }; - data = response.data; - }); + await axios.get(url).then((response) => { + if (response.status != 200) { + logToFile(`Error Fetching Person Details From: ${url}`); + return console.log("Error fetching the person data."); + } + data = response.data; + }); return data; } catch (error) { - console.log('Error fetching the person details.', error); + console.log("Error fetching the person details.", error); return null; } } @@ -197,7 +194,7 @@ async function fetchUpcoming(page = 1) { const response = await axios.get(url); return response.data; } catch (error) { - console.log('Error fetching upcoming movies.', error); + console.log("Error fetching upcoming movies.", error); return null; } } @@ -209,7 +206,7 @@ async function searchMulti(query, page = 1) { const response = await axios.get(url); return response.data; } catch (error) { - console.log('Error searching TMDB.', error); + console.log("Error searching TMDB.", error); return null; } } @@ -221,7 +218,7 @@ async function searchPeople(query, page = 1) { const response = await axios.get(url); return response.data; } catch (error) { - console.log('Error searching TMDB people.', error); + console.log("Error searching TMDB people.", error); return null; } } @@ -233,7 +230,7 @@ async function fetchPopularPeople(page = 1) { const response = await axios.get(url); return response.data; } catch (error) { - console.log('Error fetching popular people.', error); + console.log("Error fetching popular people.", error); return null; } } @@ -245,7 +242,7 @@ async function fetchPersonCombinedCredits(tmdb_id) { const response = await axios.get(url); return response.data; } catch (error) { - console.log('Error fetching person combined credits.', error); + console.log("Error fetching person combined credits.", error); return null; } } @@ -265,7 +262,4 @@ module.exports = { searchMulti, searchPeople, fetchPopularPeople, -} - - - +}; diff --git a/backend/utils/moment.js b/backend/utils/moment.js index e689f28..559a6ef 100644 --- a/backend/utils/moment.js +++ b/backend/utils/moment.js @@ -4,2571 +4,2557 @@ //! license : MIT //! momentjs.com -;(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - global.moment = factory() -}(this, (function () { 'use strict'; +(function (global, factory) { + typeof exports === "object" && typeof module !== "undefined" + ? (module.exports = factory()) + : typeof define === "function" && define.amd + ? define(factory) + : (global.moment = factory()); +})(this, function () { + "use strict"; var hookCallback; function hooks() { - return hookCallback.apply(null, arguments); + return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback(callback) { - hookCallback = callback; + hookCallback = callback; } function isArray(input) { - return ( - input instanceof Array || - Object.prototype.toString.call(input) === '[object Array]' - ); + return ( + input instanceof Array || + Object.prototype.toString.call(input) === "[object Array]" + ); } function isObject(input) { - // IE8 will treat undefined and null as object if it wasn't for - // input != null - return ( - input != null && - Object.prototype.toString.call(input) === '[object Object]' - ); + // IE8 will treat undefined and null as object if it wasn't for + // input != null + return ( + input != null && + Object.prototype.toString.call(input) === "[object Object]" + ); } function hasOwnProp(a, b) { - return Object.prototype.hasOwnProperty.call(a, b); + return Object.prototype.hasOwnProperty.call(a, b); } function isObjectEmpty(obj) { - if (Object.getOwnPropertyNames) { - return Object.getOwnPropertyNames(obj).length === 0; - } else { - var k; - for (k in obj) { - if (hasOwnProp(obj, k)) { - return false; - } - } - return true; + if (Object.getOwnPropertyNames) { + return Object.getOwnPropertyNames(obj).length === 0; + } else { + var k; + for (k in obj) { + if (hasOwnProp(obj, k)) { + return false; + } } + return true; + } } function isUndefined(input) { - return input === void 0; + return input === void 0; } function isNumber(input) { - return ( - typeof input === 'number' || - Object.prototype.toString.call(input) === '[object Number]' - ); + return ( + typeof input === "number" || + Object.prototype.toString.call(input) === "[object Number]" + ); } function isDate(input) { - return ( - input instanceof Date || - Object.prototype.toString.call(input) === '[object Date]' - ); + return ( + input instanceof Date || + Object.prototype.toString.call(input) === "[object Date]" + ); } function map(arr, fn) { - var res = [], - i; - for (i = 0; i < arr.length; ++i) { - res.push(fn(arr[i], i)); - } - return res; + var res = [], + i; + for (i = 0; i < arr.length; ++i) { + res.push(fn(arr[i], i)); + } + return res; } function extend(a, b) { - for (var i in b) { - if (hasOwnProp(b, i)) { - a[i] = b[i]; - } + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; } + } - if (hasOwnProp(b, 'toString')) { - a.toString = b.toString; - } + if (hasOwnProp(b, "toString")) { + a.toString = b.toString; + } - if (hasOwnProp(b, 'valueOf')) { - a.valueOf = b.valueOf; - } + if (hasOwnProp(b, "valueOf")) { + a.valueOf = b.valueOf; + } - return a; + return a; } function createUTC(input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, true).utc(); + return createLocalOrUTC(input, format, locale, strict, true).utc(); } function defaultParsingFlags() { - // We need to deep clone this object. - return { - empty: false, - unusedTokens: [], - unusedInput: [], - overflow: -2, - charsLeftOver: 0, - nullInput: false, - invalidEra: null, - invalidMonth: null, - invalidFormat: false, - userInvalidated: false, - iso: false, - parsedDateParts: [], - era: null, - meridiem: null, - rfc2822: false, - weekdayMismatch: false, - }; + // We need to deep clone this object. + return { + empty: false, + unusedTokens: [], + unusedInput: [], + overflow: -2, + charsLeftOver: 0, + nullInput: false, + invalidEra: null, + invalidMonth: null, + invalidFormat: false, + userInvalidated: false, + iso: false, + parsedDateParts: [], + era: null, + meridiem: null, + rfc2822: false, + weekdayMismatch: false, + }; } function getParsingFlags(m) { - if (m._pf == null) { - m._pf = defaultParsingFlags(); - } - return m._pf; + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; } var some; if (Array.prototype.some) { - some = Array.prototype.some; + some = Array.prototype.some; } else { - some = function (fun) { - var t = Object(this), - len = t.length >>> 0, - i; + some = function (fun) { + var t = Object(this), + len = t.length >>> 0, + i; - for (i = 0; i < len; i++) { - if (i in t && fun.call(this, t[i], i, t)) { - return true; - } - } + for (i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } - return false; - }; + return false; + }; } function isValid(m) { - if (m._isValid == null) { - var flags = getParsingFlags(m), - parsedParts = some.call(flags.parsedDateParts, function (i) { - return i != null; - }), - isNowValid = - !isNaN(m._d.getTime()) && - flags.overflow < 0 && - !flags.empty && - !flags.invalidEra && - !flags.invalidMonth && - !flags.invalidWeekday && - !flags.weekdayMismatch && - !flags.nullInput && - !flags.invalidFormat && - !flags.userInvalidated && - (!flags.meridiem || (flags.meridiem && parsedParts)); + if (m._isValid == null) { + var flags = getParsingFlags(m), + parsedParts = some.call(flags.parsedDateParts, function (i) { + return i != null; + }), + isNowValid = + !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidEra && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.weekdayMismatch && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); - if (m._strict) { - isNowValid = - isNowValid && - flags.charsLeftOver === 0 && - flags.unusedTokens.length === 0 && - flags.bigHour === undefined; - } - - if (Object.isFrozen == null || !Object.isFrozen(m)) { - m._isValid = isNowValid; - } else { - return isNowValid; - } + if (m._strict) { + isNowValid = + isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; } - return m._isValid; + + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } else { + return isNowValid; + } + } + return m._isValid; } function createInvalid(flags) { - var m = createUTC(NaN); - if (flags != null) { - extend(getParsingFlags(m), flags); - } else { - getParsingFlags(m).userInvalidated = true; - } + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } else { + getParsingFlags(m).userInvalidated = true; + } - return m; + return m; } // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. var momentProperties = (hooks.momentProperties = []), - updateInProgress = false; + updateInProgress = false; function copyConfig(to, from) { - var i, prop, val; + var i, prop, val; - if (!isUndefined(from._isAMomentObject)) { - to._isAMomentObject = from._isAMomentObject; - } - if (!isUndefined(from._i)) { - to._i = from._i; - } - if (!isUndefined(from._f)) { - to._f = from._f; - } - if (!isUndefined(from._l)) { - to._l = from._l; - } - if (!isUndefined(from._strict)) { - to._strict = from._strict; - } - if (!isUndefined(from._tzm)) { - to._tzm = from._tzm; - } - if (!isUndefined(from._isUTC)) { - to._isUTC = from._isUTC; - } - if (!isUndefined(from._offset)) { - to._offset = from._offset; - } - if (!isUndefined(from._pf)) { - to._pf = getParsingFlags(from); - } - if (!isUndefined(from._locale)) { - to._locale = from._locale; - } + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; + } - if (momentProperties.length > 0) { - for (i = 0; i < momentProperties.length; i++) { - prop = momentProperties[i]; - val = from[prop]; - if (!isUndefined(val)) { - to[prop] = val; - } - } + if (momentProperties.length > 0) { + for (i = 0; i < momentProperties.length; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } } + } - return to; + return to; } // Moment prototype object function Moment(config) { - copyConfig(this, config); - this._d = new Date(config._d != null ? config._d.getTime() : NaN); - if (!this.isValid()) { - this._d = new Date(NaN); - } - // Prevent infinite loop in case updateOffset creates new moment - // objects. - if (updateInProgress === false) { - updateInProgress = true; - hooks.updateOffset(this); - updateInProgress = false; - } + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } } function isMoment(obj) { - return ( - obj instanceof Moment || (obj != null && obj._isAMomentObject != null) - ); + return ( + obj instanceof Moment || (obj != null && obj._isAMomentObject != null) + ); } function warn(msg) { - if ( - hooks.suppressDeprecationWarnings === false && - typeof console !== 'undefined' && - console.warn - ) { - console.warn('Deprecation warning: ' + msg); - } + if ( + hooks.suppressDeprecationWarnings === false && + typeof console !== "undefined" && + console.warn + ) { + console.warn("Deprecation warning: " + msg); + } } function deprecate(msg, fn) { - var firstTime = true; + var firstTime = true; - return extend(function () { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(null, msg); - } - if (firstTime) { - var args = [], - arg, - i, - key; - for (i = 0; i < arguments.length; i++) { - arg = ''; - if (typeof arguments[i] === 'object') { - arg += '\n[' + i + '] '; - for (key in arguments[0]) { - if (hasOwnProp(arguments[0], key)) { - arg += key + ': ' + arguments[0][key] + ', '; - } - } - arg = arg.slice(0, -2); // Remove trailing comma and space - } else { - arg = arguments[i]; - } - args.push(arg); + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = [], + arg, + i, + key; + for (i = 0; i < arguments.length; i++) { + arg = ""; + if (typeof arguments[i] === "object") { + arg += "\n[" + i + "] "; + for (key in arguments[0]) { + if (hasOwnProp(arguments[0], key)) { + arg += key + ": " + arguments[0][key] + ", "; } - warn( - msg + - '\nArguments: ' + - Array.prototype.slice.call(args).join('') + - '\n' + - new Error().stack - ); - firstTime = false; + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; } - return fn.apply(this, arguments); - }, fn); + args.push(arg); + } + warn( + msg + + "\nArguments: " + + Array.prototype.slice.call(args).join("") + + "\n" + + new Error().stack, + ); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { - if (hooks.deprecationHandler != null) { - hooks.deprecationHandler(name, msg); - } - if (!deprecations[name]) { - warn(msg); - deprecations[name] = true; - } + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } } hooks.suppressDeprecationWarnings = false; hooks.deprecationHandler = null; function isFunction(input) { - return ( - (typeof Function !== 'undefined' && input instanceof Function) || - Object.prototype.toString.call(input) === '[object Function]' - ); + return ( + (typeof Function !== "undefined" && input instanceof Function) || + Object.prototype.toString.call(input) === "[object Function]" + ); } function set(config) { - var prop, i; - for (i in config) { - if (hasOwnProp(config, i)) { - prop = config[i]; - if (isFunction(prop)) { - this[i] = prop; - } else { - this['_' + i] = prop; - } - } + var prop, i; + for (i in config) { + if (hasOwnProp(config, i)) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this["_" + i] = prop; + } } - this._config = config; - // Lenient ordinal parsing accepts just a number in addition to - // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. - // TODO: Remove "ordinalParse" fallback in next major release. - this._dayOfMonthOrdinalParseLenient = new RegExp( - (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + - '|' + - /\d{1,2}/.source - ); + } + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + "|" + + /\d{1,2}/.source, + ); } function mergeConfigs(parentConfig, childConfig) { - var res = extend({}, parentConfig), - prop; - for (prop in childConfig) { - if (hasOwnProp(childConfig, prop)) { - if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { - res[prop] = {}; - extend(res[prop], parentConfig[prop]); - extend(res[prop], childConfig[prop]); - } else if (childConfig[prop] != null) { - res[prop] = childConfig[prop]; - } else { - delete res[prop]; - } - } + var res = extend({}, parentConfig), + prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } } - for (prop in parentConfig) { - if ( - hasOwnProp(parentConfig, prop) && - !hasOwnProp(childConfig, prop) && - isObject(parentConfig[prop]) - ) { - // make sure changes to properties don't modify parent config - res[prop] = extend({}, res[prop]); - } + } + for (prop in parentConfig) { + if ( + hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop]) + ) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); } - return res; + } + return res; } function Locale(config) { - if (config != null) { - this.set(config); - } + if (config != null) { + this.set(config); + } } var keys; if (Object.keys) { - keys = Object.keys; + keys = Object.keys; } else { - keys = function (obj) { - var i, - res = []; - for (i in obj) { - if (hasOwnProp(obj, i)) { - res.push(i); - } - } - return res; - }; + keys = function (obj) { + var i, + res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; } var defaultCalendar = { - sameDay: '[Today at] LT', - nextDay: '[Tomorrow at] LT', - nextWeek: 'dddd [at] LT', - lastDay: '[Yesterday at] LT', - lastWeek: '[Last] dddd [at] LT', - sameElse: 'L', + sameDay: "[Today at] LT", + nextDay: "[Tomorrow at] LT", + nextWeek: "dddd [at] LT", + lastDay: "[Yesterday at] LT", + lastWeek: "[Last] dddd [at] LT", + sameElse: "L", }; function calendar(key, mom, now) { - var output = this._calendar[key] || this._calendar['sameElse']; - return isFunction(output) ? output.call(mom, now) : output; + var output = this._calendar[key] || this._calendar["sameElse"]; + return isFunction(output) ? output.call(mom, now) : output; } function zeroFill(number, targetLength, forceSign) { - var absNumber = '' + Math.abs(number), - zerosToFill = targetLength - absNumber.length, - sign = number >= 0; - return ( - (sign ? (forceSign ? '+' : '') : '-') + - Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + - absNumber - ); + var absNumber = "" + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return ( + (sign ? (forceSign ? "+" : "") : "-") + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + + absNumber + ); } - var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, - localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, - formatFunctions = {}, - formatTokenFunctions = {}; + var formattingTokens = + /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, + localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, + formatFunctions = {}, + formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken(token, padded, ordinal, callback) { - var func = callback; - if (typeof callback === 'string') { - func = function () { - return this[callback](); - }; - } - if (token) { - formatTokenFunctions[token] = func; - } - if (padded) { - formatTokenFunctions[padded[0]] = function () { - return zeroFill(func.apply(this, arguments), padded[1], padded[2]); - }; - } - if (ordinal) { - formatTokenFunctions[ordinal] = function () { - return this.localeData().ordinal( - func.apply(this, arguments), - token - ); - }; - } + var func = callback; + if (typeof callback === "string") { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal(func.apply(this, arguments), token); + }; + } } function removeFormattingTokens(input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|\]$/g, ''); - } - return input.replace(/\\/g, ''); + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ""); + } + return input.replace(/\\/g, ""); } function makeFormatFunction(format) { - var array = format.match(formattingTokens), - i, - length; + var array = format.match(formattingTokens), + i, + length; - for (i = 0, length = array.length; i < length; i++) { - if (formatTokenFunctions[array[i]]) { - array[i] = formatTokenFunctions[array[i]]; - } else { - array[i] = removeFormattingTokens(array[i]); - } + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); } + } - return function (mom) { - var output = '', - i; - for (i = 0; i < length; i++) { - output += isFunction(array[i]) - ? array[i].call(mom, format) - : array[i]; - } - return output; - }; + return function (mom) { + var output = "", + i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; + } + return output; + }; } // format date using native date object function formatMoment(m, format) { - if (!m.isValid()) { - return m.localeData().invalidDate(); - } + if (!m.isValid()) { + return m.localeData().invalidDate(); + } - format = expandFormat(format, m.localeData()); - formatFunctions[format] = - formatFunctions[format] || makeFormatFunction(format); + format = expandFormat(format, m.localeData()); + formatFunctions[format] = + formatFunctions[format] || makeFormatFunction(format); - return formatFunctions[format](m); + return formatFunctions[format](m); } function expandFormat(format, locale) { - var i = 5; + var i = 5; - function replaceLongDateFormatTokens(input) { - return locale.longDateFormat(input) || input; - } + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace( + localFormattingTokens, + replaceLongDateFormatTokens, + ); localFormattingTokens.lastIndex = 0; - while (i >= 0 && localFormattingTokens.test(format)) { - format = format.replace( - localFormattingTokens, - replaceLongDateFormatTokens - ); - localFormattingTokens.lastIndex = 0; - i -= 1; - } + i -= 1; + } - return format; + return format; } var defaultLongDateFormat = { - LTS: 'h:mm:ss A', - LT: 'h:mm A', - L: 'MM/DD/YYYY', - LL: 'MMMM D, YYYY', - LLL: 'MMMM D, YYYY h:mm A', - LLLL: 'dddd, MMMM D, YYYY h:mm A', + LTS: "h:mm:ss A", + LT: "h:mm A", + L: "MM/DD/YYYY", + LL: "MMMM D, YYYY", + LLL: "MMMM D, YYYY h:mm A", + LLLL: "dddd, MMMM D, YYYY h:mm A", }; function longDateFormat(key) { - var format = this._longDateFormat[key], - formatUpper = this._longDateFormat[key.toUpperCase()]; + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; - if (format || !formatUpper) { - return format; - } + if (format || !formatUpper) { + return format; + } - this._longDateFormat[key] = formatUpper - .match(formattingTokens) - .map(function (tok) { - if ( - tok === 'MMMM' || - tok === 'MM' || - tok === 'DD' || - tok === 'dddd' - ) { - return tok.slice(1); - } - return tok; - }) - .join(''); + this._longDateFormat[key] = formatUpper + .match(formattingTokens) + .map(function (tok) { + if (tok === "MMMM" || tok === "MM" || tok === "DD" || tok === "dddd") { + return tok.slice(1); + } + return tok; + }) + .join(""); - return this._longDateFormat[key]; + return this._longDateFormat[key]; } - var defaultInvalidDate = 'Invalid date'; + var defaultInvalidDate = "Invalid date"; function invalidDate() { - return this._invalidDate; + return this._invalidDate; } - var defaultOrdinal = '%d', - defaultDayOfMonthOrdinalParse = /\d{1,2}/; + var defaultOrdinal = "%d", + defaultDayOfMonthOrdinalParse = /\d{1,2}/; function ordinal(number) { - return this._ordinal.replace('%d', number); + return this._ordinal.replace("%d", number); } var defaultRelativeTime = { - future: 'in %s', - past: '%s ago', - s: 'a few seconds', - ss: '%d seconds', - m: 'a minute', - mm: '%d minutes', - h: 'an hour', - hh: '%d hours', - d: 'a day', - dd: '%d days', - w: 'a week', - ww: '%d weeks', - M: 'a month', - MM: '%d months', - y: 'a year', - yy: '%d years', + future: "in %s", + past: "%s ago", + s: "a few seconds", + ss: "%d seconds", + m: "a minute", + mm: "%d minutes", + h: "an hour", + hh: "%d hours", + d: "a day", + dd: "%d days", + w: "a week", + ww: "%d weeks", + M: "a month", + MM: "%d months", + y: "a year", + yy: "%d years", }; function relativeTime(number, withoutSuffix, string, isFuture) { - var output = this._relativeTime[string]; - return isFunction(output) - ? output(number, withoutSuffix, string, isFuture) - : output.replace(/%d/i, number); + var output = this._relativeTime[string]; + return isFunction(output) + ? output(number, withoutSuffix, string, isFuture) + : output.replace(/%d/i, number); } function pastFuture(diff, output) { - var format = this._relativeTime[diff > 0 ? 'future' : 'past']; - return isFunction(format) ? format(output) : format.replace(/%s/i, output); + var format = this._relativeTime[diff > 0 ? "future" : "past"]; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); } var aliases = {}; function addUnitAlias(unit, shorthand) { - var lowerCase = unit.toLowerCase(); - aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + "s"] = aliases[shorthand] = unit; } function normalizeUnits(units) { - return typeof units === 'string' - ? aliases[units] || aliases[units.toLowerCase()] - : undefined; + return typeof units === "string" + ? aliases[units] || aliases[units.toLowerCase()] + : undefined; } function normalizeObjectUnits(inputObject) { - var normalizedInput = {}, - normalizedProp, - prop; + var normalizedInput = {}, + normalizedProp, + prop; - for (prop in inputObject) { - if (hasOwnProp(inputObject, prop)) { - normalizedProp = normalizeUnits(prop); - if (normalizedProp) { - normalizedInput[normalizedProp] = inputObject[prop]; - } - } + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } } + } - return normalizedInput; + return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { - priorities[unit] = priority; + priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { - var units = [], - u; - for (u in unitsObj) { - if (hasOwnProp(unitsObj, u)) { - units.push({ unit: u, priority: priorities[u] }); - } + var units = [], + u; + for (u in unitsObj) { + if (hasOwnProp(unitsObj, u)) { + units.push({ unit: u, priority: priorities[u] }); } - units.sort(function (a, b) { - return a.priority - b.priority; - }); - return units; + } + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; } function isLeapYear(year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function absFloor(number) { - if (number < 0) { - // -0 -> 0 - return Math.ceil(number) || 0; - } else { - return Math.floor(number); - } + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } } function toInt(argumentForCoercion) { - var coercedNumber = +argumentForCoercion, - value = 0; + var coercedNumber = +argumentForCoercion, + value = 0; - if (coercedNumber !== 0 && isFinite(coercedNumber)) { - value = absFloor(coercedNumber); - } + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } - return value; + return value; } function makeGetSet(unit, keepTime) { - return function (value) { - if (value != null) { - set$1(this, unit, value); - hooks.updateOffset(this, keepTime); - return this; - } else { - return get(this, unit); - } - }; + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; } function get(mom, unit) { - return mom.isValid() - ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() - : NaN; + return mom.isValid() + ? mom._d["get" + (mom._isUTC ? "UTC" : "") + unit]() + : NaN; } function set$1(mom, unit, value) { - if (mom.isValid() && !isNaN(value)) { - if ( - unit === 'FullYear' && - isLeapYear(mom.year()) && - mom.month() === 1 && - mom.date() === 29 - ) { - value = toInt(value); - mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit]( - value, - mom.month(), - daysInMonth(value, mom.month()) - ); - } else { - mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); - } + if (mom.isValid() && !isNaN(value)) { + if ( + unit === "FullYear" && + isLeapYear(mom.year()) && + mom.month() === 1 && + mom.date() === 29 + ) { + value = toInt(value); + mom._d["set" + (mom._isUTC ? "UTC" : "") + unit]( + value, + mom.month(), + daysInMonth(value, mom.month()), + ); + } else { + mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value); } + } } // MOMENTS function stringGet(units) { - units = normalizeUnits(units); - if (isFunction(this[units])) { - return this[units](); - } - return this; + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; } function stringSet(units, value) { - if (typeof units === 'object') { - units = normalizeObjectUnits(units); - var prioritized = getPrioritizedUnits(units), - i; - for (i = 0; i < prioritized.length; i++) { - this[prioritized[i].unit](units[prioritized[i].unit]); - } - } else { - units = normalizeUnits(units); - if (isFunction(this[units])) { - return this[units](value); - } + if (typeof units === "object") { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units), + i; + for (i = 0; i < prioritized.length; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); } - return this; + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; } var match1 = /\d/, // 0 - 9 - match2 = /\d\d/, // 00 - 99 - match3 = /\d{3}/, // 000 - 999 - match4 = /\d{4}/, // 0000 - 9999 - match6 = /[+-]?\d{6}/, // -999999 - 999999 - match1to2 = /\d\d?/, // 0 - 99 - match3to4 = /\d\d\d\d?/, // 999 - 9999 - match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999 - match1to3 = /\d{1,3}/, // 0 - 999 - match1to4 = /\d{1,4}/, // 0 - 9999 - match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999 - matchUnsigned = /\d+/, // 0 - inf - matchSigned = /[+-]?\d+/, // -inf - inf - matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z - matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z - matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 - // any word (or two) characters or numbers including two/three word month in arabic. - // includes scottish gaelic two word and hyphenated months - matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, - regexes; + match2 = /\d\d/, // 00 - 99 + match3 = /\d{3}/, // 000 - 999 + match4 = /\d{4}/, // 0000 - 9999 + match6 = /[+-]?\d{6}/, // -999999 - 999999 + match1to2 = /\d\d?/, // 0 - 99 + match3to4 = /\d\d\d\d?/, // 999 - 9999 + match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999 + match1to3 = /\d{1,3}/, // 0 - 999 + match1to4 = /\d{1,4}/, // 0 - 9999 + match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999 + matchUnsigned = /\d+/, // 0 - inf + matchSigned = /[+-]?\d+/, // -inf - inf + matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z + matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z + matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 + // any word (or two) characters or numbers including two/three word month in arabic. + // includes scottish gaelic two word and hyphenated months + matchWord = + /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, + regexes; regexes = {}; function addRegexToken(token, regex, strictRegex) { - regexes[token] = isFunction(regex) - ? regex - : function (isStrict, localeData) { - return isStrict && strictRegex ? strictRegex : regex; - }; + regexes[token] = isFunction(regex) + ? regex + : function (isStrict, localeData) { + return isStrict && strictRegex ? strictRegex : regex; + }; } function getParseRegexForToken(token, config) { - if (!hasOwnProp(regexes, token)) { - return new RegExp(unescapeFormat(token)); - } + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } - return regexes[token](config._strict, config._locale); + return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { - return regexEscape( - s - .replace('\\', '') - .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function ( - matched, - p1, - p2, - p3, - p4 - ) { - return p1 || p2 || p3 || p4; - }) - ); + return regexEscape( + s + .replace("\\", "") + .replace( + /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, + function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + }, + ), + ); } function regexEscape(s) { - return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); } var tokens = {}; function addParseToken(token, callback) { - var i, - func = callback; - if (typeof token === 'string') { - token = [token]; - } - if (isNumber(callback)) { - func = function (input, array) { - array[callback] = toInt(input); - }; - } - for (i = 0; i < token.length; i++) { - tokens[token[i]] = func; - } + var i, + func = callback; + if (typeof token === "string") { + token = [token]; + } + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + for (i = 0; i < token.length; i++) { + tokens[token[i]] = func; + } } function addWeekParseToken(token, callback) { - addParseToken(token, function (input, array, config, token) { - config._w = config._w || {}; - callback(input, config._w, config, token); - }); + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); } function addTimeToArrayFromToken(token, input, config) { - if (input != null && hasOwnProp(tokens, token)) { - tokens[token](input, config._a, config, token); - } + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } } var YEAR = 0, - MONTH = 1, - DATE = 2, - HOUR = 3, - MINUTE = 4, - SECOND = 5, - MILLISECOND = 6, - WEEK = 7, - WEEKDAY = 8; + MONTH = 1, + DATE = 2, + HOUR = 3, + MINUTE = 4, + SECOND = 5, + MILLISECOND = 6, + WEEK = 7, + WEEKDAY = 8; function mod(n, x) { - return ((n % x) + x) % x; + return ((n % x) + x) % x; } var indexOf; if (Array.prototype.indexOf) { - indexOf = Array.prototype.indexOf; + indexOf = Array.prototype.indexOf; } else { - indexOf = function (o) { - // I know - var i; - for (i = 0; i < this.length; ++i) { - if (this[i] === o) { - return i; - } - } - return -1; - }; + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; } function daysInMonth(year, month) { - if (isNaN(year) || isNaN(month)) { - return NaN; - } - var modMonth = mod(month, 12); - year += (month - modMonth) / 12; - return modMonth === 1 - ? isLeapYear(year) - ? 29 - : 28 - : 31 - ((modMonth % 7) % 2); + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 + ? isLeapYear(year) + ? 29 + : 28 + : 31 - ((modMonth % 7) % 2); } // FORMATTING - addFormatToken('M', ['MM', 2], 'Mo', function () { - return this.month() + 1; + addFormatToken("M", ["MM", 2], "Mo", function () { + return this.month() + 1; }); - addFormatToken('MMM', 0, 0, function (format) { - return this.localeData().monthsShort(this, format); + addFormatToken("MMM", 0, 0, function (format) { + return this.localeData().monthsShort(this, format); }); - addFormatToken('MMMM', 0, 0, function (format) { - return this.localeData().months(this, format); + addFormatToken("MMMM", 0, 0, function (format) { + return this.localeData().months(this, format); }); // ALIASES - addUnitAlias('month', 'M'); + addUnitAlias("month", "M"); // PRIORITY - addUnitPriority('month', 8); + addUnitPriority("month", 8); // PARSING - addRegexToken('M', match1to2); - addRegexToken('MM', match1to2, match2); - addRegexToken('MMM', function (isStrict, locale) { - return locale.monthsShortRegex(isStrict); + addRegexToken("M", match1to2); + addRegexToken("MM", match1to2, match2); + addRegexToken("MMM", function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); }); - addRegexToken('MMMM', function (isStrict, locale) { - return locale.monthsRegex(isStrict); + addRegexToken("MMMM", function (isStrict, locale) { + return locale.monthsRegex(isStrict); }); - addParseToken(['M', 'MM'], function (input, array) { - array[MONTH] = toInt(input) - 1; + addParseToken(["M", "MM"], function (input, array) { + array[MONTH] = toInt(input) - 1; }); - addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { - var month = config._locale.monthsParse(input, token, config._strict); - // if we didn't find a month name, mark the date as invalid. - if (month != null) { - array[MONTH] = month; - } else { - getParsingFlags(config).invalidMonth = input; - } + addParseToken(["MMM", "MMMM"], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } }); // LOCALES - var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split( - '_' + var defaultLocaleMonths = + "January_February_March_April_May_June_July_August_September_October_November_December".split( + "_", ), - defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split( - '_' - ), - MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, - defaultMonthsShortRegex = matchWord, - defaultMonthsRegex = matchWord; + defaultLocaleMonthsShort = + "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), + MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, + defaultMonthsShortRegex = matchWord, + defaultMonthsRegex = matchWord; function localeMonths(m, format) { - if (!m) { - return isArray(this._months) - ? this._months - : this._months['standalone']; - } - return isArray(this._months) - ? this._months[m.month()] - : this._months[ - (this._months.isFormat || MONTHS_IN_FORMAT).test(format) - ? 'format' - : 'standalone' - ][m.month()]; + if (!m) { + return isArray(this._months) ? this._months : this._months["standalone"]; + } + return isArray(this._months) + ? this._months[m.month()] + : this._months[ + (this._months.isFormat || MONTHS_IN_FORMAT).test(format) + ? "format" + : "standalone" + ][m.month()]; } function localeMonthsShort(m, format) { - if (!m) { - return isArray(this._monthsShort) - ? this._monthsShort - : this._monthsShort['standalone']; - } + if (!m) { return isArray(this._monthsShort) - ? this._monthsShort[m.month()] - : this._monthsShort[ - MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone' - ][m.month()]; + ? this._monthsShort + : this._monthsShort["standalone"]; + } + return isArray(this._monthsShort) + ? this._monthsShort[m.month()] + : this._monthsShort[ + MONTHS_IN_FORMAT.test(format) ? "format" : "standalone" + ][m.month()]; } function handleStrictParse(monthName, format, strict) { - var i, - ii, + var i, + ii, + mom, + llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort( mom, - llc = monthName.toLocaleLowerCase(); - if (!this._monthsParse) { - // this is not used - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - for (i = 0; i < 12; ++i) { - mom = createUTC([2000, i]); - this._shortMonthsParse[i] = this.monthsShort( - mom, - '' - ).toLocaleLowerCase(); - this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); - } + "", + ).toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, "").toLocaleLowerCase(); } + } - if (strict) { - if (format === 'MMM') { - ii = indexOf.call(this._shortMonthsParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._longMonthsParse, llc); - return ii !== -1 ? ii : null; - } + if (strict) { + if (format === "MMM") { + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; } else { - if (format === 'MMM') { - ii = indexOf.call(this._shortMonthsParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._longMonthsParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._longMonthsParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortMonthsParse, llc); - return ii !== -1 ? ii : null; - } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; } + } else { + if (format === "MMM") { + ii = indexOf.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } } function localeMonthsParse(monthName, format, strict) { - var i, mom, regex; + var i, mom, regex; - if (this._monthsParseExact) { - return handleStrictParse.call(this, monthName, format, strict); - } + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } - if (!this._monthsParse) { - this._monthsParse = []; - this._longMonthsParse = []; - this._shortMonthsParse = []; - } + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } - // TODO: add sorting - // Sorting makes sure if one month (or abbr) is a prefix of another - // see sorting in computeMonthsParse - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, i]); - if (strict && !this._longMonthsParse[i]) { - this._longMonthsParse[i] = new RegExp( - '^' + this.months(mom, '').replace('.', '') + '$', - 'i' - ); - this._shortMonthsParse[i] = new RegExp( - '^' + this.monthsShort(mom, '').replace('.', '') + '$', - 'i' - ); - } - if (!strict && !this._monthsParse[i]) { - regex = - '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); - this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if ( - strict && - format === 'MMMM' && - this._longMonthsParse[i].test(monthName) - ) { - return i; - } else if ( - strict && - format === 'MMM' && - this._shortMonthsParse[i].test(monthName) - ) { - return i; - } else if (!strict && this._monthsParse[i].test(monthName)) { - return i; - } + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp( + "^" + this.months(mom, "").replace(".", "") + "$", + "i", + ); + this._shortMonthsParse[i] = new RegExp( + "^" + this.monthsShort(mom, "").replace(".", "") + "$", + "i", + ); } + if (!strict && !this._monthsParse[i]) { + regex = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, ""); + this._monthsParse[i] = new RegExp(regex.replace(".", ""), "i"); + } + // test the regex + if ( + strict && + format === "MMMM" && + this._longMonthsParse[i].test(monthName) + ) { + return i; + } else if ( + strict && + format === "MMM" && + this._shortMonthsParse[i].test(monthName) + ) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } } // MOMENTS function setMonth(mom, value) { - var dayOfMonth; + var dayOfMonth; - if (!mom.isValid()) { - // No op - return mom; - } - - if (typeof value === 'string') { - if (/^\d+$/.test(value)) { - value = toInt(value); - } else { - value = mom.localeData().monthsParse(value); - // TODO: Another silent failure? - if (!isNumber(value)) { - return mom; - } - } - } - - dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); - mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + if (!mom.isValid()) { + // No op return mom; + } + + if (typeof value === "string") { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } + + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d["set" + (mom._isUTC ? "UTC" : "") + "Month"](value, dayOfMonth); + return mom; } function getSetMonth(value) { - if (value != null) { - setMonth(this, value); - hooks.updateOffset(this, true); - return this; - } else { - return get(this, 'Month'); - } + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, "Month"); + } } function getDaysInMonth() { - return daysInMonth(this.year(), this.month()); + return daysInMonth(this.year(), this.month()); } function monthsShortRegex(isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, '_monthsRegex')) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsShortStrictRegex; - } else { - return this._monthsShortRegex; - } - } else { - if (!hasOwnProp(this, '_monthsShortRegex')) { - this._monthsShortRegex = defaultMonthsShortRegex; - } - return this._monthsShortStrictRegex && isStrict - ? this._monthsShortStrictRegex - : this._monthsShortRegex; + if (this._monthsParseExact) { + if (!hasOwnProp(this, "_monthsRegex")) { + computeMonthsParse.call(this); } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, "_monthsShortRegex")) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict + ? this._monthsShortStrictRegex + : this._monthsShortRegex; + } } function monthsRegex(isStrict) { - if (this._monthsParseExact) { - if (!hasOwnProp(this, '_monthsRegex')) { - computeMonthsParse.call(this); - } - if (isStrict) { - return this._monthsStrictRegex; - } else { - return this._monthsRegex; - } - } else { - if (!hasOwnProp(this, '_monthsRegex')) { - this._monthsRegex = defaultMonthsRegex; - } - return this._monthsStrictRegex && isStrict - ? this._monthsStrictRegex - : this._monthsRegex; + if (this._monthsParseExact) { + if (!hasOwnProp(this, "_monthsRegex")) { + computeMonthsParse.call(this); } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, "_monthsRegex")) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict + ? this._monthsStrictRegex + : this._monthsRegex; + } } function computeMonthsParse() { - function cmpLenRev(a, b) { - return b.length - a.length; - } + function cmpLenRev(a, b) { + return b.length - a.length; + } - var shortPieces = [], - longPieces = [], - mixedPieces = [], - i, - mom; - for (i = 0; i < 12; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, i]); - shortPieces.push(this.monthsShort(mom, '')); - longPieces.push(this.months(mom, '')); - mixedPieces.push(this.months(mom, '')); - mixedPieces.push(this.monthsShort(mom, '')); - } - // Sorting makes sure if one month (or abbr) is a prefix of another it - // will match the longer piece. - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); - for (i = 0; i < 12; i++) { - shortPieces[i] = regexEscape(shortPieces[i]); - longPieces[i] = regexEscape(longPieces[i]); - } - for (i = 0; i < 24; i++) { - mixedPieces[i] = regexEscape(mixedPieces[i]); - } + var shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortPieces.push(this.monthsShort(mom, "")); + longPieces.push(this.months(mom, "")); + mixedPieces.push(this.months(mom, "")); + mixedPieces.push(this.monthsShort(mom, "")); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 12; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + } + for (i = 0; i < 24; i++) { + mixedPieces[i] = regexEscape(mixedPieces[i]); + } - this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); - this._monthsShortRegex = this._monthsRegex; - this._monthsStrictRegex = new RegExp( - '^(' + longPieces.join('|') + ')', - 'i' - ); - this._monthsShortStrictRegex = new RegExp( - '^(' + shortPieces.join('|') + ')', - 'i' - ); + this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp( + "^(" + longPieces.join("|") + ")", + "i", + ); + this._monthsShortStrictRegex = new RegExp( + "^(" + shortPieces.join("|") + ")", + "i", + ); } // FORMATTING - addFormatToken('Y', 0, 0, function () { - var y = this.year(); - return y <= 9999 ? zeroFill(y, 4) : '+' + y; + addFormatToken("Y", 0, 0, function () { + var y = this.year(); + return y <= 9999 ? zeroFill(y, 4) : "+" + y; }); - addFormatToken(0, ['YY', 2], 0, function () { - return this.year() % 100; + addFormatToken(0, ["YY", 2], 0, function () { + return this.year() % 100; }); - addFormatToken(0, ['YYYY', 4], 0, 'year'); - addFormatToken(0, ['YYYYY', 5], 0, 'year'); - addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + addFormatToken(0, ["YYYY", 4], 0, "year"); + addFormatToken(0, ["YYYYY", 5], 0, "year"); + addFormatToken(0, ["YYYYYY", 6, true], 0, "year"); // ALIASES - addUnitAlias('year', 'y'); + addUnitAlias("year", "y"); // PRIORITIES - addUnitPriority('year', 1); + addUnitPriority("year", 1); // PARSING - addRegexToken('Y', matchSigned); - addRegexToken('YY', match1to2, match2); - addRegexToken('YYYY', match1to4, match4); - addRegexToken('YYYYY', match1to6, match6); - addRegexToken('YYYYYY', match1to6, match6); + addRegexToken("Y", matchSigned); + addRegexToken("YY", match1to2, match2); + addRegexToken("YYYY", match1to4, match4); + addRegexToken("YYYYY", match1to6, match6); + addRegexToken("YYYYYY", match1to6, match6); - addParseToken(['YYYYY', 'YYYYYY'], YEAR); - addParseToken('YYYY', function (input, array) { - array[YEAR] = - input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + addParseToken(["YYYYY", "YYYYYY"], YEAR); + addParseToken("YYYY", function (input, array) { + array[YEAR] = + input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); }); - addParseToken('YY', function (input, array) { - array[YEAR] = hooks.parseTwoDigitYear(input); + addParseToken("YY", function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); }); - addParseToken('Y', function (input, array) { - array[YEAR] = parseInt(input, 10); + addParseToken("Y", function (input, array) { + array[YEAR] = parseInt(input, 10); }); // HELPERS function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; + return isLeapYear(year) ? 366 : 365; } // HOOKS hooks.parseTwoDigitYear = function (input) { - return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS - var getSetYear = makeGetSet('FullYear', true); + var getSetYear = makeGetSet("FullYear", true); function getIsLeapYear() { - return isLeapYear(this.year()); + return isLeapYear(this.year()); } function createDate(y, m, d, h, M, s, ms) { - // can't just apply() to create a date: - // https://stackoverflow.com/q/181348 - var date; - // the date constructor remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - // preserve leap years using a full 400 year cycle, then reset - date = new Date(y + 400, m, d, h, M, s, ms); - if (isFinite(date.getFullYear())) { - date.setFullYear(y); - } - } else { - date = new Date(y, m, d, h, M, s, ms); + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date; + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + date = new Date(y + 400, m, d, h, M, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y); } + } else { + date = new Date(y, m, d, h, M, s, ms); + } - return date; + return date; } function createUTCDate(y) { - var date, args; - // the Date.UTC function remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - args = Array.prototype.slice.call(arguments); - // preserve leap years using a full 400 year cycle, then reset - args[0] = y + 400; - date = new Date(Date.UTC.apply(null, args)); - if (isFinite(date.getUTCFullYear())) { - date.setUTCFullYear(y); - } - } else { - date = new Date(Date.UTC.apply(null, arguments)); + var date, args; + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + args = Array.prototype.slice.call(arguments); + // preserve leap years using a full 400 year cycle, then reset + args[0] = y + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); } + } else { + date = new Date(Date.UTC.apply(null, arguments)); + } - return date; + return date; } // start-of-first-week - start-of-year function firstWeekOffset(year, dow, doy) { - var // first-week day -- which january is always in the first week (4 for iso, 1 for other) - fwd = 7 + dow - doy, - // first-week day local weekday -- which local weekday is fwd - fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; - return -fwdlw + fwd - 1; + return -fwdlw + fwd - 1; } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, dow, doy) { - var localWeekday = (7 + weekday - dow) % 7, - weekOffset = firstWeekOffset(year, dow, doy), - dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, - resYear, - resDayOfYear; + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, + resDayOfYear; - if (dayOfYear <= 0) { - resYear = year - 1; - resDayOfYear = daysInYear(resYear) + dayOfYear; - } else if (dayOfYear > daysInYear(year)) { - resYear = year + 1; - resDayOfYear = dayOfYear - daysInYear(year); - } else { - resYear = year; - resDayOfYear = dayOfYear; - } + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } - return { - year: resYear, - dayOfYear: resDayOfYear, - }; + return { + year: resYear, + dayOfYear: resDayOfYear, + }; } function weekOfYear(mom, dow, doy) { - var weekOffset = firstWeekOffset(mom.year(), dow, doy), - week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, - resWeek, - resYear; + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, + resYear; - if (week < 1) { - resYear = mom.year() - 1; - resWeek = week + weeksInYear(resYear, dow, doy); - } else if (week > weeksInYear(mom.year(), dow, doy)) { - resWeek = week - weeksInYear(mom.year(), dow, doy); - resYear = mom.year() + 1; - } else { - resYear = mom.year(); - resWeek = week; - } + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } - return { - week: resWeek, - year: resYear, - }; + return { + week: resWeek, + year: resYear, + }; } function weeksInYear(year, dow, doy) { - var weekOffset = firstWeekOffset(year, dow, doy), - weekOffsetNext = firstWeekOffset(year + 1, dow, doy); - return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } // FORMATTING - addFormatToken('w', ['ww', 2], 'wo', 'week'); - addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + addFormatToken("w", ["ww", 2], "wo", "week"); + addFormatToken("W", ["WW", 2], "Wo", "isoWeek"); // ALIASES - addUnitAlias('week', 'w'); - addUnitAlias('isoWeek', 'W'); + addUnitAlias("week", "w"); + addUnitAlias("isoWeek", "W"); // PRIORITIES - addUnitPriority('week', 5); - addUnitPriority('isoWeek', 5); + addUnitPriority("week", 5); + addUnitPriority("isoWeek", 5); // PARSING - addRegexToken('w', match1to2); - addRegexToken('ww', match1to2, match2); - addRegexToken('W', match1to2); - addRegexToken('WW', match1to2, match2); + addRegexToken("w", match1to2); + addRegexToken("ww", match1to2, match2); + addRegexToken("W", match1to2); + addRegexToken("WW", match1to2, match2); - addWeekParseToken(['w', 'ww', 'W', 'WW'], function ( - input, - week, - config, - token - ) { + addWeekParseToken( + ["w", "ww", "W", "WW"], + function (input, week, config, token) { week[token.substr(0, 1)] = toInt(input); - }); + }, + ); // HELPERS // LOCALES function localeWeek(mom) { - return weekOfYear(mom, this._week.dow, this._week.doy).week; + return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { - dow: 0, // Sunday is the first day of the week. - doy: 6, // The week that contains Jan 6th is the first week of the year. + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. }; function localeFirstDayOfWeek() { - return this._week.dow; + return this._week.dow; } function localeFirstDayOfYear() { - return this._week.doy; + return this._week.doy; } // MOMENTS function getSetWeek(input) { - var week = this.localeData().week(this); - return input == null ? week : this.add((input - week) * 7, 'd'); + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, "d"); } function getSetISOWeek(input) { - var week = weekOfYear(this, 1, 4).week; - return input == null ? week : this.add((input - week) * 7, 'd'); + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, "d"); } // FORMATTING - addFormatToken('d', 0, 'do', 'day'); + addFormatToken("d", 0, "do", "day"); - addFormatToken('dd', 0, 0, function (format) { - return this.localeData().weekdaysMin(this, format); + addFormatToken("dd", 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); }); - addFormatToken('ddd', 0, 0, function (format) { - return this.localeData().weekdaysShort(this, format); + addFormatToken("ddd", 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); }); - addFormatToken('dddd', 0, 0, function (format) { - return this.localeData().weekdays(this, format); + addFormatToken("dddd", 0, 0, function (format) { + return this.localeData().weekdays(this, format); }); - addFormatToken('e', 0, 0, 'weekday'); - addFormatToken('E', 0, 0, 'isoWeekday'); + addFormatToken("e", 0, 0, "weekday"); + addFormatToken("E", 0, 0, "isoWeekday"); // ALIASES - addUnitAlias('day', 'd'); - addUnitAlias('weekday', 'e'); - addUnitAlias('isoWeekday', 'E'); + addUnitAlias("day", "d"); + addUnitAlias("weekday", "e"); + addUnitAlias("isoWeekday", "E"); // PRIORITY - addUnitPriority('day', 11); - addUnitPriority('weekday', 11); - addUnitPriority('isoWeekday', 11); + addUnitPriority("day", 11); + addUnitPriority("weekday", 11); + addUnitPriority("isoWeekday", 11); // PARSING - addRegexToken('d', match1to2); - addRegexToken('e', match1to2); - addRegexToken('E', match1to2); - addRegexToken('dd', function (isStrict, locale) { - return locale.weekdaysMinRegex(isStrict); + addRegexToken("d", match1to2); + addRegexToken("e", match1to2); + addRegexToken("E", match1to2); + addRegexToken("dd", function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); }); - addRegexToken('ddd', function (isStrict, locale) { - return locale.weekdaysShortRegex(isStrict); + addRegexToken("ddd", function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); }); - addRegexToken('dddd', function (isStrict, locale) { - return locale.weekdaysRegex(isStrict); + addRegexToken("dddd", function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); }); - addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + addWeekParseToken( + ["dd", "ddd", "dddd"], + function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { - week.d = weekday; + week.d = weekday; } else { - getParsingFlags(config).invalidWeekday = input; + getParsingFlags(config).invalidWeekday = input; } - }); + }, + ); - addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { - week[token] = toInt(input); + addWeekParseToken(["d", "e", "E"], function (input, week, config, token) { + week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { - if (typeof input !== 'string') { - return input; - } + if (typeof input !== "string") { + return input; + } - if (!isNaN(input)) { - return parseInt(input, 10); - } + if (!isNaN(input)) { + return parseInt(input, 10); + } - input = locale.weekdaysParse(input); - if (typeof input === 'number') { - return input; - } + input = locale.weekdaysParse(input); + if (typeof input === "number") { + return input; + } - return null; + return null; } function parseIsoWeekday(input, locale) { - if (typeof input === 'string') { - return locale.weekdaysParse(input) % 7 || 7; - } - return isNaN(input) ? null : input; + if (typeof input === "string") { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; } // LOCALES function shiftWeekdays(ws, n) { - return ws.slice(n, 7).concat(ws.slice(0, n)); + return ws.slice(n, 7).concat(ws.slice(0, n)); } - var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( - '_' - ), - defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), - defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), - defaultWeekdaysRegex = matchWord, - defaultWeekdaysShortRegex = matchWord, - defaultWeekdaysMinRegex = matchWord; + var defaultLocaleWeekdays = + "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), + defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), + defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), + defaultWeekdaysRegex = matchWord, + defaultWeekdaysShortRegex = matchWord, + defaultWeekdaysMinRegex = matchWord; function localeWeekdays(m, format) { - var weekdays = isArray(this._weekdays) - ? this._weekdays - : this._weekdays[ - m && m !== true && this._weekdays.isFormat.test(format) - ? 'format' - : 'standalone' - ]; - return m === true - ? shiftWeekdays(weekdays, this._week.dow) - : m - ? weekdays[m.day()] - : weekdays; + var weekdays = isArray(this._weekdays) + ? this._weekdays + : this._weekdays[ + m && m !== true && this._weekdays.isFormat.test(format) + ? "format" + : "standalone" + ]; + return m === true + ? shiftWeekdays(weekdays, this._week.dow) + : m + ? weekdays[m.day()] + : weekdays; } function localeWeekdaysShort(m) { - return m === true - ? shiftWeekdays(this._weekdaysShort, this._week.dow) - : m - ? this._weekdaysShort[m.day()] - : this._weekdaysShort; + return m === true + ? shiftWeekdays(this._weekdaysShort, this._week.dow) + : m + ? this._weekdaysShort[m.day()] + : this._weekdaysShort; } function localeWeekdaysMin(m) { - return m === true - ? shiftWeekdays(this._weekdaysMin, this._week.dow) - : m - ? this._weekdaysMin[m.day()] - : this._weekdaysMin; + return m === true + ? shiftWeekdays(this._weekdaysMin, this._week.dow) + : m + ? this._weekdaysMin[m.day()] + : this._weekdaysMin; } function handleStrictParse$1(weekdayName, format, strict) { - var i, - ii, + var i, + ii, + mom, + llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin( mom, - llc = weekdayName.toLocaleLowerCase(); - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._shortWeekdaysParse = []; - this._minWeekdaysParse = []; - - for (i = 0; i < 7; ++i) { - mom = createUTC([2000, 1]).day(i); - this._minWeekdaysParse[i] = this.weekdaysMin( - mom, - '' - ).toLocaleLowerCase(); - this._shortWeekdaysParse[i] = this.weekdaysShort( - mom, - '' - ).toLocaleLowerCase(); - this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); - } + "", + ).toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort( + mom, + "", + ).toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, "").toLocaleLowerCase(); } + } - if (strict) { - if (format === 'dddd') { - ii = indexOf.call(this._weekdaysParse, llc); - return ii !== -1 ? ii : null; - } else if (format === 'ddd') { - ii = indexOf.call(this._shortWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } + if (strict) { + if (format === "dddd") { + ii = indexOf.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === "ddd") { + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; } else { - if (format === 'dddd') { - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else if (format === 'ddd') { - ii = indexOf.call(this._shortWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._minWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } else { - ii = indexOf.call(this._minWeekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._weekdaysParse, llc); - if (ii !== -1) { - return ii; - } - ii = indexOf.call(this._shortWeekdaysParse, llc); - return ii !== -1 ? ii : null; - } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; } + } else { + if (format === "dddd") { + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === "ddd") { + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } } function localeWeekdaysParse(weekdayName, format, strict) { - var i, mom, regex; + var i, mom, regex; - if (this._weekdaysParseExact) { - return handleStrictParse$1.call(this, weekdayName, format, strict); + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } + + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp( + "^" + this.weekdays(mom, "").replace(".", "\\.?") + "$", + "i", + ); + this._shortWeekdaysParse[i] = new RegExp( + "^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$", + "i", + ); + this._minWeekdaysParse[i] = new RegExp( + "^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$", + "i", + ); } - - if (!this._weekdaysParse) { - this._weekdaysParse = []; - this._minWeekdaysParse = []; - this._shortWeekdaysParse = []; - this._fullWeekdaysParse = []; + if (!this._weekdaysParse[i]) { + regex = + "^" + + this.weekdays(mom, "") + + "|^" + + this.weekdaysShort(mom, "") + + "|^" + + this.weekdaysMin(mom, ""); + this._weekdaysParse[i] = new RegExp(regex.replace(".", ""), "i"); } - - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already - - mom = createUTC([2000, 1]).day(i); - if (strict && !this._fullWeekdaysParse[i]) { - this._fullWeekdaysParse[i] = new RegExp( - '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', - 'i' - ); - this._shortWeekdaysParse[i] = new RegExp( - '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', - 'i' - ); - this._minWeekdaysParse[i] = new RegExp( - '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', - 'i' - ); - } - if (!this._weekdaysParse[i]) { - regex = - '^' + - this.weekdays(mom, '') + - '|^' + - this.weekdaysShort(mom, '') + - '|^' + - this.weekdaysMin(mom, ''); - this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); - } - // test the regex - if ( - strict && - format === 'dddd' && - this._fullWeekdaysParse[i].test(weekdayName) - ) { - return i; - } else if ( - strict && - format === 'ddd' && - this._shortWeekdaysParse[i].test(weekdayName) - ) { - return i; - } else if ( - strict && - format === 'dd' && - this._minWeekdaysParse[i].test(weekdayName) - ) { - return i; - } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { - return i; - } + // test the regex + if ( + strict && + format === "dddd" && + this._fullWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === "ddd" && + this._shortWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === "dd" && + this._minWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; } + } } // MOMENTS function getSetDayOfWeek(input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } - var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); - if (input != null) { - input = parseWeekday(input, this.localeData()); - return this.add(input - day, 'd'); - } else { - return day; - } + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, "d"); + } else { + return day; + } } function getSetLocaleDayOfWeek(input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } - var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; - return input == null ? weekday : this.add(input - weekday, 'd'); + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, "d"); } function getSetISODayOfWeek(input) { - if (!this.isValid()) { - return input != null ? this : NaN; - } + if (!this.isValid()) { + return input != null ? this : NaN; + } - // behaves the same as moment#day except - // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) - // as a setter, sunday should belong to the previous week. + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. - if (input != null) { - var weekday = parseIsoWeekday(input, this.localeData()); - return this.day(this.day() % 7 ? weekday : weekday - 7); - } else { - return this.day() || 7; - } + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } } function weekdaysRegex(isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysStrictRegex; - } else { - return this._weekdaysRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysRegex')) { - this._weekdaysRegex = defaultWeekdaysRegex; - } - return this._weekdaysStrictRegex && isStrict - ? this._weekdaysStrictRegex - : this._weekdaysRegex; + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysRegex")) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict + ? this._weekdaysStrictRegex + : this._weekdaysRegex; + } } function weekdaysShortRegex(isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysShortStrictRegex; - } else { - return this._weekdaysShortRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysShortRegex')) { - this._weekdaysShortRegex = defaultWeekdaysShortRegex; - } - return this._weekdaysShortStrictRegex && isStrict - ? this._weekdaysShortStrictRegex - : this._weekdaysShortRegex; + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysShortRegex")) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict + ? this._weekdaysShortStrictRegex + : this._weekdaysShortRegex; + } } function weekdaysMinRegex(isStrict) { - if (this._weekdaysParseExact) { - if (!hasOwnProp(this, '_weekdaysRegex')) { - computeWeekdaysParse.call(this); - } - if (isStrict) { - return this._weekdaysMinStrictRegex; - } else { - return this._weekdaysMinRegex; - } - } else { - if (!hasOwnProp(this, '_weekdaysMinRegex')) { - this._weekdaysMinRegex = defaultWeekdaysMinRegex; - } - return this._weekdaysMinStrictRegex && isStrict - ? this._weekdaysMinStrictRegex - : this._weekdaysMinRegex; + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, "_weekdaysRegex")) { + computeWeekdaysParse.call(this); } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, "_weekdaysMinRegex")) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict + ? this._weekdaysMinStrictRegex + : this._weekdaysMinRegex; + } } function computeWeekdaysParse() { - function cmpLenRev(a, b) { - return b.length - a.length; - } + function cmpLenRev(a, b) { + return b.length - a.length; + } - var minPieces = [], - shortPieces = [], - longPieces = [], - mixedPieces = [], - i, - mom, - minp, - shortp, - longp; - for (i = 0; i < 7; i++) { - // make the regex if we don't have it already - mom = createUTC([2000, 1]).day(i); - minp = regexEscape(this.weekdaysMin(mom, '')); - shortp = regexEscape(this.weekdaysShort(mom, '')); - longp = regexEscape(this.weekdays(mom, '')); - minPieces.push(minp); - shortPieces.push(shortp); - longPieces.push(longp); - mixedPieces.push(minp); - mixedPieces.push(shortp); - mixedPieces.push(longp); - } - // Sorting makes sure if one weekday (or abbr) is a prefix of another it - // will match the longer piece. - minPieces.sort(cmpLenRev); - shortPieces.sort(cmpLenRev); - longPieces.sort(cmpLenRev); - mixedPieces.sort(cmpLenRev); + var minPieces = [], + shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom, + minp, + shortp, + longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = regexEscape(this.weekdaysMin(mom, "")); + shortp = regexEscape(this.weekdaysShort(mom, "")); + longp = regexEscape(this.weekdays(mom, "")); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); - this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); - this._weekdaysShortRegex = this._weekdaysRegex; - this._weekdaysMinRegex = this._weekdaysRegex; + this._weekdaysRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; - this._weekdaysStrictRegex = new RegExp( - '^(' + longPieces.join('|') + ')', - 'i' - ); - this._weekdaysShortStrictRegex = new RegExp( - '^(' + shortPieces.join('|') + ')', - 'i' - ); - this._weekdaysMinStrictRegex = new RegExp( - '^(' + minPieces.join('|') + ')', - 'i' - ); + this._weekdaysStrictRegex = new RegExp( + "^(" + longPieces.join("|") + ")", + "i", + ); + this._weekdaysShortStrictRegex = new RegExp( + "^(" + shortPieces.join("|") + ")", + "i", + ); + this._weekdaysMinStrictRegex = new RegExp( + "^(" + minPieces.join("|") + ")", + "i", + ); } // FORMATTING function hFormat() { - return this.hours() % 12 || 12; + return this.hours() % 12 || 12; } function kFormat() { - return this.hours() || 24; + return this.hours() || 24; } - addFormatToken('H', ['HH', 2], 0, 'hour'); - addFormatToken('h', ['hh', 2], 0, hFormat); - addFormatToken('k', ['kk', 2], 0, kFormat); + addFormatToken("H", ["HH", 2], 0, "hour"); + addFormatToken("h", ["hh", 2], 0, hFormat); + addFormatToken("k", ["kk", 2], 0, kFormat); - addFormatToken('hmm', 0, 0, function () { - return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); + addFormatToken("hmm", 0, 0, function () { + return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); - addFormatToken('hmmss', 0, 0, function () { - return ( - '' + - hFormat.apply(this) + - zeroFill(this.minutes(), 2) + - zeroFill(this.seconds(), 2) - ); + addFormatToken("hmmss", 0, 0, function () { + return ( + "" + + hFormat.apply(this) + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); }); - addFormatToken('Hmm', 0, 0, function () { - return '' + this.hours() + zeroFill(this.minutes(), 2); + addFormatToken("Hmm", 0, 0, function () { + return "" + this.hours() + zeroFill(this.minutes(), 2); }); - addFormatToken('Hmmss', 0, 0, function () { - return ( - '' + - this.hours() + - zeroFill(this.minutes(), 2) + - zeroFill(this.seconds(), 2) - ); + addFormatToken("Hmmss", 0, 0, function () { + return ( + "" + + this.hours() + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); }); function meridiem(token, lowercase) { - addFormatToken(token, 0, 0, function () { - return this.localeData().meridiem( - this.hours(), - this.minutes(), - lowercase - ); - }); + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem( + this.hours(), + this.minutes(), + lowercase, + ); + }); } - meridiem('a', true); - meridiem('A', false); + meridiem("a", true); + meridiem("A", false); // ALIASES - addUnitAlias('hour', 'h'); + addUnitAlias("hour", "h"); // PRIORITY - addUnitPriority('hour', 13); + addUnitPriority("hour", 13); // PARSING function matchMeridiem(isStrict, locale) { - return locale._meridiemParse; + return locale._meridiemParse; } - addRegexToken('a', matchMeridiem); - addRegexToken('A', matchMeridiem); - addRegexToken('H', match1to2); - addRegexToken('h', match1to2); - addRegexToken('k', match1to2); - addRegexToken('HH', match1to2, match2); - addRegexToken('hh', match1to2, match2); - addRegexToken('kk', match1to2, match2); + addRegexToken("a", matchMeridiem); + addRegexToken("A", matchMeridiem); + addRegexToken("H", match1to2); + addRegexToken("h", match1to2); + addRegexToken("k", match1to2); + addRegexToken("HH", match1to2, match2); + addRegexToken("hh", match1to2, match2); + addRegexToken("kk", match1to2, match2); - addRegexToken('hmm', match3to4); - addRegexToken('hmmss', match5to6); - addRegexToken('Hmm', match3to4); - addRegexToken('Hmmss', match5to6); + addRegexToken("hmm", match3to4); + addRegexToken("hmmss", match5to6); + addRegexToken("Hmm", match3to4); + addRegexToken("Hmmss", match5to6); - addParseToken(['H', 'HH'], HOUR); - addParseToken(['k', 'kk'], function (input, array, config) { - var kInput = toInt(input); - array[HOUR] = kInput === 24 ? 0 : kInput; + addParseToken(["H", "HH"], HOUR); + addParseToken(["k", "kk"], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; }); - addParseToken(['a', 'A'], function (input, array, config) { - config._isPm = config._locale.isPM(input); - config._meridiem = input; + addParseToken(["a", "A"], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; }); - addParseToken(['h', 'hh'], function (input, array, config) { - array[HOUR] = toInt(input); - getParsingFlags(config).bigHour = true; + addParseToken(["h", "hh"], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; }); - addParseToken('hmm', function (input, array, config) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); - getParsingFlags(config).bigHour = true; + addParseToken("hmm", function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; }); - addParseToken('hmmss', function (input, array, config) { - var pos1 = input.length - 4, - pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); - getParsingFlags(config).bigHour = true; + addParseToken("hmmss", function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; }); - addParseToken('Hmm', function (input, array, config) { - var pos = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos)); - array[MINUTE] = toInt(input.substr(pos)); + addParseToken("Hmm", function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); }); - addParseToken('Hmmss', function (input, array, config) { - var pos1 = input.length - 4, - pos2 = input.length - 2; - array[HOUR] = toInt(input.substr(0, pos1)); - array[MINUTE] = toInt(input.substr(pos1, 2)); - array[SECOND] = toInt(input.substr(pos2)); + addParseToken("Hmmss", function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); }); // LOCALES function localeIsPM(input) { - // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays - // Using charAt should be more compatible. - return (input + '').toLowerCase().charAt(0) === 'p'; + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return (input + "").toLowerCase().charAt(0) === "p"; } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, - // Setting the hour should keep the time, because the user explicitly - // specified which hour they want. So trying to maintain the same hour (in - // a new timezone) makes sense. Adding/subtracting hours does not follow - // this rule. - getSetHour = makeGetSet('Hours', true); + // Setting the hour should keep the time, because the user explicitly + // specified which hour they want. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + getSetHour = makeGetSet("Hours", true); function localeMeridiem(hours, minutes, isLower) { - if (hours > 11) { - return isLower ? 'pm' : 'PM'; - } else { - return isLower ? 'am' : 'AM'; - } + if (hours > 11) { + return isLower ? "pm" : "PM"; + } else { + return isLower ? "am" : "AM"; + } } var baseConfig = { - calendar: defaultCalendar, - longDateFormat: defaultLongDateFormat, - invalidDate: defaultInvalidDate, - ordinal: defaultOrdinal, - dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, - relativeTime: defaultRelativeTime, + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, - months: defaultLocaleMonths, - monthsShort: defaultLocaleMonthsShort, + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, - week: defaultLocaleWeek, + week: defaultLocaleWeek, - weekdays: defaultLocaleWeekdays, - weekdaysMin: defaultLocaleWeekdaysMin, - weekdaysShort: defaultLocaleWeekdaysShort, + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, - meridiemParse: defaultLocaleMeridiemParse, + meridiemParse: defaultLocaleMeridiemParse, }; // internal storage for locale config files var locales = {}, - localeFamilies = {}, - globalLocale; + localeFamilies = {}, + globalLocale; function commonPrefix(arr1, arr2) { - var i, - minl = Math.min(arr1.length, arr2.length); - for (i = 0; i < minl; i += 1) { - if (arr1[i] !== arr2[i]) { - return i; - } + var i, + minl = Math.min(arr1.length, arr2.length); + for (i = 0; i < minl; i += 1) { + if (arr1[i] !== arr2[i]) { + return i; } - return minl; + } + return minl; } function normalizeLocale(key) { - return key ? key.toLowerCase().replace('_', '-') : key; + return key ? key.toLowerCase().replace("_", "-") : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { - var i = 0, - j, - next, - locale, - split; + var i = 0, + j, + next, + locale, + split; - while (i < names.length) { - split = normalizeLocale(names[i]).split('-'); - j = split.length; - next = normalizeLocale(names[i + 1]); - next = next ? next.split('-') : null; - while (j > 0) { - locale = loadLocale(split.slice(0, j).join('-')); - if (locale) { - return locale; - } - if ( - next && - next.length >= j && - commonPrefix(split, next) >= j - 1 - ) { - //the next array item is better than a shallower substring of this one - break; - } - j--; - } - i++; + while (i < names.length) { + split = normalizeLocale(names[i]).split("-"); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split("-") : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join("-")); + if (locale) { + return locale; + } + if (next && next.length >= j && commonPrefix(split, next) >= j - 1) { + //the next array item is better than a shallower substring of this one + break; + } + j--; } - return globalLocale; + i++; + } + return globalLocale; } function loadLocale(name) { - var oldLocale = null, - aliasedRequire; - // TODO: Find a better way to register and load all the locales in Node - if ( - locales[name] === undefined && - typeof module !== 'undefined' && - module && - module.exports - ) { - try { - oldLocale = globalLocale._abbr; - aliasedRequire = require; - aliasedRequire('./locale/' + name); - getSetGlobalLocale(oldLocale); - } catch (e) { - // mark as not found to avoid repeating expensive file require call causing high CPU - // when trying to find en-US, en_US, en-us for every format call - locales[name] = null; // null means not found - } + var oldLocale = null, + aliasedRequire; + // TODO: Find a better way to register and load all the locales in Node + if ( + locales[name] === undefined && + typeof module !== "undefined" && + module && + module.exports + ) { + try { + oldLocale = globalLocale._abbr; + aliasedRequire = require; + aliasedRequire("./locale/" + name); + getSetGlobalLocale(oldLocale); + } catch (e) { + // mark as not found to avoid repeating expensive file require call causing high CPU + // when trying to find en-US, en_US, en-us for every format call + locales[name] = null; // null means not found } - return locales[name]; + } + return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function getSetGlobalLocale(key, values) { - var data; - if (key) { - if (isUndefined(values)) { - data = getLocale(key); - } else { - data = defineLocale(key, values); - } - - if (data) { - // moment.duration._locale = moment._locale = data; - globalLocale = data; - } else { - if (typeof console !== 'undefined' && console.warn) { - //warn user if arguments are passed but the locale could not be set - console.warn( - 'Locale ' + key + ' not found. Did you forget to load it?' - ); - } - } + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } else { + data = defineLocale(key, values); } - return globalLocale._abbr; + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } else { + if (typeof console !== "undefined" && console.warn) { + //warn user if arguments are passed but the locale could not be set + console.warn( + "Locale " + key + " not found. Did you forget to load it?", + ); + } + } + } + + return globalLocale._abbr; } function defineLocale(name, config) { - if (config !== null) { - var locale, - parentConfig = baseConfig; - config.abbr = name; - if (locales[name] != null) { - deprecateSimple( - 'defineLocaleOverride', - 'use moment.updateLocale(localeName, config) to change ' + - 'an existing locale. moment.defineLocale(localeName, ' + - 'config) should only be used for creating a new locale ' + - 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.' - ); - parentConfig = locales[name]._config; - } else if (config.parentLocale != null) { - if (locales[config.parentLocale] != null) { - parentConfig = locales[config.parentLocale]._config; - } else { - locale = loadLocale(config.parentLocale); - if (locale != null) { - parentConfig = locale._config; - } else { - if (!localeFamilies[config.parentLocale]) { - localeFamilies[config.parentLocale] = []; - } - localeFamilies[config.parentLocale].push({ - name: name, - config: config, - }); - return null; - } - } + if (config !== null) { + var locale, + parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + deprecateSimple( + "defineLocaleOverride", + "use moment.updateLocale(localeName, config) to change " + + "an existing locale. moment.defineLocale(localeName, " + + "config) should only be used for creating a new locale " + + "See http://momentjs.com/guides/#/warnings/define-locale/ for more info.", + ); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + locale = loadLocale(config.parentLocale); + if (locale != null) { + parentConfig = locale._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config, + }); + return null; } - locales[name] = new Locale(mergeConfigs(parentConfig, config)); - - if (localeFamilies[name]) { - localeFamilies[name].forEach(function (x) { - defineLocale(x.name, x.config); - }); - } - - // backwards compat for now: also set the locale - // make sure we set the locale AFTER all child locales have been - // created, so we won't end up with the child locale set. - getSetGlobalLocale(name); - - return locales[name]; - } else { - // useful for testing - delete locales[name]; - return null; + } } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); + + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } + + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); + + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } } function updateLocale(name, config) { - if (config != null) { - var locale, - tmpLocale, - parentConfig = baseConfig; + if (config != null) { + var locale, + tmpLocale, + parentConfig = baseConfig; - if (locales[name] != null && locales[name].parentLocale != null) { - // Update existing child locale in-place to avoid memory-leaks - locales[name].set(mergeConfigs(locales[name]._config, config)); - } else { - // MERGE - tmpLocale = loadLocale(name); - if (tmpLocale != null) { - parentConfig = tmpLocale._config; - } - config = mergeConfigs(parentConfig, config); - if (tmpLocale == null) { - // updateLocale is called for creating a new locale - // Set abbr so it will have a name (getters return - // undefined otherwise). - config.abbr = name; - } - locale = new Locale(config); - locale.parentLocale = locales[name]; - locales[name] = locale; - } - - // backwards compat for now: also set the locale - getSetGlobalLocale(name); + if (locales[name] != null && locales[name].parentLocale != null) { + // Update existing child locale in-place to avoid memory-leaks + locales[name].set(mergeConfigs(locales[name]._config, config)); } else { - // pass null for config to unupdate, useful for tests - if (locales[name] != null) { - if (locales[name].parentLocale != null) { - locales[name] = locales[name].parentLocale; - if (name === getSetGlobalLocale()) { - getSetGlobalLocale(name); - } - } else if (locales[name] != null) { - delete locales[name]; - } - } + // MERGE + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config = mergeConfigs(parentConfig, config); + if (tmpLocale == null) { + // updateLocale is called for creating a new locale + // Set abbr so it will have a name (getters return + // undefined otherwise). + config.abbr = name; + } + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; } - return locales[name]; + + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + if (name === getSetGlobalLocale()) { + getSetGlobalLocale(name); + } + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; } // returns locale data function getLocale(key) { - var locale; + var locale; - if (key && key._locale && key._locale._abbr) { - key = key._locale._abbr; + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + + if (!key) { + return globalLocale; + } + + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; } + key = [key]; + } - if (!key) { - return globalLocale; - } - - if (!isArray(key)) { - //short-circuit everything else - locale = loadLocale(key); - if (locale) { - return locale; - } - key = [key]; - } - - return chooseLocale(key); + return chooseLocale(key); } function listLocales() { - return keys(locales); + return keys(locales); } function checkOverflow(m) { - var overflow, - a = m._a; + var overflow, + a = m._a; - if (a && getParsingFlags(m).overflow === -2) { - overflow = - a[MONTH] < 0 || a[MONTH] > 11 - ? MONTH - : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) - ? DATE - : a[HOUR] < 0 || - a[HOUR] > 24 || - (a[HOUR] === 24 && - (a[MINUTE] !== 0 || - a[SECOND] !== 0 || - a[MILLISECOND] !== 0)) - ? HOUR - : a[MINUTE] < 0 || a[MINUTE] > 59 - ? MINUTE - : a[SECOND] < 0 || a[SECOND] > 59 + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 + ? MONTH + : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) + ? DATE + : a[HOUR] < 0 || + a[HOUR] > 24 || + (a[HOUR] === 24 && + (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) + ? HOUR + : a[MINUTE] < 0 || a[MINUTE] > 59 + ? MINUTE + : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 - ? MILLISECOND - : -1; + ? MILLISECOND + : -1; - if ( - getParsingFlags(m)._overflowDayOfYear && - (overflow < YEAR || overflow > DATE) - ) { - overflow = DATE; - } - if (getParsingFlags(m)._overflowWeeks && overflow === -1) { - overflow = WEEK; - } - if (getParsingFlags(m)._overflowWeekday && overflow === -1) { - overflow = WEEKDAY; - } - - getParsingFlags(m).overflow = overflow; + if ( + getParsingFlags(m)._overflowDayOfYear && + (overflow < YEAR || overflow > DATE) + ) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; } - return m; + getParsingFlags(m).overflow = overflow; + } + + return m; } // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) - var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, - basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, - tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, - isoDates = [ - ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], - ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], - ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], - ['GGGG-[W]WW', /\d{4}-W\d\d/, false], - ['YYYY-DDD', /\d{4}-\d{3}/], - ['YYYY-MM', /\d{4}-\d\d/, false], - ['YYYYYYMMDD', /[+-]\d{10}/], - ['YYYYMMDD', /\d{8}/], - ['GGGG[W]WWE', /\d{4}W\d{3}/], - ['GGGG[W]WW', /\d{4}W\d{2}/, false], - ['YYYYDDD', /\d{7}/], - ['YYYYMM', /\d{6}/, false], - ['YYYY', /\d{4}/, false], - ], - // iso time formats and regexes - isoTimes = [ - ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], - ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], - ['HH:mm:ss', /\d\d:\d\d:\d\d/], - ['HH:mm', /\d\d:\d\d/], - ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], - ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], - ['HHmmss', /\d\d\d\d\d\d/], - ['HHmm', /\d\d\d\d/], - ['HH', /\d\d/], - ], - aspNetJsonRegex = /^\/?Date\((-?\d+)/i, - // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 - rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, - obsOffsets = { - UT: 0, - GMT: 0, - EDT: -4 * 60, - EST: -5 * 60, - CDT: -5 * 60, - CST: -6 * 60, - MDT: -6 * 60, - MST: -7 * 60, - PDT: -7 * 60, - PST: -8 * 60, - }; + var extendedIsoRegex = + /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, + basicIsoRegex = + /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, + tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, + isoDates = [ + ["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/], + ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/], + ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/], + ["GGGG-[W]WW", /\d{4}-W\d\d/, false], + ["YYYY-DDD", /\d{4}-\d{3}/], + ["YYYY-MM", /\d{4}-\d\d/, false], + ["YYYYYYMMDD", /[+-]\d{10}/], + ["YYYYMMDD", /\d{8}/], + ["GGGG[W]WWE", /\d{4}W\d{3}/], + ["GGGG[W]WW", /\d{4}W\d{2}/, false], + ["YYYYDDD", /\d{7}/], + ["YYYYMM", /\d{6}/, false], + ["YYYY", /\d{4}/, false], + ], + // iso time formats and regexes + isoTimes = [ + ["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/], + ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/], + ["HH:mm:ss", /\d\d:\d\d:\d\d/], + ["HH:mm", /\d\d:\d\d/], + ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/], + ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/], + ["HHmmss", /\d\d\d\d\d\d/], + ["HHmm", /\d\d\d\d/], + ["HH", /\d\d/], + ], + aspNetJsonRegex = /^\/?Date\((-?\d+)/i, + // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 + rfc2822 = + /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, + obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60, + }; // date from iso format function configFromISO(config) { - var i, - l, - string = config._i, - match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), - allowTime, - dateFormat, - timeFormat, - tzFormat; + var i, + l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, + dateFormat, + timeFormat, + tzFormat; - if (match) { - getParsingFlags(config).iso = true; + if (match) { + getParsingFlags(config).iso = true; - for (i = 0, l = isoDates.length; i < l; i++) { - if (isoDates[i][1].exec(match[1])) { - dateFormat = isoDates[i][0]; - allowTime = isoDates[i][2] !== false; - break; - } - } - if (dateFormat == null) { - config._isValid = false; - return; - } - if (match[3]) { - for (i = 0, l = isoTimes.length; i < l; i++) { - if (isoTimes[i][1].exec(match[3])) { - // match[2] should be 'T' or space - timeFormat = (match[2] || ' ') + isoTimes[i][0]; - break; - } - } - if (timeFormat == null) { - config._isValid = false; - return; - } - } - if (!allowTime && timeFormat != null) { - config._isValid = false; - return; - } - if (match[4]) { - if (tzRegex.exec(match[4])) { - tzFormat = 'Z'; - } else { - config._isValid = false; - return; - } - } - config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); - configFromStringAndFormat(config); - } else { - config._isValid = false; + for (i = 0, l = isoDates.length; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimes.length; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || " ") + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = "Z"; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || "") + (tzFormat || ""); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } } function extractFromRFC2822Strings( - yearStr, - monthStr, - dayStr, - hourStr, - minuteStr, - secondStr + yearStr, + monthStr, + dayStr, + hourStr, + minuteStr, + secondStr, ) { - var result = [ - untruncateYear(yearStr), - defaultLocaleMonthsShort.indexOf(monthStr), - parseInt(dayStr, 10), - parseInt(hourStr, 10), - parseInt(minuteStr, 10), - ]; + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10), + ]; - if (secondStr) { - result.push(parseInt(secondStr, 10)); - } + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } - return result; + return result; } function untruncateYear(yearStr) { - var year = parseInt(yearStr, 10); - if (year <= 49) { - return 2000 + year; - } else if (year <= 999) { - return 1900 + year; - } - return year; + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2000 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; } function preprocessRFC2822(s) { - // Remove comments and folding whitespace and replace multiple-spaces with a single space - return s - .replace(/\([^)]*\)|[\n\t]/g, ' ') - .replace(/(\s\s+)/g, ' ') - .replace(/^\s\s*/, '') - .replace(/\s\s*$/, ''); + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s + .replace(/\([^)]*\)|[\n\t]/g, " ") + .replace(/(\s\s+)/g, " ") + .replace(/^\s\s*/, "") + .replace(/\s\s*$/, ""); } function checkWeekday(weekdayStr, parsedInput, config) { - if (weekdayStr) { - // TODO: Replace the vanilla JS Date object with an independent day-of-week check. - var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), - weekdayActual = new Date( - parsedInput[0], - parsedInput[1], - parsedInput[2] - ).getDay(); - if (weekdayProvided !== weekdayActual) { - getParsingFlags(config).weekdayMismatch = true; - config._isValid = false; - return false; - } + if (weekdayStr) { + // TODO: Replace the vanilla JS Date object with an independent day-of-week check. + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), + weekdayActual = new Date( + parsedInput[0], + parsedInput[1], + parsedInput[2], + ).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return false; } - return true; + } + return true; } function calculateOffset(obsOffset, militaryOffset, numOffset) { - if (obsOffset) { - return obsOffsets[obsOffset]; - } else if (militaryOffset) { - // the only allowed military tz is Z - return 0; - } else { - var hm = parseInt(numOffset, 10), - m = hm % 100, - h = (hm - m) / 100; - return h * 60 + m; - } + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + // the only allowed military tz is Z + return 0; + } else { + var hm = parseInt(numOffset, 10), + m = hm % 100, + h = (hm - m) / 100; + return h * 60 + m; + } } // date and time from ref 2822 format function configFromRFC2822(config) { - var match = rfc2822.exec(preprocessRFC2822(config._i)), - parsedArray; - if (match) { - parsedArray = extractFromRFC2822Strings( - match[4], - match[3], - match[2], - match[5], - match[6], - match[7] - ); - if (!checkWeekday(match[1], parsedArray, config)) { - return; - } - - config._a = parsedArray; - config._tzm = calculateOffset(match[8], match[9], match[10]); - - config._d = createUTCDate.apply(null, config._a); - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - - getParsingFlags(config).rfc2822 = true; - } else { - config._isValid = false; + var match = rfc2822.exec(preprocessRFC2822(config._i)), + parsedArray; + if (match) { + parsedArray = extractFromRFC2822Strings( + match[4], + match[3], + match[2], + match[5], + match[6], + match[7], + ); + if (!checkWeekday(match[1], parsedArray, config)) { + return; } + + config._a = parsedArray; + config._tzm = calculateOffset(match[8], match[9], match[10]); + + config._d = createUTCDate.apply(null, config._a); + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } } // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict function configFromString(config) { - var matched = aspNetJsonRegex.exec(config._i); - if (matched !== null) { - config._d = new Date(+matched[1]); - return; - } + var matched = aspNetJsonRegex.exec(config._i); + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } - configFromISO(config); - if (config._isValid === false) { - delete config._isValid; - } else { - return; - } + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } - configFromRFC2822(config); - if (config._isValid === false) { - delete config._isValid; - } else { - return; - } + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } - if (config._strict) { - config._isValid = false; - } else { - // Final attempt, use Input Fallback - hooks.createFromInputFallback(config); - } + if (config._strict) { + config._isValid = false; + } else { + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); + } } hooks.createFromInputFallback = deprecate( - 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + - 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + - 'discouraged and will be removed in an upcoming major release. Please refer to ' + - 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', - function (config) { - config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); - } + "value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), " + + "which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are " + + "discouraged and will be removed in an upcoming major release. Please refer to " + + "http://momentjs.com/guides/#/warnings/js-date/ for more info.", + function (config) { + config._d = new Date(config._i + (config._useUTC ? " UTC" : "")); + }, ); // Pick the first defined of two or three arguments. function defaults(a, b, c) { - if (a != null) { - return a; - } - if (b != null) { - return b; - } - return c; + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; } function currentDateArray(config) { - // hooks is actually the exported moment object - var nowValue = new Date(hooks.now()); - if (config._useUTC) { - return [ - nowValue.getUTCFullYear(), - nowValue.getUTCMonth(), - nowValue.getUTCDate(), - ]; - } - return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [ + nowValue.getUTCFullYear(), + nowValue.getUTCMonth(), + nowValue.getUTCDate(), + ]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } // convert an array to a date. @@ -2576,153 +2562,153 @@ // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray(config) { - var i, - date, - input = [], - currentDate, - expectedWeekday, - yearToUse; + var i, + date, + input = [], + currentDate, + expectedWeekday, + yearToUse; - if (config._d) { - return; - } + if (config._d) { + return; + } - currentDate = currentDateArray(config); + currentDate = currentDateArray(config); - //compute day of the year from weeks and weekdays - if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { - dayOfYearFromWeekInfo(config); - } + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } - //if the day of the year is set, figure out what it is - if (config._dayOfYear != null) { - yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); - if ( - config._dayOfYear > daysInYear(yearToUse) || - config._dayOfYear === 0 - ) { - getParsingFlags(config)._overflowDayOfYear = true; - } - - date = createUTCDate(yearToUse, 0, config._dayOfYear); - config._a[MONTH] = date.getUTCMonth(); - config._a[DATE] = date.getUTCDate(); - } - - // Default to current date. - // * if no year, month, day of month are given, default to today - // * if day of month is given, default month and year - // * if month is given, default only year - // * if year is given, don't default anything - for (i = 0; i < 3 && config._a[i] == null; ++i) { - config._a[i] = input[i] = currentDate[i]; - } - - // Zero out whatever was not defaulted, including time - for (; i < 7; i++) { - config._a[i] = input[i] = - config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i]; - } - - // Check for 24:00:00.000 if ( - config._a[HOUR] === 24 && - config._a[MINUTE] === 0 && - config._a[SECOND] === 0 && - config._a[MILLISECOND] === 0 + config._dayOfYear > daysInYear(yearToUse) || + config._dayOfYear === 0 ) { - config._nextDay = true; - config._a[HOUR] = 0; + getParsingFlags(config)._overflowDayOfYear = true; } - config._d = (config._useUTC ? createUTCDate : createDate).apply( - null, - input - ); - expectedWeekday = config._useUTC - ? config._d.getUTCDay() - : config._d.getDay(); + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } - // Apply timezone offset from input. The actual utcOffset can be changed - // with parseZone. - if (config._tzm != null) { - config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); - } + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } - if (config._nextDay) { - config._a[HOUR] = 24; - } + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = + config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i]; + } - // check for mismatching day of week - if ( - config._w && - typeof config._w.d !== 'undefined' && - config._w.d !== expectedWeekday - ) { - getParsingFlags(config).weekdayMismatch = true; - } + // Check for 24:00:00.000 + if ( + config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0 + ) { + config._nextDay = true; + config._a[HOUR] = 0; + } + + config._d = (config._useUTC ? createUTCDate : createDate).apply( + null, + input, + ); + expectedWeekday = config._useUTC + ? config._d.getUTCDay() + : config._d.getDay(); + + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } + + if (config._nextDay) { + config._a[HOUR] = 24; + } + + // check for mismatching day of week + if ( + config._w && + typeof config._w.d !== "undefined" && + config._w.d !== expectedWeekday + ) { + getParsingFlags(config).weekdayMismatch = true; + } } function dayOfYearFromWeekInfo(config) { - var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; - w = config._w; - if (w.GG != null || w.W != null || w.E != null) { - dow = 1; - doy = 4; + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; - // TODO: We need to take the current isoWeekYear, but that depends on - // how we interpret now (local, utc, fixed offset). So create - // a now version of current config (take local/utc/offset flags, and - // create now). - weekYear = defaults( - w.GG, - config._a[YEAR], - weekOfYear(createLocal(), 1, 4).year - ); - week = defaults(w.W, 1); - weekday = defaults(w.E, 1); - if (weekday < 1 || weekday > 7) { - weekdayOverflow = true; - } - } else { - dow = config._locale._week.dow; - doy = config._locale._week.doy; - - curWeek = weekOfYear(createLocal(), dow, doy); - - weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); - - // Default to current week. - week = defaults(w.w, curWeek.week); - - if (w.d != null) { - // weekday -- low day numbers are considered next week - weekday = w.d; - if (weekday < 0 || weekday > 6) { - weekdayOverflow = true; - } - } else if (w.e != null) { - // local weekday -- counting starts from beginning of week - weekday = w.e + dow; - if (w.e < 0 || w.e > 6) { - weekdayOverflow = true; - } - } else { - // default to beginning of week - weekday = dow; - } + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults( + w.GG, + config._a[YEAR], + weekOfYear(createLocal(), 1, 4).year, + ); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; } - if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { - getParsingFlags(config)._overflowWeeks = true; - } else if (weekdayOverflow != null) { - getParsingFlags(config)._overflowWeekday = true; + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; + + curWeek = weekOfYear(createLocal(), dow, doy); + + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + + // Default to current week. + week = defaults(w.w, curWeek.week); + + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from beginning of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } } else { - temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); - config._a[YEAR] = temp.year; - config._dayOfYear = temp.dayOfYear; + // default to beginning of week + weekday = dow; } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } } // constant that refers to the ISO standard @@ -2733,321 +2719,319 @@ // date from string and format string function configFromStringAndFormat(config) { - // TODO: Move this to another part of the creation flow to prevent circular deps - if (config._f === hooks.ISO_8601) { - configFromISO(config); - return; + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; + + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = "" + config._i, + i, + parsedInput, + tokens, + token, + skipped, + stringLength = string.length, + totalParsedInputLength = 0, + era; + + tokens = + expandFormat(config._f, config._locale).match(formattingTokens) || []; + + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || + [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice(string.indexOf(parsedInput) + parsedInput.length); + totalParsedInputLength += parsedInput.length; } - if (config._f === hooks.RFC_2822) { - configFromRFC2822(config); - return; + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); } - config._a = []; - getParsingFlags(config).empty = true; + } - // This array is used to make a Date, either with `new Date` or `Date.UTC` - var string = '' + config._i, - i, - parsedInput, - tokens, - token, - skipped, - stringLength = string.length, - totalParsedInputLength = 0, - era; + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = + stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } - tokens = - expandFormat(config._f, config._locale).match(formattingTokens) || []; + // clear _12h flag if hour is <= 12 + if ( + config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0 + ) { + getParsingFlags(config).bigHour = undefined; + } - for (i = 0; i < tokens.length; i++) { - token = tokens[i]; - parsedInput = (string.match(getParseRegexForToken(token, config)) || - [])[0]; - if (parsedInput) { - skipped = string.substr(0, string.indexOf(parsedInput)); - if (skipped.length > 0) { - getParsingFlags(config).unusedInput.push(skipped); - } - string = string.slice( - string.indexOf(parsedInput) + parsedInput.length - ); - totalParsedInputLength += parsedInput.length; - } - // don't parse if it's not a known token - if (formatTokenFunctions[token]) { - if (parsedInput) { - getParsingFlags(config).empty = false; - } else { - getParsingFlags(config).unusedTokens.push(token); - } - addTimeToArrayFromToken(token, parsedInput, config); - } else if (config._strict && !parsedInput) { - getParsingFlags(config).unusedTokens.push(token); - } - } + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap( + config._locale, + config._a[HOUR], + config._meridiem, + ); - // add remaining unparsed input length to the string - getParsingFlags(config).charsLeftOver = - stringLength - totalParsedInputLength; - if (string.length > 0) { - getParsingFlags(config).unusedInput.push(string); - } + // handle era + era = getParsingFlags(config).era; + if (era !== null) { + config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); + } - // clear _12h flag if hour is <= 12 - if ( - config._a[HOUR] <= 12 && - getParsingFlags(config).bigHour === true && - config._a[HOUR] > 0 - ) { - getParsingFlags(config).bigHour = undefined; - } - - getParsingFlags(config).parsedDateParts = config._a.slice(0); - getParsingFlags(config).meridiem = config._meridiem; - // handle meridiem - config._a[HOUR] = meridiemFixWrap( - config._locale, - config._a[HOUR], - config._meridiem - ); - - // handle era - era = getParsingFlags(config).era; - if (era !== null) { - config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); - } - - configFromArray(config); - checkOverflow(config); + configFromArray(config); + checkOverflow(config); } function meridiemFixWrap(locale, hour, meridiem) { - var isPm; + var isPm; - if (meridiem == null) { - // nothing to do - return hour; + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; } - if (locale.meridiemHour != null) { - return locale.meridiemHour(hour, meridiem); - } else if (locale.isPM != null) { - // Fallback - isPm = locale.isPM(meridiem); - if (isPm && hour < 12) { - hour += 12; - } - if (!isPm && hour === 12) { - hour = 0; - } - return hour; - } else { - // this is not supposed to happen - return hour; + if (!isPm && hour === 12) { + hour = 0; } + return hour; + } else { + // this is not supposed to happen + return hour; + } } // date from string and array of format strings function configFromStringAndArray(config) { - var tempConfig, - bestMoment, - scoreToBeat, - i, - currentScore, - validFormatFound, - bestFormatIsValid = false; + var tempConfig, + bestMoment, + scoreToBeat, + i, + currentScore, + validFormatFound, + bestFormatIsValid = false; - if (config._f.length === 0) { - getParsingFlags(config).invalidFormat = true; - config._d = new Date(NaN); - return; + if (config._f.length === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } + + for (i = 0; i < config._f.length; i++) { + currentScore = 0; + validFormatFound = false; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); + + if (isValid(tempConfig)) { + validFormatFound = true; } - for (i = 0; i < config._f.length; i++) { - currentScore = 0; - validFormatFound = false; - tempConfig = copyConfig({}, config); - if (config._useUTC != null) { - tempConfig._useUTC = config._useUTC; - } - tempConfig._f = config._f[i]; - configFromStringAndFormat(tempConfig); + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; - if (isValid(tempConfig)) { - validFormatFound = true; - } + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; - // if there is any input that was not parsed add a penalty for that format - currentScore += getParsingFlags(tempConfig).charsLeftOver; + getParsingFlags(tempConfig).score = currentScore; - //or tokens - currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; - - getParsingFlags(tempConfig).score = currentScore; - - if (!bestFormatIsValid) { - if ( - scoreToBeat == null || - currentScore < scoreToBeat || - validFormatFound - ) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - if (validFormatFound) { - bestFormatIsValid = true; - } - } - } else { - if (currentScore < scoreToBeat) { - scoreToBeat = currentScore; - bestMoment = tempConfig; - } + if (!bestFormatIsValid) { + if ( + scoreToBeat == null || + currentScore < scoreToBeat || + validFormatFound + ) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + if (validFormatFound) { + bestFormatIsValid = true; } + } + } else { + if (currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } } + } - extend(config, bestMoment || tempConfig); + extend(config, bestMoment || tempConfig); } function configFromObject(config) { - if (config._d) { - return; - } + if (config._d) { + return; + } - var i = normalizeObjectUnits(config._i), - dayOrDate = i.day === undefined ? i.date : i.day; - config._a = map( - [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], - function (obj) { - return obj && parseInt(obj, 10); - } - ); + var i = normalizeObjectUnits(config._i), + dayOrDate = i.day === undefined ? i.date : i.day; + config._a = map( + [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], + function (obj) { + return obj && parseInt(obj, 10); + }, + ); - configFromArray(config); + configFromArray(config); } function createFromConfig(config) { - var res = new Moment(checkOverflow(prepareConfig(config))); - if (res._nextDay) { - // Adding is smart enough around DST - res.add(1, 'd'); - res._nextDay = undefined; - } + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, "d"); + res._nextDay = undefined; + } - return res; + return res; } function prepareConfig(config) { - var input = config._i, - format = config._f; + var input = config._i, + format = config._f; - config._locale = config._locale || getLocale(config._l); + config._locale = config._locale || getLocale(config._l); - if (input === null || (format === undefined && input === '')) { - return createInvalid({ nullInput: true }); - } + if (input === null || (format === undefined && input === "")) { + return createInvalid({ nullInput: true }); + } - if (typeof input === 'string') { - config._i = input = config._locale.preparse(input); - } + if (typeof input === "string") { + config._i = input = config._locale.preparse(input); + } - if (isMoment(input)) { - return new Moment(checkOverflow(input)); - } else if (isDate(input)) { - config._d = input; - } else if (isArray(format)) { - configFromStringAndArray(config); - } else if (format) { - configFromStringAndFormat(config); - } else { - configFromInput(config); - } + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } - if (!isValid(config)) { - config._d = null; - } + if (!isValid(config)) { + config._d = null; + } - return config; + return config; } function configFromInput(config) { - var input = config._i; - if (isUndefined(input)) { - config._d = new Date(hooks.now()); - } else if (isDate(input)) { - config._d = new Date(input.valueOf()); - } else if (typeof input === 'string') { - configFromString(config); - } else if (isArray(input)) { - config._a = map(input.slice(0), function (obj) { - return parseInt(obj, 10); - }); - configFromArray(config); - } else if (isObject(input)) { - configFromObject(config); - } else if (isNumber(input)) { - // from milliseconds - config._d = new Date(input); - } else { - hooks.createFromInputFallback(config); - } + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === "string") { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } } function createLocalOrUTC(input, format, locale, strict, isUTC) { - var c = {}; + var c = {}; - if (format === true || format === false) { - strict = format; - format = undefined; - } + if (format === true || format === false) { + strict = format; + format = undefined; + } - if (locale === true || locale === false) { - strict = locale; - locale = undefined; - } + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } - if ( - (isObject(input) && isObjectEmpty(input)) || - (isArray(input) && input.length === 0) - ) { - input = undefined; - } - // object construction must be done this way. - // https://github.com/moment/moment/issues/1423 - c._isAMomentObject = true; - c._useUTC = c._isUTC = isUTC; - c._l = locale; - c._i = input; - c._f = format; - c._strict = strict; + if ( + (isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0) + ) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; - return createFromConfig(c); + return createFromConfig(c); } function createLocal(input, format, locale, strict) { - return createLocalOrUTC(input, format, locale, strict, false); + return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( - 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other < this ? this : other; - } else { - return createInvalid(); - } - } - ), - prototypeMax = deprecate( - 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', - function () { - var other = createLocal.apply(null, arguments); - if (this.isValid() && other.isValid()) { - return other > this ? this : other; - } else { - return createInvalid(); - } - } - ); + "moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + }, + ), + prototypeMax = deprecate( + "moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + }, + ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. @@ -3055,182 +3039,182 @@ // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { - var res, i; - if (moments.length === 1 && isArray(moments[0])) { - moments = moments[0]; + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; } - if (!moments.length) { - return createLocal(); - } - res = moments[0]; - for (i = 1; i < moments.length; ++i) { - if (!moments[i].isValid() || moments[i][fn](res)) { - res = moments[i]; - } - } - return res; + } + return res; } // TODO: Use [].sort instead? function min() { - var args = [].slice.call(arguments, 0); + var args = [].slice.call(arguments, 0); - return pickBy('isBefore', args); + return pickBy("isBefore", args); } function max() { - var args = [].slice.call(arguments, 0); + var args = [].slice.call(arguments, 0); - return pickBy('isAfter', args); + return pickBy("isAfter", args); } var now = function () { - return Date.now ? Date.now() : +new Date(); + return Date.now ? Date.now() : +new Date(); }; var ordering = [ - 'year', - 'quarter', - 'month', - 'week', - 'day', - 'hour', - 'minute', - 'second', - 'millisecond', + "year", + "quarter", + "month", + "week", + "day", + "hour", + "minute", + "second", + "millisecond", ]; function isDurationValid(m) { - var key, - unitHasDecimal = false, - i; - for (key in m) { - if ( - hasOwnProp(m, key) && - !( - indexOf.call(ordering, key) !== -1 && - (m[key] == null || !isNaN(m[key])) - ) - ) { - return false; - } + var key, + unitHasDecimal = false, + i; + for (key in m) { + if ( + hasOwnProp(m, key) && + !( + indexOf.call(ordering, key) !== -1 && + (m[key] == null || !isNaN(m[key])) + ) + ) { + return false; } + } - for (i = 0; i < ordering.length; ++i) { - if (m[ordering[i]]) { - if (unitHasDecimal) { - return false; // only allow non-integers for smallest unit - } - if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { - unitHasDecimal = true; - } - } + for (i = 0; i < ordering.length; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } } + } - return true; + return true; } function isValid$1() { - return this._isValid; + return this._isValid; } function createInvalid$1() { - return createDuration(NaN); + return createDuration(NaN); } function Duration(duration) { - var normalizedInput = normalizeObjectUnits(duration), - years = normalizedInput.year || 0, - quarters = normalizedInput.quarter || 0, - months = normalizedInput.month || 0, - weeks = normalizedInput.week || normalizedInput.isoWeek || 0, - days = normalizedInput.day || 0, - hours = normalizedInput.hour || 0, - minutes = normalizedInput.minute || 0, - seconds = normalizedInput.second || 0, - milliseconds = normalizedInput.millisecond || 0; + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || normalizedInput.isoWeek || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; - this._isValid = isDurationValid(normalizedInput); + this._isValid = isDurationValid(normalizedInput); - // representation for dateAddRemove - this._milliseconds = - +milliseconds + - seconds * 1e3 + // 1000 - minutes * 6e4 + // 1000 * 60 - hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 - // Because of dateAddRemove treats 24 hours as different from a - // day when working around DST, we need to store them separately - this._days = +days + weeks * 7; - // It is impossible to translate months into days without knowing - // which months you are are talking about, so we have to store - // it separately. - this._months = +months + quarters * 3 + years * 12; + // representation for dateAddRemove + this._milliseconds = + +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + weeks * 7; + // It is impossible to translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + quarters * 3 + years * 12; - this._data = {}; + this._data = {}; - this._locale = getLocale(); + this._locale = getLocale(); - this._bubble(); + this._bubble(); } function isDuration(obj) { - return obj instanceof Duration; + return obj instanceof Duration; } function absRound(number) { - if (number < 0) { - return Math.round(-1 * number) * -1; - } else { - return Math.round(number); - } + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { - var len = Math.min(array1.length, array2.length), - lengthDiff = Math.abs(array1.length - array2.length), - diffs = 0, - i; - for (i = 0; i < len; i++) { - if ( - (dontConvert && array1[i] !== array2[i]) || - (!dontConvert && toInt(array1[i]) !== toInt(array2[i])) - ) { - diffs++; - } + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ( + (dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i])) + ) { + diffs++; } - return diffs + lengthDiff; + } + return diffs + lengthDiff; } // FORMATTING function offset(token, separator) { - addFormatToken(token, 0, 0, function () { - var offset = this.utcOffset(), - sign = '+'; - if (offset < 0) { - offset = -offset; - sign = '-'; - } - return ( - sign + - zeroFill(~~(offset / 60), 2) + - separator + - zeroFill(~~offset % 60, 2) - ); - }); + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(), + sign = "+"; + if (offset < 0) { + offset = -offset; + sign = "-"; + } + return ( + sign + + zeroFill(~~(offset / 60), 2) + + separator + + zeroFill(~~offset % 60, 2) + ); + }); } - offset('Z', ':'); - offset('ZZ', ''); + offset("Z", ":"); + offset("ZZ", ""); // PARSING - addRegexToken('Z', matchShortOffset); - addRegexToken('ZZ', matchShortOffset); - addParseToken(['Z', 'ZZ'], function (input, array, config) { - config._useUTC = true; - config._tzm = offsetFromString(matchShortOffset, input); + addRegexToken("Z", matchShortOffset); + addRegexToken("ZZ", matchShortOffset); + addParseToken(["Z", "ZZ"], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); }); // HELPERS @@ -3241,44 +3225,44 @@ var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string) { - var matches = (string || '').match(matcher), - chunk, - parts, - minutes; + var matches = (string || "").match(matcher), + chunk, + parts, + minutes; - if (matches === null) { - return null; - } + if (matches === null) { + return null; + } - chunk = matches[matches.length - 1] || []; - parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; - minutes = +(parts[1] * 60) + toInt(parts[2]); + chunk = matches[matches.length - 1] || []; + parts = (chunk + "").match(chunkOffset) || ["-", 0, 0]; + minutes = +(parts[1] * 60) + toInt(parts[2]); - return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; + return minutes === 0 ? 0 : parts[0] === "+" ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { - var res, diff; - if (model._isUTC) { - res = model.clone(); - diff = - (isMoment(input) || isDate(input) - ? input.valueOf() - : createLocal(input).valueOf()) - res.valueOf(); - // Use low-level api, because this fn is low-level api. - res._d.setTime(res._d.valueOf() + diff); - hooks.updateOffset(res, false); - return res; - } else { - return createLocal(input).local(); - } + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = + (isMoment(input) || isDate(input) + ? input.valueOf() + : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } } function getDateOffset(m) { - // On Firefox.24 Date#getTimezoneOffset returns a floating point. - // https://github.com/moment/moment/pull/1871 - return -Math.round(m._d.getTimezoneOffset()); + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset()); } // HOOKS @@ -3300,643 +3284,637 @@ // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset(input, keepLocalTime, keepMinutes) { - var offset = this._offset || 0, - localAdjust; - if (!this.isValid()) { - return input != null ? this : NaN; - } - if (input != null) { - if (typeof input === 'string') { - input = offsetFromString(matchShortOffset, input); - if (input === null) { - return this; - } - } else if (Math.abs(input) < 16 && !keepMinutes) { - input = input * 60; - } - if (!this._isUTC && keepLocalTime) { - localAdjust = getDateOffset(this); - } - this._offset = input; - this._isUTC = true; - if (localAdjust != null) { - this.add(localAdjust, 'm'); - } - if (offset !== input) { - if (!keepLocalTime || this._changeInProgress) { - addSubtract( - this, - createDuration(input - offset, 'm'), - 1, - false - ); - } else if (!this._changeInProgress) { - this._changeInProgress = true; - hooks.updateOffset(this, true); - this._changeInProgress = null; - } - } + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === "string") { + input = offsetFromString(matchShortOffset, input); + if (input === null) { return this; - } else { - return this._isUTC ? offset : getDateOffset(this); + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, "m"); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract(this, createDuration(input - offset, "m"), 1, false); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); + } } function getSetZone(input, keepLocalTime) { - if (input != null) { - if (typeof input !== 'string') { - input = -input; - } - - this.utcOffset(input, keepLocalTime); - - return this; - } else { - return -this.utcOffset(); + if (input != null) { + if (typeof input !== "string") { + input = -input; } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); + } } function setOffsetToUTC(keepLocalTime) { - return this.utcOffset(0, keepLocalTime); + return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal(keepLocalTime) { - if (this._isUTC) { - this.utcOffset(0, keepLocalTime); - this._isUTC = false; + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; - if (keepLocalTime) { - this.subtract(getDateOffset(this), 'm'); - } + if (keepLocalTime) { + this.subtract(getDateOffset(this), "m"); } - return this; + } + return this; } function setOffsetToParsedOffset() { - if (this._tzm != null) { - this.utcOffset(this._tzm, false, true); - } else if (typeof this._i === 'string') { - var tZone = offsetFromString(matchOffset, this._i); - if (tZone != null) { - this.utcOffset(tZone); - } else { - this.utcOffset(0, true); - } + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === "string") { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } else { + this.utcOffset(0, true); } - return this; + } + return this; } function hasAlignedHourOffset(input) { - if (!this.isValid()) { - return false; - } - input = input ? createLocal(input).utcOffset() : 0; + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; - return (this.utcOffset() - input) % 60 === 0; + return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime() { - return ( - this.utcOffset() > this.clone().month(0).utcOffset() || - this.utcOffset() > this.clone().month(5).utcOffset() - ); + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); } function isDaylightSavingTimeShifted() { - if (!isUndefined(this._isDSTShifted)) { - return this._isDSTShifted; - } - - var c = {}, - other; - - copyConfig(c, this); - c = prepareConfig(c); - - if (c._a) { - other = c._isUTC ? createUTC(c._a) : createLocal(c._a); - this._isDSTShifted = - this.isValid() && compareArrays(c._a, other.toArray()) > 0; - } else { - this._isDSTShifted = false; - } - + if (!isUndefined(this._isDSTShifted)) { return this._isDSTShifted; + } + + var c = {}, + other; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = + this.isValid() && compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; } function isLocal() { - return this.isValid() ? !this._isUTC : false; + return this.isValid() ? !this._isUTC : false; } function isUtcOffset() { - return this.isValid() ? this._isUTC : false; + return this.isValid() ? this._isUTC : false; } function isUtc() { - return this.isValid() ? this._isUTC && this._offset === 0 : false; + return this.isValid() ? this._isUTC && this._offset === 0 : false; } // ASP.NET json date format regex var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, - // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html - // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere - // and further modified to allow for strings containing both week and day - isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + // and further modified to allow for strings containing both week and day + isoRegex = + /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; function createDuration(input, key) { - var duration = input, - // matching against regexp is expensive, do it on demand - match = null, - sign, - ret, - diffRes; + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; - if (isDuration(input)) { - duration = { - ms: input._milliseconds, - d: input._days, - M: input._months, - }; - } else if (isNumber(input) || !isNaN(+input)) { - duration = {}; - if (key) { - duration[key] = +input; - } else { - duration.milliseconds = +input; - } - } else if ((match = aspNetRegex.exec(input))) { - sign = match[1] === '-' ? -1 : 1; - duration = { - y: 0, - d: toInt(match[DATE]) * sign, - h: toInt(match[HOUR]) * sign, - m: toInt(match[MINUTE]) * sign, - s: toInt(match[SECOND]) * sign, - ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match - }; - } else if ((match = isoRegex.exec(input))) { - sign = match[1] === '-' ? -1 : 1; - duration = { - y: parseIso(match[2], sign), - M: parseIso(match[3], sign), - w: parseIso(match[4], sign), - d: parseIso(match[5], sign), - h: parseIso(match[6], sign), - m: parseIso(match[7], sign), - s: parseIso(match[8], sign), - }; - } else if (duration == null) { - // checks for null or undefined - duration = {}; - } else if ( - typeof duration === 'object' && - ('from' in duration || 'to' in duration) - ) { - diffRes = momentsDifference( - createLocal(duration.from), - createLocal(duration.to) - ); - - duration = {}; - duration.ms = diffRes.milliseconds; - duration.M = diffRes.months; + if (isDuration(input)) { + duration = { + ms: input._milliseconds, + d: input._days, + M: input._months, + }; + } else if (isNumber(input) || !isNaN(+input)) { + duration = {}; + if (key) { + duration[key] = +input; + } else { + duration.milliseconds = +input; } + } else if ((match = aspNetRegex.exec(input))) { + sign = match[1] === "-" ? -1 : 1; + duration = { + y: 0, + d: toInt(match[DATE]) * sign, + h: toInt(match[HOUR]) * sign, + m: toInt(match[MINUTE]) * sign, + s: toInt(match[SECOND]) * sign, + ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match + }; + } else if ((match = isoRegex.exec(input))) { + sign = match[1] === "-" ? -1 : 1; + duration = { + y: parseIso(match[2], sign), + M: parseIso(match[3], sign), + w: parseIso(match[4], sign), + d: parseIso(match[5], sign), + h: parseIso(match[6], sign), + m: parseIso(match[7], sign), + s: parseIso(match[8], sign), + }; + } else if (duration == null) { + // checks for null or undefined + duration = {}; + } else if ( + typeof duration === "object" && + ("from" in duration || "to" in duration) + ) { + diffRes = momentsDifference( + createLocal(duration.from), + createLocal(duration.to), + ); - ret = new Duration(duration); + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } - if (isDuration(input) && hasOwnProp(input, '_locale')) { - ret._locale = input._locale; - } + ret = new Duration(duration); - if (isDuration(input) && hasOwnProp(input, '_isValid')) { - ret._isValid = input._isValid; - } + if (isDuration(input) && hasOwnProp(input, "_locale")) { + ret._locale = input._locale; + } - return ret; + if (isDuration(input) && hasOwnProp(input, "_isValid")) { + ret._isValid = input._isValid; + } + + return ret; } createDuration.fn = Duration.prototype; createDuration.invalid = createInvalid$1; function parseIso(inp, sign) { - // We'd normally use ~~inp for this, but unfortunately it also - // converts floats to ints. - // inp may be undefined, so careful calling replace on it. - var res = inp && parseFloat(inp.replace(',', '.')); - // apply sign while we're at it - return (isNaN(res) ? 0 : res) * sign; + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(",", ".")); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { - var res = {}; + var res = {}; - res.months = - other.month() - base.month() + (other.year() - base.year()) * 12; - if (base.clone().add(res.months, 'M').isAfter(other)) { - --res.months; - } + res.months = + other.month() - base.month() + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, "M").isAfter(other)) { + --res.months; + } - res.milliseconds = +other - +base.clone().add(res.months, 'M'); + res.milliseconds = +other - +base.clone().add(res.months, "M"); - return res; + return res; } function momentsDifference(base, other) { - var res; - if (!(base.isValid() && other.isValid())) { - return { milliseconds: 0, months: 0 }; - } + var res; + if (!(base.isValid() && other.isValid())) { + return { milliseconds: 0, months: 0 }; + } - other = cloneWithOffset(other, base); - if (base.isBefore(other)) { - res = positiveMomentsDifference(base, other); - } else { - res = positiveMomentsDifference(other, base); - res.milliseconds = -res.milliseconds; - res.months = -res.months; - } + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } - return res; + return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { - return function (val, period) { - var dur, tmp; - //invert the arguments, but complain about it - if (period !== null && !isNaN(+period)) { - deprecateSimple( - name, - 'moment().' + - name + - '(period, number) is deprecated. Please use moment().' + - name + - '(number, period). ' + - 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.' - ); - tmp = val; - val = period; - period = tmp; - } + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple( + name, + "moment()." + + name + + "(period, number) is deprecated. Please use moment()." + + name + + "(number, period). " + + "See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.", + ); + tmp = val; + val = period; + period = tmp; + } - dur = createDuration(val, period); - addSubtract(this, dur, direction); - return this; - }; + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; } function addSubtract(mom, duration, isAdding, updateOffset) { - var milliseconds = duration._milliseconds, - days = absRound(duration._days), - months = absRound(duration._months); + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); - if (!mom.isValid()) { - // No op - return; - } + if (!mom.isValid()) { + // No op + return; + } - updateOffset = updateOffset == null ? true : updateOffset; + updateOffset = updateOffset == null ? true : updateOffset; - if (months) { - setMonth(mom, get(mom, 'Month') + months * isAdding); - } - if (days) { - set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); - } - if (milliseconds) { - mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); - } - if (updateOffset) { - hooks.updateOffset(mom, days || months); - } + if (months) { + setMonth(mom, get(mom, "Month") + months * isAdding); + } + if (days) { + set$1(mom, "Date", get(mom, "Date") + days * isAdding); + } + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } } - var add = createAdder(1, 'add'), - subtract = createAdder(-1, 'subtract'); + var add = createAdder(1, "add"), + subtract = createAdder(-1, "subtract"); function isString(input) { - return typeof input === 'string' || input instanceof String; + return typeof input === "string" || input instanceof String; } // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined function isMomentInput(input) { - return ( - isMoment(input) || - isDate(input) || - isString(input) || - isNumber(input) || - isNumberOrStringArray(input) || - isMomentInputObject(input) || - input === null || - input === undefined - ); + return ( + isMoment(input) || + isDate(input) || + isString(input) || + isNumber(input) || + isNumberOrStringArray(input) || + isMomentInputObject(input) || + input === null || + input === undefined + ); } function isMomentInputObject(input) { - var objectTest = isObject(input) && !isObjectEmpty(input), - propertyTest = false, - properties = [ - 'years', - 'year', - 'y', - 'months', - 'month', - 'M', - 'days', - 'day', - 'd', - 'dates', - 'date', - 'D', - 'hours', - 'hour', - 'h', - 'minutes', - 'minute', - 'm', - 'seconds', - 'second', - 's', - 'milliseconds', - 'millisecond', - 'ms', - ], - i, - property; + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + "years", + "year", + "y", + "months", + "month", + "M", + "days", + "day", + "d", + "dates", + "date", + "D", + "hours", + "hour", + "h", + "minutes", + "minute", + "m", + "seconds", + "second", + "s", + "milliseconds", + "millisecond", + "ms", + ], + i, + property; - for (i = 0; i < properties.length; i += 1) { - property = properties[i]; - propertyTest = propertyTest || hasOwnProp(input, property); - } + for (i = 0; i < properties.length; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } - return objectTest && propertyTest; + return objectTest && propertyTest; } function isNumberOrStringArray(input) { - var arrayTest = isArray(input), - dataTypeTest = false; - if (arrayTest) { - dataTypeTest = - input.filter(function (item) { - return !isNumber(item) && isString(input); - }).length === 0; - } - return arrayTest && dataTypeTest; + var arrayTest = isArray(input), + dataTypeTest = false; + if (arrayTest) { + dataTypeTest = + input.filter(function (item) { + return !isNumber(item) && isString(input); + }).length === 0; + } + return arrayTest && dataTypeTest; } function isCalendarSpec(input) { - var objectTest = isObject(input) && !isObjectEmpty(input), - propertyTest = false, - properties = [ - 'sameDay', - 'nextDay', - 'lastDay', - 'nextWeek', - 'lastWeek', - 'sameElse', - ], - i, - property; + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + "sameDay", + "nextDay", + "lastDay", + "nextWeek", + "lastWeek", + "sameElse", + ], + i, + property; - for (i = 0; i < properties.length; i += 1) { - property = properties[i]; - propertyTest = propertyTest || hasOwnProp(input, property); - } + for (i = 0; i < properties.length; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } - return objectTest && propertyTest; + return objectTest && propertyTest; } function getCalendarFormat(myMoment, now) { - var diff = myMoment.diff(now, 'days', true); - return diff < -6 - ? 'sameElse' - : diff < -1 - ? 'lastWeek' - : diff < 0 - ? 'lastDay' + var diff = myMoment.diff(now, "days", true); + return diff < -6 + ? "sameElse" + : diff < -1 + ? "lastWeek" + : diff < 0 + ? "lastDay" : diff < 1 - ? 'sameDay' - : diff < 2 - ? 'nextDay' - : diff < 7 - ? 'nextWeek' - : 'sameElse'; + ? "sameDay" + : diff < 2 + ? "nextDay" + : diff < 7 + ? "nextWeek" + : "sameElse"; } function calendar$1(time, formats) { - // Support for single parameter, formats only overload to the calendar function - if (arguments.length === 1) { - if (!arguments[0]) { - time = undefined; - formats = undefined; - } else if (isMomentInput(arguments[0])) { - time = arguments[0]; - formats = undefined; - } else if (isCalendarSpec(arguments[0])) { - formats = arguments[0]; - time = undefined; - } + // Support for single parameter, formats only overload to the calendar function + if (arguments.length === 1) { + if (!arguments[0]) { + time = undefined; + formats = undefined; + } else if (isMomentInput(arguments[0])) { + time = arguments[0]; + formats = undefined; + } else if (isCalendarSpec(arguments[0])) { + formats = arguments[0]; + time = undefined; } - // We want to compare the start of today, vs this. - // Getting start-of-today depends on whether we're local/utc/offset or not. - var now = time || createLocal(), - sod = cloneWithOffset(now, this).startOf('day'), - format = hooks.calendarFormat(this, sod) || 'sameElse', - output = - formats && - (isFunction(formats[format]) - ? formats[format].call(this, now) - : formats[format]); + } + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf("day"), + format = hooks.calendarFormat(this, sod) || "sameElse", + output = + formats && + (isFunction(formats[format]) + ? formats[format].call(this, now) + : formats[format]); - return this.format( - output || this.localeData().calendar(format, this, createLocal(now)) - ); + return this.format( + output || this.localeData().calendar(format, this, createLocal(now)), + ); } function clone() { - return new Moment(this); + return new Moment(this); } function isAfter(input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(units) || 'millisecond'; - if (units === 'millisecond') { - return this.valueOf() > localInput.valueOf(); - } else { - return localInput.valueOf() < this.clone().startOf(units).valueOf(); - } + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } } function isBefore(input, units) { - var localInput = isMoment(input) ? input : createLocal(input); - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(units) || 'millisecond'; - if (units === 'millisecond') { - return this.valueOf() < localInput.valueOf(); - } else { - return this.clone().endOf(units).valueOf() < localInput.valueOf(); - } + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } } function isBetween(from, to, units, inclusivity) { - var localFrom = isMoment(from) ? from : createLocal(from), - localTo = isMoment(to) ? to : createLocal(to); - if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { - return false; - } - inclusivity = inclusivity || '()'; - return ( - (inclusivity[0] === '(' - ? this.isAfter(localFrom, units) - : !this.isBefore(localFrom, units)) && - (inclusivity[1] === ')' - ? this.isBefore(localTo, units) - : !this.isAfter(localTo, units)) - ); + var localFrom = isMoment(from) ? from : createLocal(from), + localTo = isMoment(to) ? to : createLocal(to); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; + } + inclusivity = inclusivity || "()"; + return ( + (inclusivity[0] === "(" + ? this.isAfter(localFrom, units) + : !this.isBefore(localFrom, units)) && + (inclusivity[1] === ")" + ? this.isBefore(localTo, units) + : !this.isAfter(localTo, units)) + ); } function isSame(input, units) { - var localInput = isMoment(input) ? input : createLocal(input), - inputMs; - if (!(this.isValid() && localInput.isValid())) { - return false; - } - units = normalizeUnits(units) || 'millisecond'; - if (units === 'millisecond') { - return this.valueOf() === localInput.valueOf(); - } else { - inputMs = localInput.valueOf(); - return ( - this.clone().startOf(units).valueOf() <= inputMs && - inputMs <= this.clone().endOf(units).valueOf() - ); - } + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || "millisecond"; + if (units === "millisecond") { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return ( + this.clone().startOf(units).valueOf() <= inputMs && + inputMs <= this.clone().endOf(units).valueOf() + ); + } } function isSameOrAfter(input, units) { - return this.isSame(input, units) || this.isAfter(input, units); + return this.isSame(input, units) || this.isAfter(input, units); } function isSameOrBefore(input, units) { - return this.isSame(input, units) || this.isBefore(input, units); + return this.isSame(input, units) || this.isBefore(input, units); } function diff(input, units, asFloat) { - var that, zoneDelta, output; + var that, zoneDelta, output; - if (!this.isValid()) { - return NaN; - } + if (!this.isValid()) { + return NaN; + } - that = cloneWithOffset(input, this); + that = cloneWithOffset(input, this); - if (!that.isValid()) { - return NaN; - } + if (!that.isValid()) { + return NaN; + } - zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; - units = normalizeUnits(units); + units = normalizeUnits(units); - switch (units) { - case 'year': - output = monthDiff(this, that) / 12; - break; - case 'month': - output = monthDiff(this, that); - break; - case 'quarter': - output = monthDiff(this, that) / 3; - break; - case 'second': - output = (this - that) / 1e3; - break; // 1000 - case 'minute': - output = (this - that) / 6e4; - break; // 1000 * 60 - case 'hour': - output = (this - that) / 36e5; - break; // 1000 * 60 * 60 - case 'day': - output = (this - that - zoneDelta) / 864e5; - break; // 1000 * 60 * 60 * 24, negate dst - case 'week': - output = (this - that - zoneDelta) / 6048e5; - break; // 1000 * 60 * 60 * 24 * 7, negate dst - default: - output = this - that; - } + switch (units) { + case "year": + output = monthDiff(this, that) / 12; + break; + case "month": + output = monthDiff(this, that); + break; + case "quarter": + output = monthDiff(this, that) / 3; + break; + case "second": + output = (this - that) / 1e3; + break; // 1000 + case "minute": + output = (this - that) / 6e4; + break; // 1000 * 60 + case "hour": + output = (this - that) / 36e5; + break; // 1000 * 60 * 60 + case "day": + output = (this - that - zoneDelta) / 864e5; + break; // 1000 * 60 * 60 * 24, negate dst + case "week": + output = (this - that - zoneDelta) / 6048e5; + break; // 1000 * 60 * 60 * 24 * 7, negate dst + default: + output = this - that; + } - return asFloat ? output : absFloor(output); + return asFloat ? output : absFloor(output); } function monthDiff(a, b) { - if (a.date() < b.date()) { - // end-of-month calculations work correct when the start month has more - // days than the end month. - return -monthDiff(b, a); - } - // difference in months - var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), - // b is in (anchor - 1 month, anchor + 1 month) - anchor = a.clone().add(wholeMonthDiff, 'months'), - anchor2, - adjust; + if (a.date() < b.date()) { + // end-of-month calculations work correct when the start month has more + // days than the end month. + return -monthDiff(b, a); + } + // difference in months + var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, "months"), + anchor2, + adjust; - if (b - anchor < 0) { - anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor - anchor2); - } else { - anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); - // linear across the month - adjust = (b - anchor) / (anchor2 - anchor); - } + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, "months"); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, "months"); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } - //check for negative zero, return zero if negative zero - return -(wholeMonthDiff + adjust) || 0; + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; } - hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; - hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ"; + hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]"; function toString() { - return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); + return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); } function toISOString(keepOffset) { - if (!this.isValid()) { - return null; - } - var utc = keepOffset !== true, - m = utc ? this.clone().utc() : this; - if (m.year() < 0 || m.year() > 9999) { - return formatMoment( - m, - utc - ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' - : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ' - ); - } - if (isFunction(Date.prototype.toISOString)) { - // native implementation is ~50x faster, use it when we can - if (utc) { - return this.toDate().toISOString(); - } else { - return new Date(this.valueOf() + this.utcOffset() * 60 * 1000) - .toISOString() - .replace('Z', formatMoment(m, 'Z')); - } - } + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true, + m = utc ? this.clone().utc() : this; + if (m.year() < 0 || m.year() > 9999) { return formatMoment( - m, - utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ' + m, + utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ", ); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1000) + .toISOString() + .replace("Z", formatMoment(m, "Z")); + } + } + return formatMoment( + m, + utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ", + ); } /** @@ -3946,804 +3924,790 @@ * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects */ function inspect() { - if (!this.isValid()) { - return 'moment.invalid(/* ' + this._i + ' */)'; - } - var func = 'moment', - zone = '', - prefix, - year, - datetime, - suffix; - if (!this.isLocal()) { - func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; - zone = 'Z'; - } - prefix = '[' + func + '("]'; - year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY'; - datetime = '-MM-DD[T]HH:mm:ss.SSS'; - suffix = zone + '[")]'; + if (!this.isValid()) { + return "moment.invalid(/* " + this._i + " */)"; + } + var func = "moment", + zone = "", + prefix, + year, + datetime, + suffix; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone"; + zone = "Z"; + } + prefix = "[" + func + '("]'; + year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY"; + datetime = "-MM-DD[T]HH:mm:ss.SSS"; + suffix = zone + '[")]'; - return this.format(prefix + year + datetime + suffix); + return this.format(prefix + year + datetime + suffix); } function format(inputString) { - if (!inputString) { - inputString = this.isUtc() - ? hooks.defaultFormatUtc - : hooks.defaultFormat; - } - var output = formatMoment(this, inputString); - return this.localeData().postformat(output); + if (!inputString) { + inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); } function from(time, withoutSuffix) { - if ( - this.isValid() && - ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) - ) { - return createDuration({ to: this, from: time }) - .locale(this.locale()) - .humanize(!withoutSuffix); - } else { - return this.localeData().invalidDate(); - } + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ to: this, from: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } } function fromNow(withoutSuffix) { - return this.from(createLocal(), withoutSuffix); + return this.from(createLocal(), withoutSuffix); } function to(time, withoutSuffix) { - if ( - this.isValid() && - ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) - ) { - return createDuration({ from: this, to: time }) - .locale(this.locale()) - .humanize(!withoutSuffix); - } else { - return this.localeData().invalidDate(); - } + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ from: this, to: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } } function toNow(withoutSuffix) { - return this.to(createLocal(), withoutSuffix); + return this.to(createLocal(), withoutSuffix); } // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. function locale(key) { - var newLocaleData; + var newLocaleData; - if (key === undefined) { - return this._locale._abbr; - } else { - newLocaleData = getLocale(key); - if (newLocaleData != null) { - this._locale = newLocaleData; - } - return this; + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; } + return this; + } } var lang = deprecate( - 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', - function (key) { - if (key === undefined) { - return this.localeData(); - } else { - return this.locale(key); - } + "moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); } + }, ); function localeData() { - return this._locale; + return this._locale; } var MS_PER_SECOND = 1000, - MS_PER_MINUTE = 60 * MS_PER_SECOND, - MS_PER_HOUR = 60 * MS_PER_MINUTE, - MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + MS_PER_MINUTE = 60 * MS_PER_SECOND, + MS_PER_HOUR = 60 * MS_PER_MINUTE, + MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; // actual modulo - handles negative numbers (for dates before 1970): function mod$1(dividend, divisor) { - return ((dividend % divisor) + divisor) % divisor; + return ((dividend % divisor) + divisor) % divisor; } function localStartOfDate(y, m, d) { - // the date constructor remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - // preserve leap years using a full 400 year cycle, then reset - return new Date(y + 400, m, d) - MS_PER_400_YEARS; - } else { - return new Date(y, m, d).valueOf(); - } + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return new Date(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return new Date(y, m, d).valueOf(); + } } function utcStartOfDate(y, m, d) { - // Date.UTC remaps years 0-99 to 1900-1999 - if (y < 100 && y >= 0) { - // preserve leap years using a full 400 year cycle, then reset - return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; - } else { - return Date.UTC(y, m, d); - } + // Date.UTC remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y, m, d); + } } function startOf(units) { - var time, startOfDate; - units = normalizeUnits(units); - if (units === undefined || units === 'millisecond' || !this.isValid()) { - return this; - } - - startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; - - switch (units) { - case 'year': - time = startOfDate(this.year(), 0, 1); - break; - case 'quarter': - time = startOfDate( - this.year(), - this.month() - (this.month() % 3), - 1 - ); - break; - case 'month': - time = startOfDate(this.year(), this.month(), 1); - break; - case 'week': - time = startOfDate( - this.year(), - this.month(), - this.date() - this.weekday() - ); - break; - case 'isoWeek': - time = startOfDate( - this.year(), - this.month(), - this.date() - (this.isoWeekday() - 1) - ); - break; - case 'day': - case 'date': - time = startOfDate(this.year(), this.month(), this.date()); - break; - case 'hour': - time = this._d.valueOf(); - time -= mod$1( - time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), - MS_PER_HOUR - ); - break; - case 'minute': - time = this._d.valueOf(); - time -= mod$1(time, MS_PER_MINUTE); - break; - case 'second': - time = this._d.valueOf(); - time -= mod$1(time, MS_PER_SECOND); - break; - } - - this._d.setTime(time); - hooks.updateOffset(this, true); + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === "millisecond" || !this.isValid()) { return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case "year": + time = startOfDate(this.year(), 0, 1); + break; + case "quarter": + time = startOfDate(this.year(), this.month() - (this.month() % 3), 1); + break; + case "month": + time = startOfDate(this.year(), this.month(), 1); + break; + case "week": + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday(), + ); + break; + case "isoWeek": + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1), + ); + break; + case "day": + case "date": + time = startOfDate(this.year(), this.month(), this.date()); + break; + case "hour": + time = this._d.valueOf(); + time -= mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR, + ); + break; + case "minute": + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case "second": + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; } function endOf(units) { - var time, startOfDate; - units = normalizeUnits(units); - if (units === undefined || units === 'millisecond' || !this.isValid()) { - return this; - } - - startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; - - switch (units) { - case 'year': - time = startOfDate(this.year() + 1, 0, 1) - 1; - break; - case 'quarter': - time = - startOfDate( - this.year(), - this.month() - (this.month() % 3) + 3, - 1 - ) - 1; - break; - case 'month': - time = startOfDate(this.year(), this.month() + 1, 1) - 1; - break; - case 'week': - time = - startOfDate( - this.year(), - this.month(), - this.date() - this.weekday() + 7 - ) - 1; - break; - case 'isoWeek': - time = - startOfDate( - this.year(), - this.month(), - this.date() - (this.isoWeekday() - 1) + 7 - ) - 1; - break; - case 'day': - case 'date': - time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; - break; - case 'hour': - time = this._d.valueOf(); - time += - MS_PER_HOUR - - mod$1( - time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), - MS_PER_HOUR - ) - - 1; - break; - case 'minute': - time = this._d.valueOf(); - time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; - break; - case 'second': - time = this._d.valueOf(); - time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; - break; - } - - this._d.setTime(time); - hooks.updateOffset(this, true); + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === "millisecond" || !this.isValid()) { return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case "year": + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case "quarter": + time = + startOfDate(this.year(), this.month() - (this.month() % 3) + 3, 1) - + 1; + break; + case "month": + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case "week": + time = + startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + 7, + ) - 1; + break; + case "isoWeek": + time = + startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + 7, + ) - 1; + break; + case "day": + case "date": + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case "hour": + time = this._d.valueOf(); + time += + MS_PER_HOUR - + mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR, + ) - + 1; + break; + case "minute": + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case "second": + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; } function valueOf() { - return this._d.valueOf() - (this._offset || 0) * 60000; + return this._d.valueOf() - (this._offset || 0) * 60000; } function unix() { - return Math.floor(this.valueOf() / 1000); + return Math.floor(this.valueOf() / 1000); } function toDate() { - return new Date(this.valueOf()); + return new Date(this.valueOf()); } function toArray() { - var m = this; - return [ - m.year(), - m.month(), - m.date(), - m.hour(), - m.minute(), - m.second(), - m.millisecond(), - ]; + var m = this; + return [ + m.year(), + m.month(), + m.date(), + m.hour(), + m.minute(), + m.second(), + m.millisecond(), + ]; } function toObject() { - var m = this; - return { - years: m.year(), - months: m.month(), - date: m.date(), - hours: m.hours(), - minutes: m.minutes(), - seconds: m.seconds(), - milliseconds: m.milliseconds(), - }; + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds(), + }; } function toJSON() { - // new Date(NaN).toJSON() === null - return this.isValid() ? this.toISOString() : null; + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; } function isValid$2() { - return isValid(this); + return isValid(this); } function parsingFlags() { - return extend({}, getParsingFlags(this)); + return extend({}, getParsingFlags(this)); } function invalidAt() { - return getParsingFlags(this).overflow; + return getParsingFlags(this).overflow; } function creationData() { - return { - input: this._i, - format: this._f, - locale: this._locale, - isUTC: this._isUTC, - strict: this._strict, - }; + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict, + }; } - addFormatToken('N', 0, 0, 'eraAbbr'); - addFormatToken('NN', 0, 0, 'eraAbbr'); - addFormatToken('NNN', 0, 0, 'eraAbbr'); - addFormatToken('NNNN', 0, 0, 'eraName'); - addFormatToken('NNNNN', 0, 0, 'eraNarrow'); + addFormatToken("N", 0, 0, "eraAbbr"); + addFormatToken("NN", 0, 0, "eraAbbr"); + addFormatToken("NNN", 0, 0, "eraAbbr"); + addFormatToken("NNNN", 0, 0, "eraName"); + addFormatToken("NNNNN", 0, 0, "eraNarrow"); - addFormatToken('y', ['y', 1], 'yo', 'eraYear'); - addFormatToken('y', ['yy', 2], 0, 'eraYear'); - addFormatToken('y', ['yyy', 3], 0, 'eraYear'); - addFormatToken('y', ['yyyy', 4], 0, 'eraYear'); + addFormatToken("y", ["y", 1], "yo", "eraYear"); + addFormatToken("y", ["yy", 2], 0, "eraYear"); + addFormatToken("y", ["yyy", 3], 0, "eraYear"); + addFormatToken("y", ["yyyy", 4], 0, "eraYear"); - addRegexToken('N', matchEraAbbr); - addRegexToken('NN', matchEraAbbr); - addRegexToken('NNN', matchEraAbbr); - addRegexToken('NNNN', matchEraName); - addRegexToken('NNNNN', matchEraNarrow); + addRegexToken("N", matchEraAbbr); + addRegexToken("NN", matchEraAbbr); + addRegexToken("NNN", matchEraAbbr); + addRegexToken("NNNN", matchEraName); + addRegexToken("NNNNN", matchEraNarrow); - addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function ( - input, - array, - config, - token - ) { + addParseToken( + ["N", "NN", "NNN", "NNNN", "NNNNN"], + function (input, array, config, token) { var era = config._locale.erasParse(input, token, config._strict); if (era) { - getParsingFlags(config).era = era; + getParsingFlags(config).era = era; } else { - getParsingFlags(config).invalidEra = input; + getParsingFlags(config).invalidEra = input; } - }); + }, + ); - addRegexToken('y', matchUnsigned); - addRegexToken('yy', matchUnsigned); - addRegexToken('yyy', matchUnsigned); - addRegexToken('yyyy', matchUnsigned); - addRegexToken('yo', matchEraYearOrdinal); + addRegexToken("y", matchUnsigned); + addRegexToken("yy", matchUnsigned); + addRegexToken("yyy", matchUnsigned); + addRegexToken("yyyy", matchUnsigned); + addRegexToken("yo", matchEraYearOrdinal); - addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR); - addParseToken(['yo'], function (input, array, config, token) { - var match; - if (config._locale._eraYearOrdinalRegex) { - match = input.match(config._locale._eraYearOrdinalRegex); - } + addParseToken(["y", "yy", "yyy", "yyyy"], YEAR); + addParseToken(["yo"], function (input, array, config, token) { + var match; + if (config._locale._eraYearOrdinalRegex) { + match = input.match(config._locale._eraYearOrdinalRegex); + } - if (config._locale.eraYearOrdinalParse) { - array[YEAR] = config._locale.eraYearOrdinalParse(input, match); - } else { - array[YEAR] = parseInt(input, 10); - } + if (config._locale.eraYearOrdinalParse) { + array[YEAR] = config._locale.eraYearOrdinalParse(input, match); + } else { + array[YEAR] = parseInt(input, 10); + } }); function localeEras(m, format) { - var i, - l, - date, - eras = this._eras || getLocale('en')._eras; - for (i = 0, l = eras.length; i < l; ++i) { - switch (typeof eras[i].since) { - case 'string': - // truncate time - date = hooks(eras[i].since).startOf('day'); - eras[i].since = date.valueOf(); - break; - } - - switch (typeof eras[i].until) { - case 'undefined': - eras[i].until = +Infinity; - break; - case 'string': - // truncate time - date = hooks(eras[i].until).startOf('day').valueOf(); - eras[i].until = date.valueOf(); - break; - } + var i, + l, + date, + eras = this._eras || getLocale("en")._eras; + for (i = 0, l = eras.length; i < l; ++i) { + switch (typeof eras[i].since) { + case "string": + // truncate time + date = hooks(eras[i].since).startOf("day"); + eras[i].since = date.valueOf(); + break; } - return eras; + + switch (typeof eras[i].until) { + case "undefined": + eras[i].until = +Infinity; + break; + case "string": + // truncate time + date = hooks(eras[i].until).startOf("day").valueOf(); + eras[i].until = date.valueOf(); + break; + } + } + return eras; } function localeErasParse(eraName, format, strict) { - var i, - l, - eras = this.eras(), - name, - abbr, - narrow; - eraName = eraName.toUpperCase(); + var i, + l, + eras = this.eras(), + name, + abbr, + narrow; + eraName = eraName.toUpperCase(); - for (i = 0, l = eras.length; i < l; ++i) { - name = eras[i].name.toUpperCase(); - abbr = eras[i].abbr.toUpperCase(); - narrow = eras[i].narrow.toUpperCase(); + for (i = 0, l = eras.length; i < l; ++i) { + name = eras[i].name.toUpperCase(); + abbr = eras[i].abbr.toUpperCase(); + narrow = eras[i].narrow.toUpperCase(); - if (strict) { - switch (format) { - case 'N': - case 'NN': - case 'NNN': - if (abbr === eraName) { - return eras[i]; - } - break; - - case 'NNNN': - if (name === eraName) { - return eras[i]; - } - break; - - case 'NNNNN': - if (narrow === eraName) { - return eras[i]; - } - break; - } - } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { + if (strict) { + switch (format) { + case "N": + case "NN": + case "NNN": + if (abbr === eraName) { return eras[i]; - } + } + break; + + case "NNNN": + if (name === eraName) { + return eras[i]; + } + break; + + case "NNNNN": + if (narrow === eraName) { + return eras[i]; + } + break; + } + } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { + return eras[i]; } + } } function localeErasConvertYear(era, year) { - var dir = era.since <= era.until ? +1 : -1; - if (year === undefined) { - return hooks(era.since).year(); - } else { - return hooks(era.since).year() + (year - era.offset) * dir; - } + var dir = era.since <= era.until ? +1 : -1; + if (year === undefined) { + return hooks(era.since).year(); + } else { + return hooks(era.since).year() + (year - era.offset) * dir; + } } function getEraName() { - var i, - l, - val, - eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - // truncate time - val = this.clone().startOf('day').valueOf(); + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf("day").valueOf(); - if (eras[i].since <= val && val <= eras[i].until) { - return eras[i].name; - } - if (eras[i].until <= val && val <= eras[i].since) { - return eras[i].name; - } + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].name; } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].name; + } + } - return ''; + return ""; } function getEraNarrow() { - var i, - l, - val, - eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - // truncate time - val = this.clone().startOf('day').valueOf(); + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf("day").valueOf(); - if (eras[i].since <= val && val <= eras[i].until) { - return eras[i].narrow; - } - if (eras[i].until <= val && val <= eras[i].since) { - return eras[i].narrow; - } + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].narrow; } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].narrow; + } + } - return ''; + return ""; } function getEraAbbr() { - var i, - l, - val, - eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - // truncate time - val = this.clone().startOf('day').valueOf(); + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf("day").valueOf(); - if (eras[i].since <= val && val <= eras[i].until) { - return eras[i].abbr; - } - if (eras[i].until <= val && val <= eras[i].since) { - return eras[i].abbr; - } + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].abbr; } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].abbr; + } + } - return ''; + return ""; } function getEraYear() { - var i, - l, - dir, - val, - eras = this.localeData().eras(); - for (i = 0, l = eras.length; i < l; ++i) { - dir = eras[i].since <= eras[i].until ? +1 : -1; + var i, + l, + dir, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + dir = eras[i].since <= eras[i].until ? +1 : -1; - // truncate time - val = this.clone().startOf('day').valueOf(); + // truncate time + val = this.clone().startOf("day").valueOf(); - if ( - (eras[i].since <= val && val <= eras[i].until) || - (eras[i].until <= val && val <= eras[i].since) - ) { - return ( - (this.year() - hooks(eras[i].since).year()) * dir + - eras[i].offset - ); - } + if ( + (eras[i].since <= val && val <= eras[i].until) || + (eras[i].until <= val && val <= eras[i].since) + ) { + return ( + (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset + ); } + } - return this.year(); + return this.year(); } function erasNameRegex(isStrict) { - if (!hasOwnProp(this, '_erasNameRegex')) { - computeErasParse.call(this); - } - return isStrict ? this._erasNameRegex : this._erasRegex; + if (!hasOwnProp(this, "_erasNameRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasNameRegex : this._erasRegex; } function erasAbbrRegex(isStrict) { - if (!hasOwnProp(this, '_erasAbbrRegex')) { - computeErasParse.call(this); - } - return isStrict ? this._erasAbbrRegex : this._erasRegex; + if (!hasOwnProp(this, "_erasAbbrRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasAbbrRegex : this._erasRegex; } function erasNarrowRegex(isStrict) { - if (!hasOwnProp(this, '_erasNarrowRegex')) { - computeErasParse.call(this); - } - return isStrict ? this._erasNarrowRegex : this._erasRegex; + if (!hasOwnProp(this, "_erasNarrowRegex")) { + computeErasParse.call(this); + } + return isStrict ? this._erasNarrowRegex : this._erasRegex; } function matchEraAbbr(isStrict, locale) { - return locale.erasAbbrRegex(isStrict); + return locale.erasAbbrRegex(isStrict); } function matchEraName(isStrict, locale) { - return locale.erasNameRegex(isStrict); + return locale.erasNameRegex(isStrict); } function matchEraNarrow(isStrict, locale) { - return locale.erasNarrowRegex(isStrict); + return locale.erasNarrowRegex(isStrict); } function matchEraYearOrdinal(isStrict, locale) { - return locale._eraYearOrdinalRegex || matchUnsigned; + return locale._eraYearOrdinalRegex || matchUnsigned; } function computeErasParse() { - var abbrPieces = [], - namePieces = [], - narrowPieces = [], - mixedPieces = [], - i, - l, - eras = this.eras(); + var abbrPieces = [], + namePieces = [], + narrowPieces = [], + mixedPieces = [], + i, + l, + eras = this.eras(); - for (i = 0, l = eras.length; i < l; ++i) { - namePieces.push(regexEscape(eras[i].name)); - abbrPieces.push(regexEscape(eras[i].abbr)); - narrowPieces.push(regexEscape(eras[i].narrow)); + for (i = 0, l = eras.length; i < l; ++i) { + namePieces.push(regexEscape(eras[i].name)); + abbrPieces.push(regexEscape(eras[i].abbr)); + narrowPieces.push(regexEscape(eras[i].narrow)); - mixedPieces.push(regexEscape(eras[i].name)); - mixedPieces.push(regexEscape(eras[i].abbr)); - mixedPieces.push(regexEscape(eras[i].narrow)); - } + mixedPieces.push(regexEscape(eras[i].name)); + mixedPieces.push(regexEscape(eras[i].abbr)); + mixedPieces.push(regexEscape(eras[i].narrow)); + } - this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); - this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i'); - this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i'); - this._erasNarrowRegex = new RegExp( - '^(' + narrowPieces.join('|') + ')', - 'i' - ); + this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); + this._erasNameRegex = new RegExp("^(" + namePieces.join("|") + ")", "i"); + this._erasAbbrRegex = new RegExp("^(" + abbrPieces.join("|") + ")", "i"); + this._erasNarrowRegex = new RegExp( + "^(" + narrowPieces.join("|") + ")", + "i", + ); } // FORMATTING - addFormatToken(0, ['gg', 2], 0, function () { - return this.weekYear() % 100; + addFormatToken(0, ["gg", 2], 0, function () { + return this.weekYear() % 100; }); - addFormatToken(0, ['GG', 2], 0, function () { - return this.isoWeekYear() % 100; + addFormatToken(0, ["GG", 2], 0, function () { + return this.isoWeekYear() % 100; }); function addWeekYearFormatToken(token, getter) { - addFormatToken(0, [token, token.length], 0, getter); + addFormatToken(0, [token, token.length], 0, getter); } - addWeekYearFormatToken('gggg', 'weekYear'); - addWeekYearFormatToken('ggggg', 'weekYear'); - addWeekYearFormatToken('GGGG', 'isoWeekYear'); - addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + addWeekYearFormatToken("gggg", "weekYear"); + addWeekYearFormatToken("ggggg", "weekYear"); + addWeekYearFormatToken("GGGG", "isoWeekYear"); + addWeekYearFormatToken("GGGGG", "isoWeekYear"); // ALIASES - addUnitAlias('weekYear', 'gg'); - addUnitAlias('isoWeekYear', 'GG'); + addUnitAlias("weekYear", "gg"); + addUnitAlias("isoWeekYear", "GG"); // PRIORITY - addUnitPriority('weekYear', 1); - addUnitPriority('isoWeekYear', 1); + addUnitPriority("weekYear", 1); + addUnitPriority("isoWeekYear", 1); // PARSING - addRegexToken('G', matchSigned); - addRegexToken('g', matchSigned); - addRegexToken('GG', match1to2, match2); - addRegexToken('gg', match1to2, match2); - addRegexToken('GGGG', match1to4, match4); - addRegexToken('gggg', match1to4, match4); - addRegexToken('GGGGG', match1to6, match6); - addRegexToken('ggggg', match1to6, match6); + addRegexToken("G", matchSigned); + addRegexToken("g", matchSigned); + addRegexToken("GG", match1to2, match2); + addRegexToken("gg", match1to2, match2); + addRegexToken("GGGG", match1to4, match4); + addRegexToken("gggg", match1to4, match4); + addRegexToken("GGGGG", match1to6, match6); + addRegexToken("ggggg", match1to6, match6); - addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function ( - input, - week, - config, - token - ) { + addWeekParseToken( + ["gggg", "ggggg", "GGGG", "GGGGG"], + function (input, week, config, token) { week[token.substr(0, 2)] = toInt(input); - }); + }, + ); - addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { - week[token] = hooks.parseTwoDigitYear(input); + addWeekParseToken(["gg", "GG"], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); }); // MOMENTS function getSetWeekYear(input) { - return getSetWeekYearHelper.call( - this, - input, - this.week(), - this.weekday(), - this.localeData()._week.dow, - this.localeData()._week.doy - ); + return getSetWeekYearHelper.call( + this, + input, + this.week(), + this.weekday(), + this.localeData()._week.dow, + this.localeData()._week.doy, + ); } function getSetISOWeekYear(input) { - return getSetWeekYearHelper.call( - this, - input, - this.isoWeek(), - this.isoWeekday(), - 1, - 4 - ); + return getSetWeekYearHelper.call( + this, + input, + this.isoWeek(), + this.isoWeekday(), + 1, + 4, + ); } function getISOWeeksInYear() { - return weeksInYear(this.year(), 1, 4); + return weeksInYear(this.year(), 1, 4); } function getISOWeeksInISOWeekYear() { - return weeksInYear(this.isoWeekYear(), 1, 4); + return weeksInYear(this.isoWeekYear(), 1, 4); } function getWeeksInYear() { - var weekInfo = this.localeData()._week; - return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getWeeksInWeekYear() { - var weekInfo = this.localeData()._week; - return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); + var weekInfo = this.localeData()._week; + return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { - var weeksTarget; - if (input == null) { - return weekOfYear(this, dow, doy).year; - } else { - weeksTarget = weeksInYear(input, dow, doy); - if (week > weeksTarget) { - week = weeksTarget; - } - return setWeekAll.call(this, input, week, weekday, dow, doy); + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } } function setWeekAll(weekYear, week, weekday, dow, doy) { - var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), - date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); - this.year(date.getUTCFullYear()); - this.month(date.getUTCMonth()); - this.date(date.getUTCDate()); - return this; + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; } // FORMATTING - addFormatToken('Q', 0, 'Qo', 'quarter'); + addFormatToken("Q", 0, "Qo", "quarter"); // ALIASES - addUnitAlias('quarter', 'Q'); + addUnitAlias("quarter", "Q"); // PRIORITY - addUnitPriority('quarter', 7); + addUnitPriority("quarter", 7); // PARSING - addRegexToken('Q', match1); - addParseToken('Q', function (input, array) { - array[MONTH] = (toInt(input) - 1) * 3; + addRegexToken("Q", match1); + addParseToken("Q", function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter(input) { - return input == null - ? Math.ceil((this.month() + 1) / 3) - : this.month((input - 1) * 3 + (this.month() % 3)); + return input == null + ? Math.ceil((this.month() + 1) / 3) + : this.month((input - 1) * 3 + (this.month() % 3)); } // FORMATTING - addFormatToken('D', ['DD', 2], 'Do', 'date'); + addFormatToken("D", ["DD", 2], "Do", "date"); // ALIASES - addUnitAlias('date', 'D'); + addUnitAlias("date", "D"); // PRIORITY - addUnitPriority('date', 9); + addUnitPriority("date", 9); // PARSING - addRegexToken('D', match1to2); - addRegexToken('DD', match1to2, match2); - addRegexToken('Do', function (isStrict, locale) { - // TODO: Remove "ordinalParse" fallback in next major release. - return isStrict - ? locale._dayOfMonthOrdinalParse || locale._ordinalParse - : locale._dayOfMonthOrdinalParseLenient; + addRegexToken("D", match1to2); + addRegexToken("DD", match1to2, match2); + addRegexToken("Do", function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict + ? locale._dayOfMonthOrdinalParse || locale._ordinalParse + : locale._dayOfMonthOrdinalParseLenient; }); - addParseToken(['D', 'DD'], DATE); - addParseToken('Do', function (input, array) { - array[DATE] = toInt(input.match(match1to2)[0]); + addParseToken(["D", "DD"], DATE); + addParseToken("Do", function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); }); // MOMENTS - var getSetDayOfMonth = makeGetSet('Date', true); + var getSetDayOfMonth = makeGetSet("Date", true); // FORMATTING - addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear"); // ALIASES - addUnitAlias('dayOfYear', 'DDD'); + addUnitAlias("dayOfYear", "DDD"); // PRIORITY - addUnitPriority('dayOfYear', 4); + addUnitPriority("dayOfYear", 4); // PARSING - addRegexToken('DDD', match1to3); - addRegexToken('DDDD', match3); - addParseToken(['DDD', 'DDDD'], function (input, array, config) { - config._dayOfYear = toInt(input); + addRegexToken("DDD", match1to3); + addRegexToken("DDDD", match3); + addParseToken(["DDD", "DDDD"], function (input, array, config) { + config._dayOfYear = toInt(input); }); // HELPERS @@ -4751,129 +4715,129 @@ // MOMENTS function getSetDayOfYear(input) { - var dayOfYear = - Math.round( - (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5 - ) + 1; - return input == null ? dayOfYear : this.add(input - dayOfYear, 'd'); + var dayOfYear = + Math.round( + (this.clone().startOf("day") - this.clone().startOf("year")) / 864e5, + ) + 1; + return input == null ? dayOfYear : this.add(input - dayOfYear, "d"); } // FORMATTING - addFormatToken('m', ['mm', 2], 0, 'minute'); + addFormatToken("m", ["mm", 2], 0, "minute"); // ALIASES - addUnitAlias('minute', 'm'); + addUnitAlias("minute", "m"); // PRIORITY - addUnitPriority('minute', 14); + addUnitPriority("minute", 14); // PARSING - addRegexToken('m', match1to2); - addRegexToken('mm', match1to2, match2); - addParseToken(['m', 'mm'], MINUTE); + addRegexToken("m", match1to2); + addRegexToken("mm", match1to2, match2); + addParseToken(["m", "mm"], MINUTE); // MOMENTS - var getSetMinute = makeGetSet('Minutes', false); + var getSetMinute = makeGetSet("Minutes", false); // FORMATTING - addFormatToken('s', ['ss', 2], 0, 'second'); + addFormatToken("s", ["ss", 2], 0, "second"); // ALIASES - addUnitAlias('second', 's'); + addUnitAlias("second", "s"); // PRIORITY - addUnitPriority('second', 15); + addUnitPriority("second", 15); // PARSING - addRegexToken('s', match1to2); - addRegexToken('ss', match1to2, match2); - addParseToken(['s', 'ss'], SECOND); + addRegexToken("s", match1to2); + addRegexToken("ss", match1to2, match2); + addParseToken(["s", "ss"], SECOND); // MOMENTS - var getSetSecond = makeGetSet('Seconds', false); + var getSetSecond = makeGetSet("Seconds", false); // FORMATTING - addFormatToken('S', 0, 0, function () { - return ~~(this.millisecond() / 100); + addFormatToken("S", 0, 0, function () { + return ~~(this.millisecond() / 100); }); - addFormatToken(0, ['SS', 2], 0, function () { - return ~~(this.millisecond() / 10); + addFormatToken(0, ["SS", 2], 0, function () { + return ~~(this.millisecond() / 10); }); - addFormatToken(0, ['SSS', 3], 0, 'millisecond'); - addFormatToken(0, ['SSSS', 4], 0, function () { - return this.millisecond() * 10; + addFormatToken(0, ["SSS", 3], 0, "millisecond"); + addFormatToken(0, ["SSSS", 4], 0, function () { + return this.millisecond() * 10; }); - addFormatToken(0, ['SSSSS', 5], 0, function () { - return this.millisecond() * 100; + addFormatToken(0, ["SSSSS", 5], 0, function () { + return this.millisecond() * 100; }); - addFormatToken(0, ['SSSSSS', 6], 0, function () { - return this.millisecond() * 1000; + addFormatToken(0, ["SSSSSS", 6], 0, function () { + return this.millisecond() * 1000; }); - addFormatToken(0, ['SSSSSSS', 7], 0, function () { - return this.millisecond() * 10000; + addFormatToken(0, ["SSSSSSS", 7], 0, function () { + return this.millisecond() * 10000; }); - addFormatToken(0, ['SSSSSSSS', 8], 0, function () { - return this.millisecond() * 100000; + addFormatToken(0, ["SSSSSSSS", 8], 0, function () { + return this.millisecond() * 100000; }); - addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { - return this.millisecond() * 1000000; + addFormatToken(0, ["SSSSSSSSS", 9], 0, function () { + return this.millisecond() * 1000000; }); // ALIASES - addUnitAlias('millisecond', 'ms'); + addUnitAlias("millisecond", "ms"); // PRIORITY - addUnitPriority('millisecond', 16); + addUnitPriority("millisecond", 16); // PARSING - addRegexToken('S', match1to3, match1); - addRegexToken('SS', match1to3, match2); - addRegexToken('SSS', match1to3, match3); + addRegexToken("S", match1to3, match1); + addRegexToken("SS", match1to3, match2); + addRegexToken("SSS", match1to3, match3); var token, getSetMillisecond; - for (token = 'SSSS'; token.length <= 9; token += 'S') { - addRegexToken(token, matchUnsigned); + for (token = "SSSS"; token.length <= 9; token += "S") { + addRegexToken(token, matchUnsigned); } function parseMs(input, array) { - array[MILLISECOND] = toInt(('0.' + input) * 1000); + array[MILLISECOND] = toInt(("0." + input) * 1000); } - for (token = 'S'; token.length <= 9; token += 'S') { - addParseToken(token, parseMs); + for (token = "S"; token.length <= 9; token += "S") { + addParseToken(token, parseMs); } - getSetMillisecond = makeGetSet('Milliseconds', false); + getSetMillisecond = makeGetSet("Milliseconds", false); // FORMATTING - addFormatToken('z', 0, 0, 'zoneAbbr'); - addFormatToken('zz', 0, 0, 'zoneName'); + addFormatToken("z", 0, 0, "zoneAbbr"); + addFormatToken("zz", 0, 0, "zoneName"); // MOMENTS function getZoneAbbr() { - return this._isUTC ? 'UTC' : ''; + return this._isUTC ? "UTC" : ""; } function getZoneName() { - return this._isUTC ? 'Coordinated Universal Time' : ''; + return this._isUTC ? "Coordinated Universal Time" : ""; } var proto = Moment.prototype; @@ -4911,10 +4875,10 @@ proto.toDate = toDate; proto.toISOString = toISOString; proto.inspect = inspect; - if (typeof Symbol !== 'undefined' && Symbol.for != null) { - proto[Symbol.for('nodejs.util.inspect.custom')] = function () { - return 'Moment<' + this.format() + '>'; - }; + if (typeof Symbol !== "undefined" && Symbol.for != null) { + proto[Symbol.for("nodejs.util.inspect.custom")] = function () { + return "Moment<" + this.format() + ">"; + }; } proto.toJSON = toJSON; proto.toString = toString; @@ -4960,36 +4924,36 @@ proto.zoneAbbr = getZoneAbbr; proto.zoneName = getZoneName; proto.dates = deprecate( - 'dates accessor is deprecated. Use date instead.', - getSetDayOfMonth + "dates accessor is deprecated. Use date instead.", + getSetDayOfMonth, ); proto.months = deprecate( - 'months accessor is deprecated. Use month instead', - getSetMonth + "months accessor is deprecated. Use month instead", + getSetMonth, ); proto.years = deprecate( - 'years accessor is deprecated. Use year instead', - getSetYear + "years accessor is deprecated. Use year instead", + getSetYear, ); proto.zone = deprecate( - 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', - getSetZone + "moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", + getSetZone, ); proto.isDSTShifted = deprecate( - 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', - isDaylightSavingTimeShifted + "isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", + isDaylightSavingTimeShifted, ); function createUnix(input) { - return createLocal(input * 1000); + return createLocal(input * 1000); } function createInZone() { - return createLocal.apply(null, arguments).parseZone(); + return createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat(string) { - return string; + return string; } var proto$1 = Locale.prototype; @@ -5032,29 +4996,29 @@ proto$1.meridiem = localeMeridiem; function get$1(format, index, field, setter) { - var locale = getLocale(), - utc = createUTC().set(setter, index); - return locale[field](utc, format); + var locale = getLocale(), + utc = createUTC().set(setter, index); + return locale[field](utc, format); } function listMonthsImpl(format, index, field) { - if (isNumber(format)) { - index = format; - format = undefined; - } + if (isNumber(format)) { + index = format; + format = undefined; + } - format = format || ''; + format = format || ""; - if (index != null) { - return get$1(format, index, field, 'month'); - } + if (index != null) { + return get$1(format, index, field, "month"); + } - var i, - out = []; - for (i = 0; i < 12; i++) { - out[i] = get$1(format, i, field, 'month'); - } - return out; + var i, + out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, "month"); + } + return out; } // () @@ -5066,500 +5030,497 @@ // (true, fmt, 5) // (true, fmt) function listWeekdaysImpl(localeSorted, format, index, field) { - if (typeof localeSorted === 'boolean') { - if (isNumber(format)) { - index = format; - format = undefined; - } - - format = format || ''; - } else { - format = localeSorted; - index = format; - localeSorted = false; - - if (isNumber(format)) { - index = format; - format = undefined; - } - - format = format || ''; + if (typeof localeSorted === "boolean") { + if (isNumber(format)) { + index = format; + format = undefined; } - var locale = getLocale(), - shift = localeSorted ? locale._week.dow : 0, - i, - out = []; + format = format || ""; + } else { + format = localeSorted; + index = format; + localeSorted = false; - if (index != null) { - return get$1(format, (index + shift) % 7, field, 'day'); + if (isNumber(format)) { + index = format; + format = undefined; } - for (i = 0; i < 7; i++) { - out[i] = get$1(format, (i + shift) % 7, field, 'day'); - } - return out; + format = format || ""; + } + + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0, + i, + out = []; + + if (index != null) { + return get$1(format, (index + shift) % 7, field, "day"); + } + + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, "day"); + } + return out; } function listMonths(format, index) { - return listMonthsImpl(format, index, 'months'); + return listMonthsImpl(format, index, "months"); } function listMonthsShort(format, index) { - return listMonthsImpl(format, index, 'monthsShort'); + return listMonthsImpl(format, index, "monthsShort"); } function listWeekdays(localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); + return listWeekdaysImpl(localeSorted, format, index, "weekdays"); } function listWeekdaysShort(localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); + return listWeekdaysImpl(localeSorted, format, index, "weekdaysShort"); } function listWeekdaysMin(localeSorted, format, index) { - return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); + return listWeekdaysImpl(localeSorted, format, index, "weekdaysMin"); } - getSetGlobalLocale('en', { - eras: [ - { - since: '0001-01-01', - until: +Infinity, - offset: 1, - name: 'Anno Domini', - narrow: 'AD', - abbr: 'AD', - }, - { - since: '0000-12-31', - until: -Infinity, - offset: 1, - name: 'Before Christ', - narrow: 'BC', - abbr: 'BC', - }, - ], - dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, - ordinal: function (number) { - var b = number % 10, - output = - toInt((number % 100) / 10) === 1 - ? 'th' - : b === 1 - ? 'st' - : b === 2 - ? 'nd' - : b === 3 - ? 'rd' - : 'th'; - return number + output; + getSetGlobalLocale("en", { + eras: [ + { + since: "0001-01-01", + until: +Infinity, + offset: 1, + name: "Anno Domini", + narrow: "AD", + abbr: "AD", }, + { + since: "0000-12-31", + until: -Infinity, + offset: 1, + name: "Before Christ", + narrow: "BC", + abbr: "BC", + }, + ], + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal: function (number) { + var b = number % 10, + output = + toInt((number % 100) / 10) === 1 + ? "th" + : b === 1 + ? "st" + : b === 2 + ? "nd" + : b === 3 + ? "rd" + : "th"; + return number + output; + }, }); // Side effect imports hooks.lang = deprecate( - 'moment.lang is deprecated. Use moment.locale instead.', - getSetGlobalLocale + "moment.lang is deprecated. Use moment.locale instead.", + getSetGlobalLocale, ); hooks.langData = deprecate( - 'moment.langData is deprecated. Use moment.localeData instead.', - getLocale + "moment.langData is deprecated. Use moment.localeData instead.", + getLocale, ); var mathAbs = Math.abs; function abs() { - var data = this._data; + var data = this._data; - this._milliseconds = mathAbs(this._milliseconds); - this._days = mathAbs(this._days); - this._months = mathAbs(this._months); + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); - data.milliseconds = mathAbs(data.milliseconds); - data.seconds = mathAbs(data.seconds); - data.minutes = mathAbs(data.minutes); - data.hours = mathAbs(data.hours); - data.months = mathAbs(data.months); - data.years = mathAbs(data.years); + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); - return this; + return this; } function addSubtract$1(duration, input, value, direction) { - var other = createDuration(input, value); + var other = createDuration(input, value); - duration._milliseconds += direction * other._milliseconds; - duration._days += direction * other._days; - duration._months += direction * other._months; + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; - return duration._bubble(); + return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function add$1(input, value) { - return addSubtract$1(this, input, value, 1); + return addSubtract$1(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function subtract$1(input, value) { - return addSubtract$1(this, input, value, -1); + return addSubtract$1(this, input, value, -1); } function absCeil(number) { - if (number < 0) { - return Math.floor(number); - } else { - return Math.ceil(number); - } + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } } function bubble() { - var milliseconds = this._milliseconds, - days = this._days, - months = this._months, - data = this._data, - seconds, - minutes, - hours, - years, - monthsFromDays; + var milliseconds = this._milliseconds, + days = this._days, + months = this._months, + data = this._data, + seconds, + minutes, + hours, + years, + monthsFromDays; - // if we have a mix of positive and negative values, bubble down first - // check: https://github.com/moment/moment/issues/2166 - if ( - !( - (milliseconds >= 0 && days >= 0 && months >= 0) || - (milliseconds <= 0 && days <= 0 && months <= 0) - ) - ) { - milliseconds += absCeil(monthsToDays(months) + days) * 864e5; - days = 0; - months = 0; - } + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if ( + !( + (milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0) + ) + ) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } - // The following code bubbles up values, see the tests for - // examples of what that means. - data.milliseconds = milliseconds % 1000; + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; - seconds = absFloor(milliseconds / 1000); - data.seconds = seconds % 60; + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; - minutes = absFloor(seconds / 60); - data.minutes = minutes % 60; + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; - hours = absFloor(minutes / 60); - data.hours = hours % 24; + hours = absFloor(minutes / 60); + data.hours = hours % 24; - days += absFloor(hours / 24); + days += absFloor(hours / 24); - // convert days to months - monthsFromDays = absFloor(daysToMonths(days)); - months += monthsFromDays; - days -= absCeil(monthsToDays(monthsFromDays)); + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); - // 12 months -> 1 year - years = absFloor(months / 12); - months %= 12; + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; - data.days = days; - data.months = months; - data.years = years; + data.days = days; + data.months = months; + data.years = years; - return this; + return this; } function daysToMonths(days) { - // 400 years have 146097 days (taking into account leap year rules) - // 400 years have 12 months === 4800 - return (days * 4800) / 146097; + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return (days * 4800) / 146097; } function monthsToDays(months) { - // the reverse of daysToMonths - return (months * 146097) / 4800; + // the reverse of daysToMonths + return (months * 146097) / 4800; } function as(units) { - if (!this.isValid()) { - return NaN; - } - var days, - months, - milliseconds = this._milliseconds; + if (!this.isValid()) { + return NaN; + } + var days, + months, + milliseconds = this._milliseconds; - units = normalizeUnits(units); + units = normalizeUnits(units); - if (units === 'month' || units === 'quarter' || units === 'year') { - days = this._days + milliseconds / 864e5; - months = this._months + daysToMonths(days); - switch (units) { - case 'month': - return months; - case 'quarter': - return months / 3; - case 'year': - return months / 12; - } - } else { - // handle milliseconds separately because of floating point math errors (issue #1867) - days = this._days + Math.round(monthsToDays(this._months)); - switch (units) { - case 'week': - return days / 7 + milliseconds / 6048e5; - case 'day': - return days + milliseconds / 864e5; - case 'hour': - return days * 24 + milliseconds / 36e5; - case 'minute': - return days * 1440 + milliseconds / 6e4; - case 'second': - return days * 86400 + milliseconds / 1000; - // Math.floor prevents floating point math errors here - case 'millisecond': - return Math.floor(days * 864e5) + milliseconds; - default: - throw new Error('Unknown unit ' + units); - } + if (units === "month" || units === "quarter" || units === "year") { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + switch (units) { + case "month": + return months; + case "quarter": + return months / 3; + case "year": + return months / 12; } + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case "week": + return days / 7 + milliseconds / 6048e5; + case "day": + return days + milliseconds / 864e5; + case "hour": + return days * 24 + milliseconds / 36e5; + case "minute": + return days * 1440 + milliseconds / 6e4; + case "second": + return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case "millisecond": + return Math.floor(days * 864e5) + milliseconds; + default: + throw new Error("Unknown unit " + units); + } + } } // TODO: Use this.as('ms')? function valueOf$1() { - if (!this.isValid()) { - return NaN; - } - return ( - this._milliseconds + - this._days * 864e5 + - (this._months % 12) * 2592e6 + - toInt(this._months / 12) * 31536e6 - ); + if (!this.isValid()) { + return NaN; + } + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); } function makeAs(alias) { - return function () { - return this.as(alias); - }; + return function () { + return this.as(alias); + }; } - var asMilliseconds = makeAs('ms'), - asSeconds = makeAs('s'), - asMinutes = makeAs('m'), - asHours = makeAs('h'), - asDays = makeAs('d'), - asWeeks = makeAs('w'), - asMonths = makeAs('M'), - asQuarters = makeAs('Q'), - asYears = makeAs('y'); + var asMilliseconds = makeAs("ms"), + asSeconds = makeAs("s"), + asMinutes = makeAs("m"), + asHours = makeAs("h"), + asDays = makeAs("d"), + asWeeks = makeAs("w"), + asMonths = makeAs("M"), + asQuarters = makeAs("Q"), + asYears = makeAs("y"); function clone$1() { - return createDuration(this); + return createDuration(this); } function get$2(units) { - units = normalizeUnits(units); - return this.isValid() ? this[units + 's']() : NaN; + units = normalizeUnits(units); + return this.isValid() ? this[units + "s"]() : NaN; } function makeGetter(name) { - return function () { - return this.isValid() ? this._data[name] : NaN; - }; + return function () { + return this.isValid() ? this._data[name] : NaN; + }; } - var milliseconds = makeGetter('milliseconds'), - seconds = makeGetter('seconds'), - minutes = makeGetter('minutes'), - hours = makeGetter('hours'), - days = makeGetter('days'), - months = makeGetter('months'), - years = makeGetter('years'); + var milliseconds = makeGetter("milliseconds"), + seconds = makeGetter("seconds"), + minutes = makeGetter("minutes"), + hours = makeGetter("hours"), + days = makeGetter("days"), + months = makeGetter("months"), + years = makeGetter("years"); function weeks() { - return absFloor(this.days() / 7); + return absFloor(this.days() / 7); } var round = Math.round, - thresholds = { - ss: 44, // a few seconds to seconds - s: 45, // seconds to minute - m: 45, // minutes to hour - h: 22, // hours to day - d: 26, // days to month/week - w: null, // weeks to month - M: 11, // months to year - }; + thresholds = { + ss: 44, // a few seconds to seconds + s: 45, // seconds to minute + m: 45, // minutes to hour + h: 22, // hours to day + d: 26, // days to month/week + w: null, // weeks to month + M: 11, // months to year + }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { - return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) { - var duration = createDuration(posNegDuration).abs(), - seconds = round(duration.as('s')), - minutes = round(duration.as('m')), - hours = round(duration.as('h')), - days = round(duration.as('d')), - months = round(duration.as('M')), - weeks = round(duration.as('w')), - years = round(duration.as('y')), - a = - (seconds <= thresholds.ss && ['s', seconds]) || - (seconds < thresholds.s && ['ss', seconds]) || - (minutes <= 1 && ['m']) || - (minutes < thresholds.m && ['mm', minutes]) || - (hours <= 1 && ['h']) || - (hours < thresholds.h && ['hh', hours]) || - (days <= 1 && ['d']) || - (days < thresholds.d && ['dd', days]); + var duration = createDuration(posNegDuration).abs(), + seconds = round(duration.as("s")), + minutes = round(duration.as("m")), + hours = round(duration.as("h")), + days = round(duration.as("d")), + months = round(duration.as("M")), + weeks = round(duration.as("w")), + years = round(duration.as("y")), + a = + (seconds <= thresholds.ss && ["s", seconds]) || + (seconds < thresholds.s && ["ss", seconds]) || + (minutes <= 1 && ["m"]) || + (minutes < thresholds.m && ["mm", minutes]) || + (hours <= 1 && ["h"]) || + (hours < thresholds.h && ["hh", hours]) || + (days <= 1 && ["d"]) || + (days < thresholds.d && ["dd", days]); - if (thresholds.w != null) { - a = - a || - (weeks <= 1 && ['w']) || - (weeks < thresholds.w && ['ww', weeks]); - } - a = a || - (months <= 1 && ['M']) || - (months < thresholds.M && ['MM', months]) || - (years <= 1 && ['y']) || ['yy', years]; + if (thresholds.w != null) { + a = a || (weeks <= 1 && ["w"]) || (weeks < thresholds.w && ["ww", weeks]); + } + a = a || + (months <= 1 && ["M"]) || + (months < thresholds.M && ["MM", months]) || + (years <= 1 && ["y"]) || ["yy", years]; - a[2] = withoutSuffix; - a[3] = +posNegDuration > 0; - a[4] = locale; - return substituteTimeAgo.apply(null, a); + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); } // This function allows you to set the rounding function for relative time strings function getSetRelativeTimeRounding(roundingFunction) { - if (roundingFunction === undefined) { - return round; - } - if (typeof roundingFunction === 'function') { - round = roundingFunction; - return true; - } - return false; + if (roundingFunction === undefined) { + return round; + } + if (typeof roundingFunction === "function") { + round = roundingFunction; + return true; + } + return false; } // This function allows you to set a threshold for relative time strings function getSetRelativeTimeThreshold(threshold, limit) { - if (thresholds[threshold] === undefined) { - return false; - } - if (limit === undefined) { - return thresholds[threshold]; - } - thresholds[threshold] = limit; - if (threshold === 's') { - thresholds.ss = limit - 1; - } - return true; + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === "s") { + thresholds.ss = limit - 1; + } + return true; } function humanize(argWithSuffix, argThresholds) { - if (!this.isValid()) { - return this.localeData().invalidDate(); - } + if (!this.isValid()) { + return this.localeData().invalidDate(); + } - var withSuffix = false, - th = thresholds, - locale, - output; + var withSuffix = false, + th = thresholds, + locale, + output; - if (typeof argWithSuffix === 'object') { - argThresholds = argWithSuffix; - argWithSuffix = false; - } - if (typeof argWithSuffix === 'boolean') { - withSuffix = argWithSuffix; - } - if (typeof argThresholds === 'object') { - th = Object.assign({}, thresholds, argThresholds); - if (argThresholds.s != null && argThresholds.ss == null) { - th.ss = argThresholds.s - 1; - } + if (typeof argWithSuffix === "object") { + argThresholds = argWithSuffix; + argWithSuffix = false; + } + if (typeof argWithSuffix === "boolean") { + withSuffix = argWithSuffix; + } + if (typeof argThresholds === "object") { + th = Object.assign({}, thresholds, argThresholds); + if (argThresholds.s != null && argThresholds.ss == null) { + th.ss = argThresholds.s - 1; } + } - locale = this.localeData(); - output = relativeTime$1(this, !withSuffix, th, locale); + locale = this.localeData(); + output = relativeTime$1(this, !withSuffix, th, locale); - if (withSuffix) { - output = locale.pastFuture(+this, output); - } + if (withSuffix) { + output = locale.pastFuture(+this, output); + } - return locale.postformat(output); + return locale.postformat(output); } var abs$1 = Math.abs; function sign(x) { - return (x > 0) - (x < 0) || +x; + return (x > 0) - (x < 0) || +x; } function toISOString$1() { - // for ISO strings we do not use the normal bubbling rules: - // * milliseconds bubble up until they become hours - // * days do not bubble at all - // * months bubble up until they become years - // This is because there is no context-free conversion between hours and days - // (think of clock changes) - // and also not between days and months (28-31 days per month) - if (!this.isValid()) { - return this.localeData().invalidDate(); - } + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); + } - var seconds = abs$1(this._milliseconds) / 1000, - days = abs$1(this._days), - months = abs$1(this._months), - minutes, - hours, - years, - s, - total = this.asSeconds(), - totalSign, - ymSign, - daysSign, - hmsSign; + var seconds = abs$1(this._milliseconds) / 1000, + days = abs$1(this._days), + months = abs$1(this._months), + minutes, + hours, + years, + s, + total = this.asSeconds(), + totalSign, + ymSign, + daysSign, + hmsSign; - if (!total) { - // this is the same as C#'s (Noda) and python (isodate)... - // but not other JS (goog.date) - return 'P0D'; - } + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return "P0D"; + } - // 3600 seconds -> 60 minutes -> 1 hour - minutes = absFloor(seconds / 60); - hours = absFloor(minutes / 60); - seconds %= 60; - minutes %= 60; + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; - // 12 months -> 1 year - years = absFloor(months / 12); - months %= 12; + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; - // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js - s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, "") : ""; - totalSign = total < 0 ? '-' : ''; - ymSign = sign(this._months) !== sign(total) ? '-' : ''; - daysSign = sign(this._days) !== sign(total) ? '-' : ''; - hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; + totalSign = total < 0 ? "-" : ""; + ymSign = sign(this._months) !== sign(total) ? "-" : ""; + daysSign = sign(this._days) !== sign(total) ? "-" : ""; + hmsSign = sign(this._milliseconds) !== sign(total) ? "-" : ""; - return ( - totalSign + - 'P' + - (years ? ymSign + years + 'Y' : '') + - (months ? ymSign + months + 'M' : '') + - (days ? daysSign + days + 'D' : '') + - (hours || minutes || seconds ? 'T' : '') + - (hours ? hmsSign + hours + 'H' : '') + - (minutes ? hmsSign + minutes + 'M' : '') + - (seconds ? hmsSign + s + 'S' : '') - ); + return ( + totalSign + + "P" + + (years ? ymSign + years + "Y" : "") + + (months ? ymSign + months + "M" : "") + + (days ? daysSign + days + "D" : "") + + (hours || minutes || seconds ? "T" : "") + + (hours ? hmsSign + hours + "H" : "") + + (minutes ? hmsSign + minutes + "M" : "") + + (seconds ? hmsSign + s + "S" : "") + ); } var proto$2 = Duration.prototype; @@ -5598,30 +5559,30 @@ proto$2.localeData = localeData; proto$2.toIsoString = deprecate( - 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', - toISOString$1 + "toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", + toISOString$1, ); proto$2.lang = lang; // FORMATTING - addFormatToken('X', 0, 0, 'unix'); - addFormatToken('x', 0, 0, 'valueOf'); + addFormatToken("X", 0, 0, "unix"); + addFormatToken("x", 0, 0, "valueOf"); // PARSING - addRegexToken('x', matchSigned); - addRegexToken('X', matchTimestamp); - addParseToken('X', function (input, array, config) { - config._d = new Date(parseFloat(input) * 1000); + addRegexToken("x", matchSigned); + addRegexToken("X", matchTimestamp); + addParseToken("X", function (input, array, config) { + config._d = new Date(parseFloat(input) * 1000); }); - addParseToken('x', function (input, array, config) { - config._d = new Date(toInt(input)); + addParseToken("x", function (input, array, config) { + config._d = new Date(toInt(input)); }); //! moment.js - hooks.version = '2.29.0'; + hooks.version = "2.29.0"; setHookCallback(createLocal); @@ -5655,17 +5616,16 @@ // currently HTML5 input type only supports 24-hour formats hooks.HTML5_FMT = { - DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // - DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // - DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // - DATE: 'YYYY-MM-DD', // - TIME: 'HH:mm', // - TIME_SECONDS: 'HH:mm:ss', // - TIME_MS: 'HH:mm:ss.SSS', // - WEEK: 'GGGG-[W]WW', // - MONTH: 'YYYY-MM', // + DATETIME_LOCAL: "YYYY-MM-DDTHH:mm", // + DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss", // + DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS", // + DATE: "YYYY-MM-DD", // + TIME: "HH:mm", // + TIME_SECONDS: "HH:mm:ss", // + TIME_MS: "HH:mm:ss.SSS", // + WEEK: "GGGG-[W]WW", // + MONTH: "YYYY-MM", // }; return hooks; - -}))); \ No newline at end of file +}); diff --git a/changes.md b/changes.md index 05d5940..6f8f56c 100644 --- a/changes.md +++ b/changes.md @@ -29,3 +29,9 @@ - Created `MarkSeasonWatchedDialog` — dedicated dialog for marking a season as watched, replacing the old two-step EpisodeSeenEditDialog+ConfirmDialog flow - Added **Scatter Mode** toggle: distributes episodes across a date range (start → end) with an even spread, shows preview of days and max episodes/day - "Mark Season Watched" button is now always visible (not hidden when all episodes are watched) + +### Milestone 001.2 + +#### Frontend Changes + +- **TmdbPreviewPage**: Added redirect when entry is already in library — navigating to `/entry/tmdb/:type/:id` for an in-library entry now immediately redirects to `/entry/:id` (EntryDetailsPage) with `replace: true`, eliminating the extra "Already in Library — View" button step diff --git a/electron/pnpm-lock.yaml b/electron/pnpm-lock.yaml index 235d8d9..30217f1 100644 --- a/electron/pnpm-lock.yaml +++ b/electron/pnpm-lock.yaml @@ -8,42 +8,13 @@ importers: .: dependencies: - axios: - specifier: ^1.7.9 - version: 1.7.9 - body-parser: - specifier: ^1.20.3 - version: 1.20.3 - copyfiles: - specifier: ^2.4.1 - version: 2.4.1 - dotenv: - specifier: ^16.4.7 - version: 16.4.7 electron: specifier: ^34.0.1 version: 34.0.1 + devDependencies: electron-builder: specifier: ^25.1.8 version: 25.1.8(electron-builder-squirrel-windows@25.1.8) - express: - specifier: ^4.21.2 - version: 4.21.2 - multer: - specifier: 1.4.5-lts.1 - version: 1.4.5-lts.1 - mysql2: - specifier: ^3.12.0 - version: 3.12.0 - sequelize: - specifier: ^6.37.5 - version: 6.37.5(mysql2@3.12.0) - sharp: - specifier: ^0.33.5 - version: 0.33.5 - uuid: - specifier: ^11.0.5 - version: 11.0.5 packages: @@ -81,117 +52,9 @@ packages: resolution: {integrity: sha512-fKpv9kg4SPmt+hY7SVBnIYULE9QJl8L3sCfcBsnqbJwwBwAeTLokJ9TRt9y7bK0JAzIW2y78TVVjvnQEms/yyA==} engines: {node: '>=16.4'} - '@emnapi/runtime@1.3.1': - resolution: {integrity: sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==} - '@gar/promisify@1.1.3': resolution: {integrity: sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==} - '@img/sharp-darwin-arm64@0.33.5': - resolution: {integrity: sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [darwin] - - '@img/sharp-darwin-x64@0.33.5': - resolution: {integrity: sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [darwin] - - '@img/sharp-libvips-darwin-arm64@1.0.4': - resolution: {integrity: sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==} - cpu: [arm64] - os: [darwin] - - '@img/sharp-libvips-darwin-x64@1.0.4': - resolution: {integrity: sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==} - cpu: [x64] - os: [darwin] - - '@img/sharp-libvips-linux-arm64@1.0.4': - resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==} - cpu: [arm64] - os: [linux] - - '@img/sharp-libvips-linux-arm@1.0.5': - resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==} - cpu: [arm] - os: [linux] - - '@img/sharp-libvips-linux-s390x@1.0.4': - resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==} - cpu: [s390x] - os: [linux] - - '@img/sharp-libvips-linux-x64@1.0.4': - resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==} - cpu: [x64] - os: [linux] - - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==} - cpu: [arm64] - os: [linux] - - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==} - cpu: [x64] - os: [linux] - - '@img/sharp-linux-arm64@0.33.5': - resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [linux] - - '@img/sharp-linux-arm@0.33.5': - resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm] - os: [linux] - - '@img/sharp-linux-s390x@0.33.5': - resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [s390x] - os: [linux] - - '@img/sharp-linux-x64@0.33.5': - resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [linux] - - '@img/sharp-linuxmusl-arm64@0.33.5': - resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [linux] - - '@img/sharp-linuxmusl-x64@0.33.5': - resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [linux] - - '@img/sharp-wasm32@0.33.5': - resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [wasm32] - - '@img/sharp-win32-ia32@0.33.5': - resolution: {integrity: sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [ia32] - os: [win32] - - '@img/sharp-win32-x64@0.33.5': - resolution: {integrity: sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [win32] - '@isaacs/cliui@8.0.2': resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} engines: {node: '>=12'} @@ -259,9 +122,6 @@ packages: '@types/responselike@1.0.3': resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==} - '@types/validator@13.12.2': - resolution: {integrity: sha512-6SlHBzUW8Jhf3liqrGGXyTJSIFe4nqlJ5A5KaMZ2l/vbM3Wh3KSybots/wfWVzNLK4D1NZluDlSQIbIEPx6oyA==} - '@types/verror@1.10.10': resolution: {integrity: sha512-l4MM0Jppn18hb9xmM6wwD1uTdShpf9Pn80aXTStnK1C94gtPvJcV2FrDmbOQUAQfJ1cKZHktkQUDwEqaAKXMMg==} @@ -275,10 +135,6 @@ packages: abbrev@1.1.1: resolution: {integrity: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==} - accepts@1.3.8: - resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} - engines: {node: '>= 0.6'} - agent-base@6.0.2: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} @@ -329,9 +185,6 @@ packages: dmg-builder: 25.1.8 electron-builder-squirrel-windows: 25.1.8 - append-field@1.0.0: - resolution: {integrity: sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==} - aproba@2.0.0: resolution: {integrity: sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==} @@ -355,9 +208,6 @@ packages: argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} - array-flatten@1.1.1: - resolution: {integrity: sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==} - assert-plus@1.0.0: resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} engines: {node: '>=0.8'} @@ -380,13 +230,6 @@ packages: resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==} engines: {node: '>= 4.0.0'} - aws-ssl-profiles@1.1.2: - resolution: {integrity: sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==} - engines: {node: '>= 6.0.0'} - - axios@1.7.9: - resolution: {integrity: sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==} - balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} @@ -402,10 +245,6 @@ packages: bluebird@3.7.2: resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==} - body-parser@1.20.3: - resolution: {integrity: sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==} - engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} - boolean@3.2.0: resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==} deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. @@ -432,14 +271,6 @@ packages: builder-util@25.1.7: resolution: {integrity: sha512-7jPjzBwEGRbwNcep0gGNpLXG9P94VA3CPAZQCzxkFXiV2GMQKlziMbY//rXPI7WKfhsvGgFXjTcXdBEwgXw9ww==} - busboy@1.6.0: - resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==} - engines: {node: '>=10.16.0'} - - bytes@3.1.2: - resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} - engines: {node: '>= 0.8'} - cacache@16.1.3: resolution: {integrity: sha512-/+Emcj9DAXxX4cwlLmRI9c166RuL3w30zp4R7Joiv2cQTtTtA+jeuCAjH3ZlGnYS3tKENSrKhAzVVP9GVyzeYQ==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -452,14 +283,6 @@ packages: resolution: {integrity: sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==} engines: {node: '>=8'} - call-bind-apply-helpers@1.0.1: - resolution: {integrity: sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==} - engines: {node: '>= 0.4'} - - call-bound@1.0.3: - resolution: {integrity: sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==} - engines: {node: '>= 0.4'} - chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} @@ -491,9 +314,6 @@ packages: resolution: {integrity: sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==} engines: {node: '>=8'} - cliui@7.0.4: - resolution: {integrity: sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==} - cliui@8.0.1: resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} engines: {node: '>=12'} @@ -512,17 +332,10 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - color-string@1.9.1: - resolution: {integrity: sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==} - color-support@1.1.3: resolution: {integrity: sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==} hasBin: true - color@4.2.3: - resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} - engines: {node: '>=12.5.0'} - combined-stream@1.0.8: resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} engines: {node: '>= 0.8'} @@ -542,35 +355,12 @@ packages: concat-map@0.0.1: resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} - concat-stream@1.6.2: - resolution: {integrity: sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==} - engines: {'0': node >= 0.8} - config-file-ts@0.2.8-rc1: resolution: {integrity: sha512-GtNECbVI82bT4RiDIzBSVuTKoSHufnU7Ce7/42bkWZJZFLjmDF2WBpVsvRkhKCfKBnTBb3qZrBwPpFBU/Myvhg==} console-control-strings@1.1.0: resolution: {integrity: sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==} - content-disposition@0.5.4: - resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==} - engines: {node: '>= 0.6'} - - content-type@1.0.5: - resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} - engines: {node: '>= 0.6'} - - cookie-signature@1.0.6: - resolution: {integrity: sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==} - - cookie@0.7.1: - resolution: {integrity: sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==} - engines: {node: '>= 0.6'} - - copyfiles@2.4.1: - resolution: {integrity: sha512-fereAvAvxDrQDOXybk3Qu3dPbOoKoysFMWtkY3mv5BsL8//OSZVL5DCLYqgRfY5cWirgRzlC+WSrxp6Bo3eNZg==} - hasBin: true - core-util-is@1.0.2: resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==} @@ -593,14 +383,6 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} - debug@2.6.9: - resolution: {integrity: sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - debug@4.4.0: resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==} engines: {node: '>=6.0'} @@ -636,18 +418,6 @@ packages: delegates@1.0.0: resolution: {integrity: sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==} - denque@2.1.0: - resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==} - engines: {node: '>=0.10'} - - depd@2.0.0: - resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} - engines: {node: '>= 0.8'} - - destroy@1.2.0: - resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} - engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} - detect-libc@2.0.3: resolution: {integrity: sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==} engines: {node: '>=8'} @@ -675,19 +445,9 @@ packages: resolution: {integrity: sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==} engines: {node: '>=12'} - dottie@2.0.6: - resolution: {integrity: sha512-iGCHkfUc5kFekGiqhe8B/mdaurD+lakO9txNnTvKtA6PISrw86LgqHvRzWYPyoE2Ph5aMIrCw9/uko6XHTKCwA==} - - dunder-proto@1.0.1: - resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} - engines: {node: '>= 0.4'} - eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} - ee-first@1.1.1: - resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} - ejs@3.1.10: resolution: {integrity: sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==} engines: {node: '>=0.10.0'} @@ -715,14 +475,6 @@ packages: emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} - encodeurl@1.0.2: - resolution: {integrity: sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==} - engines: {node: '>= 0.8'} - - encodeurl@2.0.0: - resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} - engines: {node: '>= 0.8'} - encoding@0.1.13: resolution: {integrity: sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==} @@ -744,10 +496,6 @@ packages: resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} engines: {node: '>= 0.4'} - es-object-atoms@1.1.1: - resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} - engines: {node: '>= 0.4'} - es6-error@4.1.1: resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==} @@ -755,24 +503,13 @@ packages: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} - escape-html@1.0.3: - resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} - escape-string-regexp@4.0.0: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} - etag@1.8.1: - resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} - engines: {node: '>= 0.6'} - exponential-backoff@3.1.1: resolution: {integrity: sha512-dX7e/LHVJ6W3DE1MHWi9S1EYzDESENfLrYohG2G++ovZrYOkm4Knwa0mc1cn84xJOR4KEU0WSchhLbd0UklbHw==} - express@4.21.2: - resolution: {integrity: sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==} - engines: {node: '>= 0.10.0'} - extract-zip@2.0.1: resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==} engines: {node: '>= 10.17.0'} @@ -794,19 +531,6 @@ packages: filelist@1.0.4: resolution: {integrity: sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==} - finalhandler@1.3.1: - resolution: {integrity: sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==} - engines: {node: '>= 0.8'} - - follow-redirects@1.15.9: - resolution: {integrity: sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==} - engines: {node: '>=4.0'} - peerDependencies: - debug: '*' - peerDependenciesMeta: - debug: - optional: true - foreground-child@3.3.0: resolution: {integrity: sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==} engines: {node: '>=14'} @@ -815,14 +539,6 @@ packages: resolution: {integrity: sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==} engines: {node: '>= 6'} - forwarded@0.2.0: - resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} - engines: {node: '>= 0.6'} - - fresh@0.5.2: - resolution: {integrity: sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==} - engines: {node: '>= 0.6'} - fs-constants@1.0.0: resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} @@ -849,29 +565,15 @@ packages: fs.realpath@1.0.0: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} - function-bind@1.1.2: - resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - gauge@4.0.4: resolution: {integrity: sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} deprecated: This package is no longer supported. - generate-function@2.3.1: - resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==} - get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} - get-intrinsic@1.2.7: - resolution: {integrity: sha512-VW6Pxhsrk0KAOqs3WEd0klDiF/+V7gQOpAvY1jVU/LHmaD/kQO4523aiJuikX/QAKYiW6x8Jh+RJej1almdtCA==} - engines: {node: '>= 0.4'} - - get-proto@1.0.1: - resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} - engines: {node: '>= 0.4'} - get-stream@5.2.0: resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==} engines: {node: '>=8'} @@ -915,17 +617,9 @@ packages: has-property-descriptors@1.0.2: resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} - has-symbols@1.1.0: - resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} - engines: {node: '>= 0.4'} - has-unicode@2.0.1: resolution: {integrity: sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==} - hasown@2.0.2: - resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} - engines: {node: '>= 0.4'} - hosted-git-info@4.1.0: resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==} engines: {node: '>=10'} @@ -933,10 +627,6 @@ packages: http-cache-semantics@4.1.1: resolution: {integrity: sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==} - http-errors@2.0.0: - resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==} - engines: {node: '>= 0.8'} - http-proxy-agent@5.0.0: resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==} engines: {node: '>= 6'} @@ -965,10 +655,6 @@ packages: engines: {node: ^8.11.2 || >=10} os: [darwin] - iconv-lite@0.4.24: - resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==} - engines: {node: '>=0.10.0'} - iconv-lite@0.6.3: resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} engines: {node: '>=0.10.0'} @@ -987,10 +673,6 @@ packages: infer-owner@1.0.4: resolution: {integrity: sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==} - inflection@1.13.4: - resolution: {integrity: sha512-6I/HUDeYFfuNCVS3td055BaXBwKYuzw7K3ExVMStBowKo9oOAMJIXIHvdyR3iboTCp1b+1i5DSkIZTcwIktuDw==} - engines: {'0': node >= 0.4.0} - inflight@1.0.6: resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. @@ -1002,13 +684,6 @@ packages: resolution: {integrity: sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==} engines: {node: '>= 12'} - ipaddr.js@1.9.1: - resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} - engines: {node: '>= 0.10'} - - is-arrayish@0.3.2: - resolution: {integrity: sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==} - is-ci@3.0.1: resolution: {integrity: sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==} hasBin: true @@ -1024,16 +699,10 @@ packages: is-lambda@1.0.1: resolution: {integrity: sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==} - is-property@1.0.2: - resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==} - is-unicode-supported@0.1.0: resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} engines: {node: '>=10'} - isarray@0.0.1: - resolution: {integrity: sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==} - isarray@1.0.0: resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} @@ -1115,9 +784,6 @@ packages: resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} engines: {node: '>=10'} - long@5.2.4: - resolution: {integrity: sha512-qtzLbJE8hq7VabR3mISmVGtoXP8KGc2Z/AT8OuqlYD7JTR3oqrgwdjnk07wpj1twXxYmgDXgoKVWUG/fReSzHg==} - lowercase-keys@2.0.0: resolution: {integrity: sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==} engines: {node: '>=8'} @@ -1133,10 +799,6 @@ packages: resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==} engines: {node: '>=12'} - lru.min@1.1.1: - resolution: {integrity: sha512-FbAj6lXil6t8z4z3j0E5mfRlPzxkySotzUHwRXjlpRh10vc6AI6WN62ehZj82VG7M20rqogJ0GLwar2Xa05a8Q==} - engines: {bun: '>=1.0.0', deno: '>=1.30.0', node: '>=8.0.0'} - make-fetch-happen@10.2.1: resolution: {integrity: sha512-NgOPbRiaQM10DYXvN3/hhGVI2M5MtITFryzBGxHM5p4wnFxsVCbxkrBrDsk+EZ5OB4jEOT7AjDxtdF+KVEFT7w==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -1145,21 +807,6 @@ packages: resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==} engines: {node: '>=10'} - math-intrinsics@1.1.0: - resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} - engines: {node: '>= 0.4'} - - media-typer@0.3.0: - resolution: {integrity: sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==} - engines: {node: '>= 0.6'} - - merge-descriptors@1.0.3: - resolution: {integrity: sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==} - - methods@1.1.2: - resolution: {integrity: sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==} - engines: {node: '>= 0.6'} - mime-db@1.52.0: resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} engines: {node: '>= 0.6'} @@ -1168,11 +815,6 @@ packages: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} - mime@1.6.0: - resolution: {integrity: sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==} - engines: {node: '>=4'} - hasBin: true - mime@2.6.0: resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} engines: {node: '>=4.0.0'} @@ -1244,43 +886,14 @@ packages: resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==} engines: {node: '>= 8'} - mkdirp@0.5.6: - resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==} - hasBin: true - mkdirp@1.0.4: resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==} engines: {node: '>=10'} hasBin: true - moment-timezone@0.5.46: - resolution: {integrity: sha512-ZXm9b36esbe7OmdABqIWJuBBiLLwAjrN7CE+7sYdCCx82Nabt1wHDj8TVseS59QIlfFPbOoiBPm6ca9BioG4hw==} - - moment@2.30.1: - resolution: {integrity: sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==} - - ms@2.0.0: - resolution: {integrity: sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==} - ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - multer@1.4.5-lts.1: - resolution: {integrity: sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==} - engines: {node: '>= 6.0.0'} - - mysql2@3.12.0: - resolution: {integrity: sha512-C8fWhVysZoH63tJbX8d10IAoYCyXy4fdRFz2Ihrt9jtPILYynFEKUUzpp1U7qxzDc3tMbotvaBH+sl6bFnGZiw==} - engines: {node: '>= 8.0'} - - named-placeholders@1.1.3: - resolution: {integrity: sha512-eLoBxg6wE/rZkJPhU/xRX1WTpkFEwDJEN96oxFrTsqBdbT5ec295Q+CoHrL9IT0DipqKhmGcaZmwOt8OON5x1w==} - engines: {node: '>=12.0.0'} - - negotiator@0.6.3: - resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==} - engines: {node: '>= 0.6'} - negotiator@0.6.4: resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==} engines: {node: '>= 0.6'} @@ -1300,9 +913,6 @@ packages: engines: {node: ^12.13 || ^14.13 || >=16} hasBin: true - noms@0.0.0: - resolution: {integrity: sha512-lNDU9VJaOPxUmXcLb+HQFeUgQQPtMI24Gt6hgfuMHRJgMRHMF/qZ4HJD3GDru4sSw9IQl2jPjAYnQrdIeLbwow==} - nopt@6.0.0: resolution: {integrity: sha512-ZwLpbTgdhuZUnZzjd7nb1ZV+4DoiC6/sfiVKok72ym/4Tlf+DFdlHYmT2JPmcNNWV6Pi3SDf1kT+A4r9RTuT9g==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -1321,22 +931,10 @@ packages: engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} deprecated: This package is no longer supported. - object-assign@4.1.1: - resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} - engines: {node: '>=0.10.0'} - - object-inspect@1.13.3: - resolution: {integrity: sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==} - engines: {node: '>= 0.4'} - object-keys@1.1.1: resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} engines: {node: '>= 0.4'} - on-finished@2.4.1: - resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==} - engines: {node: '>= 0.8'} - once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} @@ -1363,10 +961,6 @@ packages: package-json-from-dist@1.0.1: resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} - parseurl@1.3.3: - resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} - engines: {node: '>= 0.8'} - path-is-absolute@1.0.1: resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} engines: {node: '>=0.10.0'} @@ -1379,9 +973,6 @@ packages: resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==} engines: {node: '>=16 || 14 >=14.18'} - path-to-regexp@0.1.12: - resolution: {integrity: sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==} - pe-library@0.4.1: resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==} engines: {node: '>=12', npm: '>=6'} @@ -1389,9 +980,6 @@ packages: pend@1.2.0: resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} - pg-connection-string@2.7.0: - resolution: {integrity: sha512-PI2W9mv53rXJQEOb8xNR8lH7Hr+EKa6oJa38zsK0S/ky2er16ios1wLKhZyxzD7jUReiWokc9WK5nxSnC7W1TA==} - plist@3.1.0: resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==} engines: {node: '>=10.4.0'} @@ -1415,13 +1003,6 @@ packages: resolution: {integrity: sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==} engines: {node: '>=10'} - proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} - engines: {node: '>= 0.10'} - - proxy-from-env@1.1.0: - resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} - pump@3.0.2: resolution: {integrity: sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw==} @@ -1429,29 +1010,14 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} - qs@6.13.0: - resolution: {integrity: sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==} - engines: {node: '>=0.6'} - quick-lru@5.1.1: resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} engines: {node: '>=10'} - range-parser@1.2.1: - resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==} - engines: {node: '>= 0.6'} - - raw-body@2.5.2: - resolution: {integrity: sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==} - engines: {node: '>= 0.8'} - read-binary-file-arch@1.0.6: resolution: {integrity: sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==} hasBin: true - readable-stream@1.0.34: - resolution: {integrity: sha512-ok1qVCJuRkNmvebYikljxJA/UEsKwLl2nI1OmaqAu4/UE+h0wKCHok4XkL/gvi39OacXvw59RJUOFUkDib2rHg==} - readable-stream@2.3.8: resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} @@ -1480,9 +1046,6 @@ packages: resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==} engines: {node: '>=8'} - retry-as-promised@7.0.4: - resolution: {integrity: sha512-XgmCoxKWkDofwH8WddD0w85ZfqYz+ZHlr5yo+3YUCfycWawU56T5ckWXsScsj5B8tqUcIG67DxXByo3VUgiAdA==} - retry@0.12.0: resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} engines: {node: '>= 4'} @@ -1523,68 +1086,13 @@ packages: engines: {node: '>=10'} hasBin: true - send@0.19.0: - resolution: {integrity: sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==} - engines: {node: '>= 0.8.0'} - - seq-queue@0.0.5: - resolution: {integrity: sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==} - - sequelize-pool@7.1.0: - resolution: {integrity: sha512-G9c0qlIWQSK29pR/5U2JF5dDQeqqHRragoyahj/Nx4KOOQ3CPPfzxnfqFPCSB7x5UgjOgnZ61nSxz+fjDpRlJg==} - engines: {node: '>= 10.0.0'} - - sequelize@6.37.5: - resolution: {integrity: sha512-10WA4poUb3XWnUROThqL2Apq9C2NhyV1xHPMZuybNMCucDsbbFuKg51jhmyvvAUyUqCiimwTZamc3AHhMoBr2Q==} - engines: {node: '>=10.0.0'} - peerDependencies: - ibm_db: '*' - mariadb: '*' - mysql2: '*' - oracledb: '*' - pg: '*' - pg-hstore: '*' - snowflake-sdk: '*' - sqlite3: '*' - tedious: '*' - peerDependenciesMeta: - ibm_db: - optional: true - mariadb: - optional: true - mysql2: - optional: true - oracledb: - optional: true - pg: - optional: true - pg-hstore: - optional: true - snowflake-sdk: - optional: true - sqlite3: - optional: true - tedious: - optional: true - serialize-error@7.0.1: resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==} engines: {node: '>=10'} - serve-static@1.16.2: - resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==} - engines: {node: '>= 0.8.0'} - set-blocking@2.0.0: resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==} - setprototypeof@1.2.0: - resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} - - sharp@0.33.5: - resolution: {integrity: sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -1593,22 +1101,6 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} - side-channel-list@1.0.0: - resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==} - engines: {node: '>= 0.4'} - - side-channel-map@1.0.1: - resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} - engines: {node: '>= 0.4'} - - side-channel-weakmap@1.0.2: - resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} - engines: {node: '>= 0.4'} - - side-channel@1.1.0: - resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} - engines: {node: '>= 0.4'} - signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} @@ -1616,9 +1108,6 @@ packages: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} - simple-swizzle@0.2.2: - resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==} - simple-update-notifier@2.0.0: resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==} engines: {node: '>=10'} @@ -1649,10 +1138,6 @@ packages: sprintf-js@1.1.3: resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==} - sqlstring@2.3.3: - resolution: {integrity: sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==} - engines: {node: '>= 0.6'} - ssri@9.0.1: resolution: {integrity: sha512-o57Wcn66jMQvfHG1FlYbWeZWW/dHZhJXjpIcTfXldXEk5nz5lStPo3mK0OJQfGR3RbZUlbISexbljkJzuEj/8Q==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} @@ -1661,14 +1146,6 @@ packages: resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==} engines: {node: '>= 6'} - statuses@2.0.1: - resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==} - engines: {node: '>= 0.8'} - - streamsearch@1.1.0: - resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==} - engines: {node: '>=10.0.0'} - string-width@4.2.3: resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} engines: {node: '>=8'} @@ -1677,9 +1154,6 @@ packages: resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} engines: {node: '>=12'} - string_decoder@0.10.31: - resolution: {integrity: sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ==} - string_decoder@1.1.1: resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==} @@ -1713,9 +1187,6 @@ packages: temp-file@3.4.0: resolution: {integrity: sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg==} - through2@2.0.5: - resolution: {integrity: sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==} - tmp-promise@3.0.3: resolution: {integrity: sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==} @@ -1723,30 +1194,13 @@ packages: resolution: {integrity: sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==} engines: {node: '>=14.14'} - toidentifier@1.0.1: - resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} - engines: {node: '>=0.6'} - - toposort-class@1.0.1: - resolution: {integrity: sha512-OsLcGGbYF3rMjPUf8oKktyvCiUxSbqMMS39m33MAjLTC1DVIH6x3WSt63/M77ihI09+Sdfk1AXvfhCEeUmC7mg==} - truncate-utf8-bytes@1.0.2: resolution: {integrity: sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==} - tslib@2.8.1: - resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} - type-fest@0.13.1: resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==} engines: {node: '>=10'} - type-is@1.6.18: - resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} - engines: {node: '>= 0.6'} - - typedarray@0.0.6: - resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==} - typescript@5.7.3: resolution: {integrity: sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==} engines: {node: '>=14.17'} @@ -1774,14 +1228,6 @@ packages: resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} engines: {node: '>= 10.0.0'} - unpipe@1.0.0: - resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} - engines: {node: '>= 0.8'} - - untildify@4.0.0: - resolution: {integrity: sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==} - engines: {node: '>=8'} - uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -1791,26 +1237,6 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - utils-merge@1.0.1: - resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==} - engines: {node: '>= 0.4.0'} - - uuid@11.0.5: - resolution: {integrity: sha512-508e6IcKLrhxKdBbcA2b4KQZlLVp2+J5UwQ6F7Drckkc5N9ZJwFa4TgWtsww9UG8fGHbm6gbV19TdM5pQ4GaIA==} - hasBin: true - - uuid@8.3.2: - resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==} - hasBin: true - - validator@13.12.0: - resolution: {integrity: sha512-c1Q0mCiPlgdTVVVIJIrBuxNicYE+t/7oKeI9MWLj3fh/uq2Pxh/3eeWbVZ4OcGW1TUf53At0njHw5SMdA3tmMg==} - engines: {node: '>= 0.10'} - - vary@1.1.2: - resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} - engines: {node: '>= 0.8'} - verror@1.10.1: resolution: {integrity: sha512-veufcmxri4e3XSrT0xwfUR7kguIkaxBeosDg00yDWhk49wdwkSUrvvsm7nc75e1PUyvIeZj6nS8VQRYz2/S4Xg==} engines: {node: '>=0.6.0'} @@ -1826,9 +1252,6 @@ packages: wide-align@1.1.5: resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==} - wkx@0.5.0: - resolution: {integrity: sha512-Xng/d4Ichh8uN4l0FToV/258EjMGU9MGcA0HV2d9B/ZpZB3lqQm7nkOdZdm5GhKtLLhAE7PiVQwN4eN+2YJJUg==} - wrap-ansi@7.0.0: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} @@ -1844,10 +1267,6 @@ packages: resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==} engines: {node: '>=8.0'} - xtend@4.0.2: - resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} - engines: {node: '>=0.4'} - y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} @@ -1855,18 +1274,10 @@ packages: yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} - yargs-parser@20.2.9: - resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} - engines: {node: '>=10'} - yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} - yargs@16.2.0: - resolution: {integrity: sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==} - engines: {node: '>=10'} - yargs@17.7.2: resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} engines: {node: '>=12'} @@ -1962,88 +1373,8 @@ snapshots: transitivePeerDependencies: - supports-color - '@emnapi/runtime@1.3.1': - dependencies: - tslib: 2.8.1 - optional: true - '@gar/promisify@1.1.3': {} - '@img/sharp-darwin-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.0.4 - optional: true - - '@img/sharp-darwin-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.0.4 - optional: true - - '@img/sharp-libvips-darwin-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-darwin-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linux-arm@1.0.5': - optional: true - - '@img/sharp-libvips-linux-s390x@1.0.4': - optional: true - - '@img/sharp-libvips-linux-x64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-arm64@1.0.4': - optional: true - - '@img/sharp-libvips-linuxmusl-x64@1.0.4': - optional: true - - '@img/sharp-linux-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.0.4 - optional: true - - '@img/sharp-linux-arm@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.0.5 - optional: true - - '@img/sharp-linux-s390x@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.0.4 - optional: true - - '@img/sharp-linux-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-arm64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 - optional: true - - '@img/sharp-linuxmusl-x64@0.33.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.0.4 - optional: true - - '@img/sharp-wasm32@0.33.5': - dependencies: - '@emnapi/runtime': 1.3.1 - optional: true - - '@img/sharp-win32-ia32@0.33.5': - optional: true - - '@img/sharp-win32-x64@0.33.5': - optional: true - '@isaacs/cliui@8.0.2': dependencies: string-width: 5.1.2 @@ -2128,8 +1459,6 @@ snapshots: dependencies: '@types/node': 20.17.16 - '@types/validator@13.12.2': {} - '@types/verror@1.10.10': optional: true @@ -2142,11 +1471,6 @@ snapshots: abbrev@1.1.1: {} - accepts@1.3.8: - dependencies: - mime-types: 2.1.35 - negotiator: 0.6.3 - agent-base@6.0.2: dependencies: debug: 4.4.0 @@ -2227,8 +1551,6 @@ snapshots: - bluebird - supports-color - append-field@1.0.0: {} - aproba@2.0.0: {} archiver-utils@2.1.0: @@ -2274,8 +1596,6 @@ snapshots: argparse@2.0.1: {} - array-flatten@1.1.1: {} - assert-plus@1.0.0: optional: true @@ -2290,16 +1610,6 @@ snapshots: at-least-node@1.0.0: {} - aws-ssl-profiles@1.1.2: {} - - axios@1.7.9: - dependencies: - follow-redirects: 1.15.9 - form-data: 4.0.1 - proxy-from-env: 1.1.0 - transitivePeerDependencies: - - debug - balanced-match@1.0.2: {} base64-js@1.5.1: {} @@ -2316,23 +1626,6 @@ snapshots: bluebird@3.7.2: {} - body-parser@1.20.3: - dependencies: - bytes: 3.1.2 - content-type: 1.0.5 - debug: 2.6.9 - depd: 2.0.0 - destroy: 1.2.0 - http-errors: 2.0.0 - iconv-lite: 0.4.24 - on-finished: 2.4.1 - qs: 6.13.0 - raw-body: 2.5.2 - type-is: 1.6.18 - unpipe: 1.0.0 - transitivePeerDependencies: - - supports-color - boolean@3.2.0: optional: true @@ -2382,12 +1675,6 @@ snapshots: transitivePeerDependencies: - supports-color - busboy@1.6.0: - dependencies: - streamsearch: 1.1.0 - - bytes@3.1.2: {} - cacache@16.1.3: dependencies: '@npmcli/fs': 2.1.2 @@ -2423,16 +1710,6 @@ snapshots: normalize-url: 6.1.0 responselike: 2.0.1 - call-bind-apply-helpers@1.0.1: - dependencies: - es-errors: 1.3.0 - function-bind: 1.1.2 - - call-bound@1.0.3: - dependencies: - call-bind-apply-helpers: 1.0.1 - get-intrinsic: 1.2.7 - chalk@4.1.2: dependencies: ansi-styles: 4.3.0 @@ -2458,12 +1735,6 @@ snapshots: string-width: 4.2.3 optional: true - cliui@7.0.4: - dependencies: - string-width: 4.2.3 - strip-ansi: 6.0.1 - wrap-ansi: 7.0.0 - cliui@8.0.1: dependencies: string-width: 4.2.3 @@ -2482,18 +1753,8 @@ snapshots: color-name@1.1.4: {} - color-string@1.9.1: - dependencies: - color-name: 1.1.4 - simple-swizzle: 0.2.2 - color-support@1.1.3: {} - color@4.2.3: - dependencies: - color-convert: 2.0.1 - color-string: 1.9.1 - combined-stream@1.0.8: dependencies: delayed-stream: 1.0.0 @@ -2511,13 +1772,6 @@ snapshots: concat-map@0.0.1: {} - concat-stream@1.6.2: - dependencies: - buffer-from: 1.1.2 - inherits: 2.0.4 - readable-stream: 2.3.8 - typedarray: 0.0.6 - config-file-ts@0.2.8-rc1: dependencies: glob: 10.4.5 @@ -2525,26 +1779,6 @@ snapshots: console-control-strings@1.1.0: {} - content-disposition@0.5.4: - dependencies: - safe-buffer: 5.2.1 - - content-type@1.0.5: {} - - cookie-signature@1.0.6: {} - - cookie@0.7.1: {} - - copyfiles@2.4.1: - dependencies: - glob: 7.2.3 - minimatch: 3.1.2 - mkdirp: 1.0.4 - noms: 0.0.0 - through2: 2.0.5 - untildify: 4.0.0 - yargs: 16.2.0 - core-util-is@1.0.2: optional: true @@ -2568,10 +1802,6 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 - debug@2.6.9: - dependencies: - ms: 2.0.0 - debug@4.4.0: dependencies: ms: 2.1.3 @@ -2604,12 +1834,6 @@ snapshots: delegates@1.0.0: {} - denque@2.1.0: {} - - depd@2.0.0: {} - - destroy@1.2.0: {} - detect-libc@2.0.3: {} detect-node@2.1.0: @@ -2653,18 +1877,8 @@ snapshots: dotenv@16.4.7: {} - dottie@2.0.6: {} - - dunder-proto@1.0.1: - dependencies: - call-bind-apply-helpers: 1.0.1 - es-errors: 1.3.0 - gopd: 1.2.0 - eastasianwidth@0.2.0: {} - ee-first@1.1.1: {} - ejs@3.1.10: dependencies: jake: 10.9.2 @@ -2721,10 +1935,6 @@ snapshots: emoji-regex@9.2.2: {} - encodeurl@1.0.2: {} - - encodeurl@2.0.0: {} - encoding@0.1.13: dependencies: iconv-lite: 0.6.3 @@ -2738,64 +1948,22 @@ snapshots: err-code@2.0.3: {} - es-define-property@1.0.1: {} + es-define-property@1.0.1: + optional: true - es-errors@1.3.0: {} - - es-object-atoms@1.1.1: - dependencies: - es-errors: 1.3.0 + es-errors@1.3.0: + optional: true es6-error@4.1.1: optional: true escalade@3.2.0: {} - escape-html@1.0.3: {} - escape-string-regexp@4.0.0: optional: true - etag@1.8.1: {} - exponential-backoff@3.1.1: {} - express@4.21.2: - dependencies: - accepts: 1.3.8 - array-flatten: 1.1.1 - body-parser: 1.20.3 - content-disposition: 0.5.4 - content-type: 1.0.5 - cookie: 0.7.1 - cookie-signature: 1.0.6 - debug: 2.6.9 - depd: 2.0.0 - encodeurl: 2.0.0 - escape-html: 1.0.3 - etag: 1.8.1 - finalhandler: 1.3.1 - fresh: 0.5.2 - http-errors: 2.0.0 - merge-descriptors: 1.0.3 - methods: 1.1.2 - on-finished: 2.4.1 - parseurl: 1.3.3 - path-to-regexp: 0.1.12 - proxy-addr: 2.0.7 - qs: 6.13.0 - range-parser: 1.2.1 - safe-buffer: 5.2.1 - send: 0.19.0 - serve-static: 1.16.2 - setprototypeof: 1.2.0 - statuses: 2.0.1 - type-is: 1.6.18 - utils-merge: 1.0.1 - vary: 1.1.2 - transitivePeerDependencies: - - supports-color - extract-zip@2.0.1: dependencies: debug: 4.4.0 @@ -2821,20 +1989,6 @@ snapshots: dependencies: minimatch: 5.1.6 - finalhandler@1.3.1: - dependencies: - debug: 2.6.9 - encodeurl: 2.0.0 - escape-html: 1.0.3 - on-finished: 2.4.1 - parseurl: 1.3.3 - statuses: 2.0.1 - unpipe: 1.0.0 - transitivePeerDependencies: - - supports-color - - follow-redirects@1.15.9: {} - foreground-child@3.3.0: dependencies: cross-spawn: 7.0.6 @@ -2846,10 +2000,6 @@ snapshots: combined-stream: 1.0.8 mime-types: 2.1.35 - forwarded@0.2.0: {} - - fresh@0.5.2: {} - fs-constants@1.0.0: {} fs-extra@10.1.0: @@ -2883,8 +2033,6 @@ snapshots: fs.realpath@1.0.0: {} - function-bind@1.1.2: {} - gauge@4.0.4: dependencies: aproba: 2.0.0 @@ -2896,30 +2044,8 @@ snapshots: strip-ansi: 6.0.1 wide-align: 1.1.5 - generate-function@2.3.1: - dependencies: - is-property: 1.0.2 - get-caller-file@2.0.5: {} - get-intrinsic@1.2.7: - dependencies: - call-bind-apply-helpers: 1.0.1 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - function-bind: 1.1.2 - get-proto: 1.0.1 - gopd: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.2 - math-intrinsics: 1.1.0 - - get-proto@1.0.1: - dependencies: - dunder-proto: 1.0.1 - es-object-atoms: 1.1.1 - get-stream@5.2.0: dependencies: pump: 3.0.2 @@ -2966,7 +2092,8 @@ snapshots: gopd: 1.2.0 optional: true - gopd@1.2.0: {} + gopd@1.2.0: + optional: true got@11.8.6: dependencies: @@ -2991,28 +2118,14 @@ snapshots: es-define-property: 1.0.1 optional: true - has-symbols@1.1.0: {} - has-unicode@2.0.1: {} - hasown@2.0.2: - dependencies: - function-bind: 1.1.2 - hosted-git-info@4.1.0: dependencies: lru-cache: 6.0.0 http-cache-semantics@4.1.1: {} - http-errors@2.0.0: - dependencies: - depd: 2.0.0 - inherits: 2.0.4 - setprototypeof: 1.2.0 - statuses: 2.0.1 - toidentifier: 1.0.1 - http-proxy-agent@5.0.0: dependencies: '@tootallnate/once': 2.0.0 @@ -3057,10 +2170,6 @@ snapshots: node-addon-api: 1.7.2 optional: true - iconv-lite@0.4.24: - dependencies: - safer-buffer: 2.1.2 - iconv-lite@0.6.3: dependencies: safer-buffer: 2.1.2 @@ -3073,8 +2182,6 @@ snapshots: infer-owner@1.0.4: {} - inflection@1.13.4: {} - inflight@1.0.6: dependencies: once: 1.4.0 @@ -3087,10 +2194,6 @@ snapshots: jsbn: 1.1.0 sprintf-js: 1.1.3 - ipaddr.js@1.9.1: {} - - is-arrayish@0.3.2: {} - is-ci@3.0.1: dependencies: ci-info: 3.9.0 @@ -3101,12 +2204,8 @@ snapshots: is-lambda@1.0.1: {} - is-property@1.0.2: {} - is-unicode-supported@0.1.0: {} - isarray@0.0.1: {} - isarray@1.0.0: {} isbinaryfile@4.0.10: {} @@ -3180,8 +2279,6 @@ snapshots: chalk: 4.1.2 is-unicode-supported: 0.1.0 - long@5.2.4: {} - lowercase-keys@2.0.0: {} lru-cache@10.4.3: {} @@ -3192,8 +2289,6 @@ snapshots: lru-cache@7.18.3: {} - lru.min@1.1.1: {} - make-fetch-happen@10.2.1: dependencies: agentkeepalive: 4.6.0 @@ -3221,22 +2316,12 @@ snapshots: escape-string-regexp: 4.0.0 optional: true - math-intrinsics@1.1.0: {} - - media-typer@0.3.0: {} - - merge-descriptors@1.0.3: {} - - methods@1.1.2: {} - mime-db@1.52.0: {} mime-types@2.1.35: dependencies: mime-db: 1.52.0 - mime@1.6.0: {} - mime@2.6.0: {} mimic-fn@2.1.0: {} @@ -3300,50 +2385,10 @@ snapshots: minipass: 3.3.6 yallist: 4.0.0 - mkdirp@0.5.6: - dependencies: - minimist: 1.2.8 - mkdirp@1.0.4: {} - moment-timezone@0.5.46: - dependencies: - moment: 2.30.1 - - moment@2.30.1: {} - - ms@2.0.0: {} - ms@2.1.3: {} - multer@1.4.5-lts.1: - dependencies: - append-field: 1.0.0 - busboy: 1.6.0 - concat-stream: 1.6.2 - mkdirp: 0.5.6 - object-assign: 4.1.1 - type-is: 1.6.18 - xtend: 4.0.2 - - mysql2@3.12.0: - dependencies: - aws-ssl-profiles: 1.1.2 - denque: 2.1.0 - generate-function: 2.3.1 - iconv-lite: 0.6.3 - long: 5.2.4 - lru.min: 1.1.1 - named-placeholders: 1.1.3 - seq-queue: 0.0.5 - sqlstring: 2.3.3 - - named-placeholders@1.1.3: - dependencies: - lru-cache: 7.18.3 - - negotiator@0.6.3: {} - negotiator@0.6.4: {} node-abi@3.73.0: @@ -3374,11 +2419,6 @@ snapshots: - bluebird - supports-color - noms@0.0.0: - dependencies: - inherits: 2.0.4 - readable-stream: 1.0.34 - nopt@6.0.0: dependencies: abbrev: 1.1.1 @@ -3394,17 +2434,9 @@ snapshots: gauge: 4.0.4 set-blocking: 2.0.0 - object-assign@4.1.1: {} - - object-inspect@1.13.3: {} - object-keys@1.1.1: optional: true - on-finished@2.4.1: - dependencies: - ee-first: 1.1.1 - once@1.4.0: dependencies: wrappy: 1.0.2 @@ -3437,8 +2469,6 @@ snapshots: package-json-from-dist@1.0.1: {} - parseurl@1.3.3: {} - path-is-absolute@1.0.1: {} path-key@3.1.1: {} @@ -3448,14 +2478,10 @@ snapshots: lru-cache: 10.4.3 minipass: 7.1.2 - path-to-regexp@0.1.12: {} - pe-library@0.4.1: {} pend@1.2.0: {} - pg-connection-string@2.7.0: {} - plist@3.1.0: dependencies: '@xmldom/xmldom': 0.8.10 @@ -3473,13 +2499,6 @@ snapshots: err-code: 2.0.3 retry: 0.12.0 - proxy-addr@2.0.7: - dependencies: - forwarded: 0.2.0 - ipaddr.js: 1.9.1 - - proxy-from-env@1.1.0: {} - pump@3.0.2: dependencies: end-of-stream: 1.4.4 @@ -3487,34 +2506,14 @@ snapshots: punycode@2.3.1: {} - qs@6.13.0: - dependencies: - side-channel: 1.1.0 - quick-lru@5.1.1: {} - range-parser@1.2.1: {} - - raw-body@2.5.2: - dependencies: - bytes: 3.1.2 - http-errors: 2.0.0 - iconv-lite: 0.4.24 - unpipe: 1.0.0 - read-binary-file-arch@1.0.6: dependencies: debug: 4.4.0 transitivePeerDependencies: - supports-color - readable-stream@1.0.34: - dependencies: - core-util-is: 1.0.3 - inherits: 2.0.4 - isarray: 0.0.1 - string_decoder: 0.10.31 - readable-stream@2.3.8: dependencies: core-util-is: 1.0.3 @@ -3552,8 +2551,6 @@ snapshots: onetime: 5.1.2 signal-exit: 3.0.7 - retry-as-promised@7.0.4: {} - retry@0.12.0: {} rimraf@3.0.2: @@ -3589,137 +2586,23 @@ snapshots: semver@7.6.3: {} - send@0.19.0: - dependencies: - debug: 2.6.9 - depd: 2.0.0 - destroy: 1.2.0 - encodeurl: 1.0.2 - escape-html: 1.0.3 - etag: 1.8.1 - fresh: 0.5.2 - http-errors: 2.0.0 - mime: 1.6.0 - ms: 2.1.3 - on-finished: 2.4.1 - range-parser: 1.2.1 - statuses: 2.0.1 - transitivePeerDependencies: - - supports-color - - seq-queue@0.0.5: {} - - sequelize-pool@7.1.0: {} - - sequelize@6.37.5(mysql2@3.12.0): - dependencies: - '@types/debug': 4.1.12 - '@types/validator': 13.12.2 - debug: 4.4.0 - dottie: 2.0.6 - inflection: 1.13.4 - lodash: 4.17.21 - moment: 2.30.1 - moment-timezone: 0.5.46 - pg-connection-string: 2.7.0 - retry-as-promised: 7.0.4 - semver: 7.6.3 - sequelize-pool: 7.1.0 - toposort-class: 1.0.1 - uuid: 8.3.2 - validator: 13.12.0 - wkx: 0.5.0 - optionalDependencies: - mysql2: 3.12.0 - transitivePeerDependencies: - - supports-color - serialize-error@7.0.1: dependencies: type-fest: 0.13.1 optional: true - serve-static@1.16.2: - dependencies: - encodeurl: 2.0.0 - escape-html: 1.0.3 - parseurl: 1.3.3 - send: 0.19.0 - transitivePeerDependencies: - - supports-color - set-blocking@2.0.0: {} - setprototypeof@1.2.0: {} - - sharp@0.33.5: - dependencies: - color: 4.2.3 - detect-libc: 2.0.3 - semver: 7.6.3 - optionalDependencies: - '@img/sharp-darwin-arm64': 0.33.5 - '@img/sharp-darwin-x64': 0.33.5 - '@img/sharp-libvips-darwin-arm64': 1.0.4 - '@img/sharp-libvips-darwin-x64': 1.0.4 - '@img/sharp-libvips-linux-arm': 1.0.5 - '@img/sharp-libvips-linux-arm64': 1.0.4 - '@img/sharp-libvips-linux-s390x': 1.0.4 - '@img/sharp-libvips-linux-x64': 1.0.4 - '@img/sharp-libvips-linuxmusl-arm64': 1.0.4 - '@img/sharp-libvips-linuxmusl-x64': 1.0.4 - '@img/sharp-linux-arm': 0.33.5 - '@img/sharp-linux-arm64': 0.33.5 - '@img/sharp-linux-s390x': 0.33.5 - '@img/sharp-linux-x64': 0.33.5 - '@img/sharp-linuxmusl-arm64': 0.33.5 - '@img/sharp-linuxmusl-x64': 0.33.5 - '@img/sharp-wasm32': 0.33.5 - '@img/sharp-win32-ia32': 0.33.5 - '@img/sharp-win32-x64': 0.33.5 - shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 shebang-regex@3.0.0: {} - side-channel-list@1.0.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.3 - - side-channel-map@1.0.1: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - get-intrinsic: 1.2.7 - object-inspect: 1.13.3 - - side-channel-weakmap@1.0.2: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - get-intrinsic: 1.2.7 - object-inspect: 1.13.3 - side-channel-map: 1.0.1 - - side-channel@1.1.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.3 - side-channel-list: 1.0.0 - side-channel-map: 1.0.1 - side-channel-weakmap: 1.0.2 - signal-exit@3.0.7: {} signal-exit@4.1.0: {} - simple-swizzle@0.2.2: - dependencies: - is-arrayish: 0.3.2 - simple-update-notifier@2.0.0: dependencies: semver: 7.6.3 @@ -3755,18 +2638,12 @@ snapshots: sprintf-js@1.1.3: {} - sqlstring@2.3.3: {} - ssri@9.0.1: dependencies: minipass: 3.3.6 stat-mode@1.0.0: {} - statuses@2.0.1: {} - - streamsearch@1.1.0: {} - string-width@4.2.3: dependencies: emoji-regex: 8.0.0 @@ -3779,8 +2656,6 @@ snapshots: emoji-regex: 9.2.2 strip-ansi: 7.1.0 - string_decoder@0.10.31: {} - string_decoder@1.1.1: dependencies: safe-buffer: 5.1.2 @@ -3829,38 +2704,19 @@ snapshots: async-exit-hook: 2.0.1 fs-extra: 10.1.0 - through2@2.0.5: - dependencies: - readable-stream: 2.3.8 - xtend: 4.0.2 - tmp-promise@3.0.3: dependencies: tmp: 0.2.3 tmp@0.2.3: {} - toidentifier@1.0.1: {} - - toposort-class@1.0.1: {} - truncate-utf8-bytes@1.0.2: dependencies: utf8-byte-length: 1.0.5 - tslib@2.8.1: - optional: true - type-fest@0.13.1: optional: true - type-is@1.6.18: - dependencies: - media-typer: 0.3.0 - mime-types: 2.1.35 - - typedarray@0.0.6: {} - typescript@5.7.3: {} undici-types@6.19.8: {} @@ -3879,10 +2735,6 @@ snapshots: universalify@2.0.1: {} - unpipe@1.0.0: {} - - untildify@4.0.0: {} - uri-js@4.4.1: dependencies: punycode: 2.3.1 @@ -3891,16 +2743,6 @@ snapshots: util-deprecate@1.0.2: {} - utils-merge@1.0.1: {} - - uuid@11.0.5: {} - - uuid@8.3.2: {} - - validator@13.12.0: {} - - vary@1.1.2: {} - verror@1.10.1: dependencies: assert-plus: 1.0.0 @@ -3920,10 +2762,6 @@ snapshots: dependencies: string-width: 4.2.3 - wkx@0.5.0: - dependencies: - '@types/node': 22.10.10 - wrap-ansi@7.0.0: dependencies: ansi-styles: 4.3.0 @@ -3940,26 +2778,12 @@ snapshots: xmlbuilder@15.1.1: {} - xtend@4.0.2: {} - y18n@5.0.8: {} yallist@4.0.0: {} - yargs-parser@20.2.9: {} - yargs-parser@21.1.1: {} - yargs@16.2.0: - dependencies: - cliui: 7.0.4 - escalade: 3.2.0 - get-caller-file: 2.0.5 - require-directory: 2.1.1 - string-width: 4.2.3 - y18n: 5.0.8 - yargs-parser: 20.2.9 - yargs@17.7.2: dependencies: cliui: 8.0.1 diff --git a/react_frontend/.prettierrc b/react_frontend/.prettierrc new file mode 100644 index 0000000..168791c --- /dev/null +++ b/react_frontend/.prettierrc @@ -0,0 +1,6 @@ +{ + "singleQuote": false, + "trailingComma": "all", + "tabWidth": 2, + "semi": true +} diff --git a/react_frontend/src/App.tsx b/react_frontend/src/App.tsx index a5de598..d322b4e 100644 --- a/react_frontend/src/App.tsx +++ b/react_frontend/src/App.tsx @@ -1,8 +1,8 @@ -import { RouterProvider } from 'react-router-dom'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { TooltipProvider } from '@/components/ui/tooltip'; -import { Toaster } from '@/components/ui/sonner'; -import { router } from './router'; +import { RouterProvider } from "react-router-dom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { Toaster } from "@/components/ui/sonner"; +import { router } from "./router"; const queryClient = new QueryClient({ defaultOptions: { @@ -19,7 +19,12 @@ export function App() { - + ); diff --git a/react_frontend/src/api/collections.ts b/react_frontend/src/api/collections.ts index 11df4b5..1623e88 100644 --- a/react_frontend/src/api/collections.ts +++ b/react_frontend/src/api/collections.ts @@ -1,11 +1,11 @@ -import { api } from '@/lib/api'; -import { normalizeCollection } from '@/lib/normalizers'; -import type { Collection } from '@/types'; +import { api } from "@/lib/api"; +import { normalizeCollection } from "@/lib/normalizers"; +import type { Collection } from "@/types"; export const collectionsApi = { getAll: () => api - .get('/collections') + .get("/collections") .then((r) => r.data.map(normalizeCollection)), getById: (id: number) => @@ -14,23 +14,26 @@ export const collectionsApi = { .then((r) => normalizeCollection(r.data)), create: (data: Partial) => - api.post('/collections', data).then((r) => r.data), + api.post("/collections", data).then((r) => r.data), update: (id: number, data: Partial) => - api.put(`/collections/${id}`, data).then((r) => normalizeCollection(r.data)), + api + .put(`/collections/${id}`, data) + .then((r) => normalizeCollection(r.data)), updateWithMedia: (id: number, formData: FormData) => api .put(`/collections/${id}`, formData, { - headers: { 'Content-Type': 'multipart/form-data' }, + headers: { "Content-Type": "multipart/form-data" }, }) .then((r) => normalizeCollection(r.data)), - delete: (id: number) => - api.delete(`/collections/${id}`).then((r) => r.data), + delete: (id: number) => api.delete(`/collections/${id}`).then((r) => r.data), getCollectionParts: (id: number) => - api.put(`/collections/${id}/parts`).then((r) => normalizeCollection(r.data)), + api + .put(`/collections/${id}/parts`) + .then((r) => normalizeCollection(r.data)), addEntry: (collectionId: number, entryId: number) => api diff --git a/react_frontend/src/api/entries.ts b/react_frontend/src/api/entries.ts index f372693..5a47b6d 100644 --- a/react_frontend/src/api/entries.ts +++ b/react_frontend/src/api/entries.ts @@ -1,19 +1,23 @@ -import { api } from '@/lib/api'; -import { normalizeEntry, normalizeCredit } from '@/lib/normalizers'; -import type { Entry, Credit, TmdbPreview } from '@/types'; +import { api } from "@/lib/api"; +import { normalizeEntry, normalizeCredit } from "@/lib/normalizers"; +import type { Entry, Credit, TmdbPreview } from "@/types"; export const entriesApi = { getAll: () => - api.get('/entries').then((r) => r.data.map(normalizeEntry)), + api.get("/entries").then((r) => r.data.map(normalizeEntry)), getById: (id: number) => api.get(`/entries/${id}`).then((r) => normalizeEntry(r.data)), create: (tmdb_id: number, is_tvserie: boolean) => - api.post('/entries', { tmdb_id, is_tvserie }).then((r) => normalizeEntry(r.data)), + api + .post("/entries", { tmdb_id, is_tvserie }) + .then((r) => normalizeEntry(r.data)), update: (id: number, data: Partial) => - api.put(`/entries/${id}`, { entryData: data }).then((r) => normalizeEntry(r.data)), + api + .put(`/entries/${id}`, { entryData: data }) + .then((r) => normalizeEntry(r.data)), updateRatings: ( id: number, @@ -23,39 +27,48 @@ export const entriesApi = { tmdb_rating?: number | null; imdb_rating?: number | null; rotten_tomatoes_rating?: number | null; - } - ) => api.put(`/entries/${id}/ratings`, { entryRatings: ratings }).then((r) => r.data), + }, + ) => + api + .put(`/entries/${id}/ratings`, { entryRatings: ratings }) + .then((r) => r.data), updateIds: ( id: number, - ids: { tmdb_id?: number; imdb_id?: string; tvdb_id?: number } + ids: { tmdb_id?: number; imdb_id?: string; tvdb_id?: number }, ) => api.put(`/entries/${id}/ids`, ids).then((r) => r.data), delete: (id: number) => api.delete(`/entries/${id}`).then((r) => r.data), refresh: (id: number) => - api.put(`/entries/${id}/refresh`).then((r) => normalizeEntry(r.data)), + api + .put(`/entries/${id}/refresh`) + .then((r) => normalizeEntry(r.data)), fetchCollection: (id: number) => api.put(`/entries/${id}/fetch-collection`).then((r) => r.data), getSeasons: (id: number) => - api.get(`/entries/${id}/seasons`).then((r) => Array.isArray(r.data) ? r.data : []), + api + .get(`/entries/${id}/seasons`) + .then((r) => (Array.isArray(r.data) ? r.data : [])), getCredits: (id: number) => api .get(`/entries/${id}/credits`) .then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])), - syncSeries: () => api.get('/entries/sync-series').then((r) => r.data), + syncSeries: () => api.get("/entries/sync-series").then((r) => r.data), - previewTmdb: (tmdbId: number, type: 'movie' | 'tv') => - api.get(`/entries/tmdb/preview/${type}/${tmdbId}`).then((r) => r.data), + previewTmdb: (tmdbId: number, type: "movie" | "tv") => + api + .get(`/entries/tmdb/preview/${type}/${tmdbId}`) + .then((r) => r.data), uploadMedia: (id: number, formData: FormData) => api .post(`/entries/${id}/media`, formData, { - headers: { 'Content-Type': 'multipart/form-data' }, + headers: { "Content-Type": "multipart/form-data" }, }) .then((r) => r.data), diff --git a/react_frontend/src/api/entry-seen.ts b/react_frontend/src/api/entry-seen.ts index cbbaceb..a7f8c04 100644 --- a/react_frontend/src/api/entry-seen.ts +++ b/react_frontend/src/api/entry-seen.ts @@ -1,8 +1,8 @@ -import { api } from '@/lib/api'; -import type { EntrySeen } from '@/types'; +import { api } from "@/lib/api"; +import type { EntrySeen } from "@/types"; export const entrySeenApi = { - getAll: () => api.get('/entry-seen').then((r) => r.data), + getAll: () => api.get("/entry-seen").then((r) => r.data), getById: (id: number) => api.get(`/entry-seen/${id}`).then((r) => r.data), @@ -16,8 +16,12 @@ export const entrySeenApi = { throw err; }), - create: (data: { entry_id: number; date_seen: string; seen_with?: string; accuracy?: string }) => - api.post('/entry-seen', data).then((r) => r.data), + create: (data: { + entry_id: number; + date_seen: string; + seen_with?: string; + accuracy?: string; + }) => api.post("/entry-seen", data).then((r) => r.data), update: (id: number, data: Partial) => api.put(`/entry-seen/${id}`, data).then((r) => r.data), diff --git a/react_frontend/src/api/episode-seen.ts b/react_frontend/src/api/episode-seen.ts index c2372c5..2f4ba2e 100644 --- a/react_frontend/src/api/episode-seen.ts +++ b/react_frontend/src/api/episode-seen.ts @@ -1,8 +1,8 @@ -import { api } from '@/lib/api'; -import type { EpisodeSeen } from '@/types'; +import { api } from "@/lib/api"; +import type { EpisodeSeen } from "@/types"; export const episodeSeenApi = { - getAll: () => api.get('/episode-seen').then((r) => r.data), + getAll: () => api.get("/episode-seen").then((r) => r.data), getById: (id: number) => api.get(`/episode-seen/${id}`).then((r) => r.data), @@ -22,11 +22,10 @@ export const episodeSeenApi = { date_seen: string; seen_with?: string; accuracy?: string; - }) => api.post('/episode-seen', data).then((r) => r.data), + }) => api.post("/episode-seen", data).then((r) => r.data), update: (id: number, data: Partial) => api.put(`/episode-seen/${id}`, data).then((r) => r.data), - delete: (id: number) => - api.delete(`/episode-seen/${id}`).then((r) => r.data), + delete: (id: number) => api.delete(`/episode-seen/${id}`).then((r) => r.data), }; diff --git a/react_frontend/src/api/episodes.ts b/react_frontend/src/api/episodes.ts index 832fdce..57f5a63 100644 --- a/react_frontend/src/api/episodes.ts +++ b/react_frontend/src/api/episodes.ts @@ -1,5 +1,5 @@ -import { api } from '@/lib/api'; -import type { Episode } from '@/types'; +import { api } from "@/lib/api"; +import type { Episode } from "@/types"; export const episodesApi = { getByMonth: (startDate: string, endDate: string) => diff --git a/react_frontend/src/api/people.ts b/react_frontend/src/api/people.ts index af98885..156da08 100644 --- a/react_frontend/src/api/people.ts +++ b/react_frontend/src/api/people.ts @@ -1,5 +1,5 @@ -import { api } from '@/lib/api'; -import type { People, Credit } from '@/types'; +import { api } from "@/lib/api"; +import type { People, Credit } from "@/types"; export interface TmdbFilmographyItem { id: number; @@ -8,7 +8,7 @@ export interface TmdbFilmographyItem { poster_path: string | null; release_date?: string; first_air_date?: string; - media_type: 'movie' | 'tv'; + media_type: "movie" | "tv"; character?: string; job?: string; department?: string; @@ -44,31 +44,38 @@ export interface PaginatedPeopleResponse { } export const peopleApi = { - getAll: () => api.get('/people').then((r) => r.data), + getAll: () => api.get("/people").then((r) => r.data), getAllPaginated: (page: number, limit: number, search?: string) => api - .get('/people', { params: { page, limit, ...(search ? { search } : {}) } }) + .get("/people", { + params: { page, limit, ...(search ? { search } : {}) }, + }) .then((r) => r.data), - getById: (id: number) => - api.get(`/people/${id}`).then((r) => r.data), + getById: (id: number) => api.get(`/people/${id}`).then((r) => r.data), getCredits: (id: number) => api.get(`/people/${id}/credits`).then((r) => r.data), getTmdbFilmography: (id: number) => - api.get(`/people/${id}/tmdb-filmography`).then((r) => r.data), + api + .get(`/people/${id}/tmdb-filmography`) + .then((r) => r.data), previewTmdb: (tmdbId: number) => - api.get(`/people/tmdb/preview/${tmdbId}`).then((r) => r.data), + api + .get(`/people/tmdb/preview/${tmdbId}`) + .then((r) => r.data), fetchByTmdbId: (tmdb_id: number, pinned = false) => - api.post('/people/fetch', { tmdb_id, pinned }).then((r) => r.data), + api.post("/people/fetch", { tmdb_id, pinned }).then((r) => r.data), update: (id: number, data: Partial) => api.put(`/people/${id}`, data).then((r) => r.data), search: (query: string) => - api.get('/people/search', { params: { query } }).then((r) => r.data), + api + .get("/people/search", { params: { query } }) + .then((r) => r.data), }; diff --git a/react_frontend/src/api/seasons.ts b/react_frontend/src/api/seasons.ts index 287520e..0d098a9 100644 --- a/react_frontend/src/api/seasons.ts +++ b/react_frontend/src/api/seasons.ts @@ -1,8 +1,8 @@ -import { api } from '@/lib/api'; -import type { Season, Episode } from '@/types'; +import { api } from "@/lib/api"; +import type { Season, Episode } from "@/types"; export const seasonsApi = { - getAll: () => api.get('/seasons').then((r) => r.data), + getAll: () => api.get("/seasons").then((r) => r.data), getById: (id: number) => api.get(`/seasons/${id}`).then((r) => r.data), @@ -11,7 +11,7 @@ export const seasonsApi = { api.get(`/seasons/${id}/episodes`).then((r) => r.data), create: (data: Partial) => - api.post('/seasons', data).then((r) => r.data), + api.post("/seasons", data).then((r) => r.data), update: (id: number, data: Partial) => api.put(`/seasons/${id}`, data).then((r) => r.data), diff --git a/react_frontend/src/api/settings.ts b/react_frontend/src/api/settings.ts index 345119b..631683d 100644 --- a/react_frontend/src/api/settings.ts +++ b/react_frontend/src/api/settings.ts @@ -1,9 +1,9 @@ -import { api } from '@/lib/api'; -import type { Settings } from '@/types'; +import { api } from "@/lib/api"; +import type { Settings } from "@/types"; export const settingsApi = { - get: () => api.get('/settings').then((r) => r.data), + get: () => api.get("/settings").then((r) => r.data), update: (data: Partial) => - api.put('/settings', data).then((r) => r.data), + api.put("/settings", data).then((r) => r.data), }; diff --git a/react_frontend/src/api/statistics.ts b/react_frontend/src/api/statistics.ts index e075b21..b27a6ef 100644 --- a/react_frontend/src/api/statistics.ts +++ b/react_frontend/src/api/statistics.ts @@ -1,4 +1,4 @@ -import { api } from '@/lib/api'; +import { api } from "@/lib/api"; export interface MonthlyCountItem { month: number; @@ -37,11 +37,17 @@ export interface AllTimeWatchTime { export const statisticsApi = { getAllTimeWatchTime: () => - api.get('/statistics/watch-time').then((r) => r.data), + api.get("/statistics/watch-time").then((r) => r.data), getYearlyWatchCount: (year: number) => - api.get(`/statistics/watch-count/year/${year}`).then((r) => r.data), + api + .get(`/statistics/watch-count/year/${year}`) + .then((r) => r.data), getYearlyWatchTime: (year: number) => - api.get(`/statistics/watch-time/year/${year}`).then((r) => r.data), + api + .get(`/statistics/watch-time/year/${year}`) + .then((r) => r.data), getWatchdayDistribution: () => - api.get('/statistics/watch-weekday').then((r) => r.data), + api + .get("/statistics/watch-weekday") + .then((r) => r.data), }; diff --git a/react_frontend/src/api/tmdb.ts b/react_frontend/src/api/tmdb.ts index 2860536..8e49d76 100644 --- a/react_frontend/src/api/tmdb.ts +++ b/react_frontend/src/api/tmdb.ts @@ -1,73 +1,73 @@ -import { api } from '@/lib/api'; -import type { TmdbEntry, TmdbPaginatedResponse, TmdbPerson } from '@/types'; +import { api } from "@/lib/api"; +import type { TmdbEntry, TmdbPaginatedResponse, TmdbPerson } from "@/types"; export const tmdbApi = { getPopularMovies: (page = 1) => api - .get>('/entries/tmdb/popular/movie', { + .get>("/entries/tmdb/popular/movie", { params: { page }, }) .then((r) => r.data), getPopularTv: (page = 1) => api - .get>('/entries/tmdb/popular/tv', { + .get>("/entries/tmdb/popular/tv", { params: { page }, }) .then((r) => r.data), getTrendingMovies: (page = 1) => api - .get>('/entries/tmdb/trending/movie', { + .get>("/entries/tmdb/trending/movie", { params: { page }, }) .then((r) => r.data), getTrendingTv: (page = 1) => api - .get>('/entries/tmdb/trending/tv', { + .get>("/entries/tmdb/trending/tv", { params: { page }, }) .then((r) => r.data), getTopRatedMovies: (page = 1) => api - .get>('/entries/tmdb/top-rated/movie', { + .get>("/entries/tmdb/top-rated/movie", { params: { page }, }) .then((r) => r.data), getTopRatedTv: (page = 1) => api - .get>('/entries/tmdb/top-rated/tv', { + .get>("/entries/tmdb/top-rated/tv", { params: { page }, }) .then((r) => r.data), getUpcomingMovies: (page = 1) => api - .get>('/entries/tmdb/upcoming/movie', { + .get>("/entries/tmdb/upcoming/movie", { params: { page }, }) .then((r) => r.data), search: (query: string, page = 1) => api - .get>('/entries/tmdb/search', { + .get>("/entries/tmdb/search", { params: { query, page }, }) .then((r) => r.data), getPopularPeople: (page = 1) => api - .get>('/people/tmdb/popular', { + .get>("/people/tmdb/popular", { params: { page }, }) .then((r) => r.data), searchPeople: (query: string, page = 1) => api - .get>('/people/tmdb/search', { + .get>("/people/tmdb/search", { params: { query, page }, }) .then((r) => r.data), diff --git a/react_frontend/src/components/CommandPalette.tsx b/react_frontend/src/components/CommandPalette.tsx index 1a55978..e434a0e 100644 --- a/react_frontend/src/components/CommandPalette.tsx +++ b/react_frontend/src/components/CommandPalette.tsx @@ -1,6 +1,6 @@ -import { useState, useEffect, useRef, useCallback, useMemo } from 'react'; -import { useNavigate } from 'react-router-dom'; -import { useQuery } from '@tanstack/react-query'; +import { useState, useEffect, useRef, useCallback, useMemo } from "react"; +import { useNavigate } from "react-router-dom"; +import { useQuery } from "@tanstack/react-query"; import { Search, Film, @@ -16,22 +16,22 @@ import { ArrowDown, CornerDownLeft, ArrowRight, -} from 'lucide-react'; -import { tmdbApi } from '@/api/tmdb'; -import { useLibraryStore } from '@/stores/useLibraryStore'; -import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore'; -import { useCreateEntry } from '@/hooks/useEntries'; -import { getTmdbImageUrl } from '@/lib/api'; -import { cn } from '@/lib/utils'; -import type { TmdbEntry } from '@/types'; +} from "lucide-react"; +import { tmdbApi } from "@/api/tmdb"; +import { useLibraryStore } from "@/stores/useLibraryStore"; +import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore"; +import { useCreateEntry } from "@/hooks/useEntries"; +import { getTmdbImageUrl } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import type { TmdbEntry } from "@/types"; interface CommandItem { id: string; - type: 'command' | 'library' | 'tmdb'; + type: "command" | "library" | "tmdb"; title: string; subtitle?: string; year?: string; - mediaType?: 'movie' | 'tv'; + mediaType?: "movie" | "tv"; posterPath?: string | null; icon?: React.ReactNode; inLibrary?: boolean; @@ -41,23 +41,58 @@ interface CommandItem { } const NAVIGATION_COMMANDS: CommandItem[] = [ - { id: 'cmd-library', type: 'command', title: 'Go to Library', icon: }, - { id: 'cmd-watchlist', type: 'command', title: 'Go to Watchlist', icon: }, - { id: 'cmd-stats', type: 'command', title: 'Go to Statistics', icon: }, - { id: 'cmd-calendar', type: 'command', title: 'Go to Calendar', icon: }, - { id: 'cmd-people', type: 'command', title: 'Go to People', icon: }, - { id: 'cmd-settings', type: 'command', title: 'Go to Settings', icon: }, - { id: 'cmd-favorites', type: 'command', title: 'Go to Favorites', icon: }, + { + id: "cmd-library", + type: "command", + title: "Go to Library", + icon: , + }, + { + id: "cmd-watchlist", + type: "command", + title: "Go to Watchlist", + icon: , + }, + { + id: "cmd-stats", + type: "command", + title: "Go to Statistics", + icon: , + }, + { + id: "cmd-calendar", + type: "command", + title: "Go to Calendar", + icon: , + }, + { + id: "cmd-people", + type: "command", + title: "Go to People", + icon: , + }, + { + id: "cmd-settings", + type: "command", + title: "Go to Settings", + icon: , + }, + { + id: "cmd-favorites", + type: "command", + title: "Go to Favorites", + icon: , + }, ]; const COMMAND_ROUTES: Record = { - 'cmd-library': '/library', - 'cmd-watchlist': '/watchlist', - 'cmd-stats': '/dashboard', - 'cmd-calendar': '/calendar', - 'cmd-people': '/people', - 'cmd-settings': '/settings', - 'cmd-favorites': '/library?filter=favorites', + "cmd-library": "/library", + "cmd-watchlist": "/watchlist", + "cmd-stats": "/dashboard", + "cmd-calendar": "/calendar", + "cmd-people": "/people", + "cmd-settings": "/settings", + "cmd-favorites": "/library?filter=favorites", }; export function CommandPalette() { @@ -68,8 +103,8 @@ export function CommandPalette() { const inputRef = useRef(null); const listRef = useRef(null); - const [query, setQuery] = useState(''); - const [debouncedQuery, setDebouncedQuery] = useState(''); + const [query, setQuery] = useState(""); + const [debouncedQuery, setDebouncedQuery] = useState(""); const [selectedIndex, setSelectedIndex] = useState(0); // Debounce search query @@ -81,8 +116,8 @@ export function CommandPalette() { // Focus input when opened useEffect(() => { if (isOpen) { - setQuery(''); - setDebouncedQuery(''); + setQuery(""); + setDebouncedQuery(""); setSelectedIndex(0); setTimeout(() => inputRef.current?.focus(), 50); } @@ -90,7 +125,7 @@ export function CommandPalette() { // TMDB search const { data: tmdbResults, isFetching: tmdbLoading } = useQuery({ - queryKey: ['command-palette', 'tmdb', debouncedQuery], + queryKey: ["command-palette", "tmdb", debouncedQuery], queryFn: () => tmdbApi.search(debouncedQuery, 1), enabled: debouncedQuery.length > 1, staleTime: 60 * 1000, @@ -98,7 +133,16 @@ export function CommandPalette() { // Build library TMDB ID index for fast lookups const libraryTmdbIndex = useMemo(() => { - const index = new Map(); + const index = new Map< + number, + { + id: number; + title: string; + is_tvseries: boolean; + poster_path: string | null; + rating: number | null; + } + >(); libraryEntries.forEach((entry) => { if (entry.entryIds?.tmdb_id) { index.set(entry.entryIds.tmdb_id, { @@ -122,10 +166,10 @@ export function CommandPalette() { if (entry.title.toLowerCase().includes(lower)) { results.push({ id: `lib-${entry.id}`, - type: 'library', + type: "library", title: entry.title, year: entry.release_date?.slice(0, 4), - mediaType: entry.is_tvseries ? 'tv' : 'movie', + mediaType: entry.is_tvseries ? "tv" : "movie", posterPath: entry.poster_path, inLibrary: true, libraryId: entry.id, @@ -145,13 +189,13 @@ export function CommandPalette() { .filter((r: TmdbEntry) => !libraryTmdbIndex.has(r.id)) .slice(0, 8) .map((r: TmdbEntry) => { - const mediaType = r.media_type === 'tv' || r.name ? 'tv' : 'movie'; - const title = r.title || r.name || 'Unknown'; + const mediaType = r.media_type === "tv" || r.name ? "tv" : "movie"; + const title = r.title || r.name || "Unknown"; const year = (r.release_date || r.first_air_date)?.slice(0, 4); return { id: `tmdb-${r.id}`, - type: 'tmdb' as const, + type: "tmdb" as const, title, year, mediaType, @@ -167,7 +211,9 @@ export function CommandPalette() { const filteredCommands = useMemo((): CommandItem[] => { if (!query.trim()) return NAVIGATION_COMMANDS; const lower = query.toLowerCase(); - return NAVIGATION_COMMANDS.filter((c) => c.title.toLowerCase().includes(lower)); + return NAVIGATION_COMMANDS.filter((c) => + c.title.toLowerCase().includes(lower), + ); }, [query]); // Recently viewed items (shown when no query) @@ -175,7 +221,7 @@ export function CommandPalette() { if (query.trim()) return []; return recentlyViewed.map((r) => ({ id: `recent-${r.id}`, - type: (r.libraryId ? 'library' : 'tmdb') as 'library' | 'tmdb', + type: (r.libraryId ? "library" : "tmdb") as "library" | "tmdb", title: r.title, mediaType: r.type, posterPath: r.poster_path, @@ -187,7 +233,12 @@ export function CommandPalette() { // All items combined const allItems = useMemo(() => { - return [...filteredCommands, ...localResults, ...tmdbItems, ...(query ? [] : recentItems)]; + return [ + ...filteredCommands, + ...localResults, + ...tmdbItems, + ...(query ? [] : recentItems), + ]; }, [filteredCommands, localResults, tmdbItems, recentItems, query]); // Keep selected index in bounds @@ -199,13 +250,15 @@ export function CommandPalette() { // Scroll selected item into view useEffect(() => { - const el = listRef.current?.querySelector(`[data-index="${selectedIndex}"]`); - el?.scrollIntoView({ block: 'nearest' }); + const el = listRef.current?.querySelector( + `[data-index="${selectedIndex}"]`, + ); + el?.scrollIntoView({ block: "nearest" }); }, [selectedIndex]); const handleSelect = useCallback( (item: CommandItem, quickAdd = false) => { - if (item.type === 'command') { + if (item.type === "command") { const route = COMMAND_ROUTES[item.id]; if (route) navigate(route); close(); @@ -220,13 +273,13 @@ export function CommandPalette() { if (quickAdd && item.tmdbId && item.mediaType) { createEntry.mutate( - { tmdb_id: item.tmdbId, is_tvserie: item.mediaType === 'tv' }, + { tmdb_id: item.tmdbId, is_tvserie: item.mediaType === "tv" }, { onSuccess: (entry) => { navigate(`/entry/${entry.id}`); close(); }, - } + }, ); return; } @@ -237,39 +290,42 @@ export function CommandPalette() { close(); } }, - [navigate, close, createEntry] + [navigate, close, createEntry], ); const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { switch (e.key) { - case 'ArrowDown': + case "ArrowDown": e.preventDefault(); setSelectedIndex((i) => Math.min(i + 1, allItems.length - 1)); break; - case 'ArrowUp': + case "ArrowUp": e.preventDefault(); setSelectedIndex((i) => Math.max(i - 1, 0)); break; - case 'Enter': { + case "Enter": { e.preventDefault(); const item = allItems[selectedIndex]; if (item) handleSelect(item, e.shiftKey); break; } - case 'Escape': + case "Escape": e.preventDefault(); close(); break; } }, - [allItems, selectedIndex, handleSelect, close] + [allItems, selectedIndex, handleSelect, close], ); if (!isOpen) return null; return ( -
+
{/* Backdrop */}
@@ -304,7 +360,7 @@ export function CommandPalette() { {filteredCommands.length > 0 && (
- {query ? 'Commands' : 'Quick Actions'} + {query ? "Commands" : "Quick Actions"}
{filteredCommands.map((item, i) => { const idx = i; @@ -346,7 +402,9 @@ export function CommandPalette() { {localResults.length > 0 && (
- Library + + Library +
@@ -447,25 +512,29 @@ function ResultRow({
{/* Poster or icon */} - {item.type === 'command' ? ( + {item.type === "command" ? (
{item.icon}
) : item.posterPath ? ( ) : (
- {item.mediaType === 'tv' ? : } + {item.mediaType === "tv" ? ( + + ) : ( + + )}
)} @@ -478,9 +547,11 @@ function ResultRow({
{item.year && {item.year}} {item.mediaType && ( - {item.mediaType === 'tv' ? 'TV Series' : 'Movie'} + + {item.mediaType === "tv" ? "TV Series" : "Movie"} + )} - {item.rating != null && item.type !== 'command' && ( + {item.rating != null && item.type !== "command" && ( {item.rating} diff --git a/react_frontend/src/components/collections/CollectionsGrid.tsx b/react_frontend/src/components/collections/CollectionsGrid.tsx index 5bfd5df..bdc1594 100644 --- a/react_frontend/src/components/collections/CollectionsGrid.tsx +++ b/react_frontend/src/components/collections/CollectionsGrid.tsx @@ -1,8 +1,8 @@ -import { useCallback, useRef, useEffect } from 'react'; -import { Link } from 'react-router-dom'; -import { getCollectionPosterUrl } from '@/lib/media-utils'; -import { Skeleton } from '@/components/ui/skeleton'; -import type { Collection } from '@/types'; +import { useCallback, useRef, useEffect } from "react"; +import { Link } from "react-router-dom"; +import { getCollectionPosterUrl } from "@/lib/media-utils"; +import { Skeleton } from "@/components/ui/skeleton"; +import type { Collection } from "@/types"; interface CollectionCardProps { collection: Collection; @@ -61,7 +61,7 @@ export function CollectionsGrid({ }); if (node) observerRef.current.observe(node); }, - [isLoading, hasMore, onLoadMore] + [isLoading, hasMore, onLoadMore], ); useEffect(() => { diff --git a/react_frontend/src/components/dashboard/CouchDayChart.tsx b/react_frontend/src/components/dashboard/CouchDayChart.tsx index 074a11a..7e8f169 100644 --- a/react_frontend/src/components/dashboard/CouchDayChart.tsx +++ b/react_frontend/src/components/dashboard/CouchDayChart.tsx @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from "react"; import { BarChart, Bar, @@ -8,30 +8,37 @@ import { Tooltip, Cell, ResponsiveContainer, -} from 'recharts'; -import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; -import { Skeleton } from '@/components/ui/skeleton'; -import { useWatchdayDistribution } from '@/hooks/useStatistics'; -import type { WatchdayItem } from '@/api/statistics'; +} from "recharts"; +import { + Card, + CardContent, + CardHeader, + CardTitle, + CardDescription, +} from "@/components/ui/card"; +import { Skeleton } from "@/components/ui/skeleton"; +import { useWatchdayDistribution } from "@/hooks/useStatistics"; +import type { WatchdayItem } from "@/api/statistics"; // DAYOFWEEK: MySQL returns 1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri, 7=Sat // We display Mon–Sun const DAY_ORDER = [2, 3, 4, 5, 6, 7, 1]; const DAY_LABELS: Record = { - 1: 'Sun', - 2: 'Mon', - 3: 'Tue', - 4: 'Wed', - 5: 'Thu', - 6: 'Fri', - 7: 'Sat', + 1: "Sun", + 2: "Mon", + 3: "Tue", + 4: "Wed", + 5: "Thu", + 6: "Fri", + 7: "Sat", }; function buildChartData(episodes: WatchdayItem[], movies: WatchdayItem[]) { return DAY_ORDER.map((dayNum) => { const ep = episodes.find((x) => Number(x.day) === dayNum); const mv = movies.find((x) => Number(x.day) === dayNum); - const total = (ep ? parseInt(ep.count, 10) : 0) + (mv ? parseInt(mv.count, 10) : 0); + const total = + (ep ? parseInt(ep.count, 10) : 0) + (mv ? parseInt(mv.count, 10) : 0); return { day: DAY_LABELS[dayNum], total, dayNum }; }); } @@ -47,16 +54,18 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) { return (

{day}

-

{total} {total === 1 ? 'watch' : 'watches'}

+

+ {total} {total === 1 ? "watch" : "watches"} +

); } @@ -71,7 +80,10 @@ export function CouchDayChart() { const peakDay = useMemo(() => { if (!chartData.length) return null; - return chartData.reduce((max, d) => (d.total > max.total ? d : max), chartData[0]); + return chartData.reduce( + (max, d) => (d.total > max.total ? d : max), + chartData[0], + ); }, [chartData]); const maxTotal = Math.max(...chartData.map((d) => d.total), 1); @@ -96,29 +108,39 @@ export function CouchDayChart() { ) : ( - - + + - } cursor={{ fill: 'var(--color-accent)' }} /> + } + cursor={{ fill: "var(--color-accent)" }} + /> {chartData.map((entry) => ( 0 - ? 'var(--color-chart-4)' - : 'var(--color-chart-1)' + ? "var(--color-chart-4)" + : "var(--color-chart-1)" } opacity={entry.total === 0 ? 0.3 : 1} /> diff --git a/react_frontend/src/components/dashboard/LibraryGrowthChart.tsx b/react_frontend/src/components/dashboard/LibraryGrowthChart.tsx index 099f122..cb69874 100644 --- a/react_frontend/src/components/dashboard/LibraryGrowthChart.tsx +++ b/react_frontend/src/components/dashboard/LibraryGrowthChart.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react'; +import { useMemo, useState } from "react"; import { AreaChart, Area, @@ -7,15 +7,37 @@ import { CartesianGrid, Tooltip, ResponsiveContainer, -} from 'recharts'; -import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; -import { useLibraryEntries } from '@/stores/useLibraryStore'; +} from "recharts"; +import { + Card, + CardContent, + CardHeader, + CardTitle, + CardDescription, +} from "@/components/ui/card"; +import { useLibraryEntries } from "@/stores/useLibraryStore"; -const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +const MONTH_LABELS = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", +]; interface CustomTooltipProps { active?: boolean; - payload?: { value: number; payload: { month: string; count: number; cumulative: number } }[]; + payload?: { + value: number; + payload: { month: string; count: number; cumulative: number }; + }[]; } function CustomTooltip({ active, payload }: CustomTooltipProps) { @@ -24,17 +46,19 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) { return (

{d.month}

-

+{d.count} added

-

{d.cumulative} total

+

+{d.count} added

+

+ {d.cumulative} total +

); } @@ -43,8 +67,7 @@ export function LibraryGrowthChart() { const allEntries = useLibraryEntries(); const currentYear = new Date().getFullYear(); - const getEntryDate = (e: { createdAt?: string }) => - e.createdAt || null; + const getEntryDate = (e: { createdAt?: string }) => e.createdAt || null; const years = useMemo(() => { const set = new Set(); @@ -56,16 +79,17 @@ export function LibraryGrowthChart() { return Array.from(set).sort((a, b) => b - a); }, [allEntries, currentYear]); - const [year, setYear] = useState('all'); + const [year, setYear] = useState("all"); // Ensure selected year is always valid - const effectiveYear = year === 'all' ? 'all' : (years.includes(year) ? year : years[0]); + const effectiveYear = + year === "all" ? "all" : years.includes(year) ? year : years[0]; const chartData = useMemo(() => { // Include all entries (library + watchlist) const entries = allEntries; - if (effectiveYear === 'all') { + if (effectiveYear === "all") { // Build monthly data across all years const dateEntries = entries .map((e) => { @@ -75,7 +99,11 @@ export function LibraryGrowthChart() { .filter(Boolean) as Date[]; if (dateEntries.length === 0) { - return MONTH_LABELS.map((label) => ({ month: label, count: 0, cumulative: 0 })); + return MONTH_LABELS.map((label) => ({ + month: label, + count: 0, + cumulative: 0, + })); } const minYear = Math.min(...dateEntries.map((d) => d.getFullYear())); @@ -88,7 +116,7 @@ export function LibraryGrowthChart() { for (let y = minYear; y <= maxYear; y++) { for (let m = 0; m < 12; m++) { const count = dateEntries.filter( - (d) => d.getFullYear() === y && d.getMonth() === m + (d) => d.getFullYear() === y && d.getMonth() === m, ).length; cumulative += count; data.push({ @@ -137,29 +165,50 @@ export function LibraryGrowthChart() { value={effectiveYear} onChange={(e) => { const val = e.target.value; - setYear(val === 'all' ? 'all' : Number(val)); + setYear(val === "all" ? "all" : Number(val)); }} className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring" > {years.map((y) => ( - + ))}
- + - - + + - - + + } />

{name}

-

{value} titles

+

{value} titles

); } export function MediaTypeChart() { const allEntries = useLibraryEntries(); - const [scope, setScope] = useState('library'); + const [scope, setScope] = useState("library"); const chartData = useMemo(() => { - const filtered = scope === 'library' - ? allEntries.filter((e) => !e.watchlist) - : allEntries.filter((e) => e.watchlist); + const filtered = + scope === "library" + ? allEntries.filter((e) => !e.watchlist) + : allEntries.filter((e) => e.watchlist); const movies = filtered.filter((e) => !e.is_tvseries).length; const tv = filtered.filter((e) => e.is_tvseries).length; return [ - { name: 'Movies', value: movies }, - { name: 'TV Series', value: tv }, + { name: "Movies", value: movies }, + { name: "TV Series", value: tv }, ]; }, [allEntries, scope]); @@ -68,14 +75,14 @@ export function MediaTypeChart() {
- {(['library', 'watchlist'] as Scope[]).map((s) => ( + {(["library", "watchlist"] as Scope[]).map((s) => (
- {(['all', 'movies', 'series'] as Filter[]).map((f) => ( + {(["all", "movies", "series"] as Filter[]).map((f) => (
@@ -95,43 +116,72 @@ export function WatchActivityChart() { ) : ( - + - - + + - - + + - + ( - {value} + + {value} + )} /> {showMovies && ( @@ -142,7 +192,11 @@ export function WatchActivityChart() { strokeWidth={2} fill="url(#colorMovies)" dot={false} - activeDot={{ r: 4, strokeWidth: 0, fill: 'var(--color-chart-1)' }} + activeDot={{ + r: 4, + strokeWidth: 0, + fill: "var(--color-chart-1)", + }} /> )} {showEpisodes && ( @@ -153,7 +207,11 @@ export function WatchActivityChart() { strokeWidth={2} fill="url(#colorEpisodes)" dot={false} - activeDot={{ r: 4, strokeWidth: 0, fill: 'var(--color-chart-2)' }} + activeDot={{ + r: 4, + strokeWidth: 0, + fill: "var(--color-chart-2)", + }} /> )} diff --git a/react_frontend/src/components/dashboard/WatchTimeChart.tsx b/react_frontend/src/components/dashboard/WatchTimeChart.tsx index 304568e..14283d3 100644 --- a/react_frontend/src/components/dashboard/WatchTimeChart.tsx +++ b/react_frontend/src/components/dashboard/WatchTimeChart.tsx @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useMemo } from "react"; import { BarChart, Bar, @@ -8,12 +8,31 @@ import { Tooltip, Legend, ResponsiveContainer, -} from 'recharts'; -import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; -import { Skeleton } from '@/components/ui/skeleton'; -import { useYearlyWatchTime } from '@/hooks/useStatistics'; +} from "recharts"; +import { + Card, + CardContent, + CardHeader, + CardTitle, + CardDescription, +} from "@/components/ui/card"; +import { Skeleton } from "@/components/ui/skeleton"; +import { useYearlyWatchTime } from "@/hooks/useStatistics"; -const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +const MONTH_LABELS = [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", +]; function minutesToHours(minutes: number) { return Math.round((minutes / 60) * 10) / 10; @@ -29,7 +48,7 @@ function buildChartData( const m = movies.find((x) => Number(x.month) === monthNum); return { month: label, - 'TV Series': s ? minutesToHours(parseInt(s.watchTime, 10)) : 0, + "TV Series": s ? minutesToHours(parseInt(s.watchTime, 10)) : 0, Movies: m ? minutesToHours(parseInt(m.watchTime, 10)) : 0, }; }); @@ -47,12 +66,12 @@ function CustomTooltip({ active, payload, label }: CustomTooltipProps) { return (

{label}

@@ -62,7 +81,14 @@ function CustomTooltip({ active, payload, label }: CustomTooltipProps) {

))} {payload.length > 1 && ( -

+

Total: {total}h

)} @@ -70,7 +96,13 @@ function CustomTooltip({ active, payload, label }: CustomTooltipProps) { ); } -export function WatchTimeChart({ year, onYearChange }: { year: number; onYearChange: (y: number) => void }) { +export function WatchTimeChart({ + year, + onYearChange, +}: { + year: number; + onYearChange: (y: number) => void; +}) { const currentYear = new Date().getFullYear(); const { data, isLoading } = useYearlyWatchTime(year); @@ -83,11 +115,20 @@ export function WatchTimeChart({ year, onYearChange }: { year: number; onYearCha const monthTotal = useMemo(() => { if (!chartData.length || year !== currentYear) return 0; const m = chartData[currentMonth]; - return m ? Math.round(((m['Movies'] || 0) + (m['TV Series'] || 0)) * 10) / 10 : 0; + return m + ? Math.round(((m["Movies"] || 0) + (m["TV Series"] || 0)) * 10) / 10 + : 0; }, [chartData, currentMonth, year, currentYear]); const yearTotal = useMemo(() => { - return Math.round(chartData.reduce((s, m) => s + (m['Movies'] || 0) + (m['TV Series'] || 0), 0) * 10) / 10; + return ( + Math.round( + chartData.reduce( + (s, m) => s + (m["Movies"] || 0) + (m["TV Series"] || 0), + 0, + ) * 10, + ) / 10 + ); }, [chartData]); const years = Array.from({ length: 5 }, (_, i) => currentYear - i); @@ -119,7 +160,9 @@ export function WatchTimeChart({ year, onYearChange }: { year: number; onYearCha className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring" > {years.map((y) => ( - + ))}
@@ -130,24 +173,41 @@ export function WatchTimeChart({ year, onYearChange }: { year: number; onYearCha ) : ( - - + + - } cursor={{ fill: 'var(--color-accent)' }} /> + } + cursor={{ fill: "var(--color-accent)" }} + /> ( - {value} + + {value} + )} /> >(new Set()); const [creating, setCreating] = useState(false); const { data: allCollections = [] } = useCollections(); const queryClient = useQueryClient(); const filtered = allCollections.filter((c) => - c.name.toLowerCase().includes(search.toLowerCase()) + c.name.toLowerCase().includes(search.toLowerCase()), ); const showCreateOption = search.trim().length > 0 && !allCollections.some( - (c) => c.name.toLowerCase() === search.trim().toLowerCase() + (c) => c.name.toLowerCase() === search.trim().toLowerCase(), ); const isInCollection = (collectionId: number) => @@ -61,11 +61,17 @@ export function AddEntryToCollectionDialog({ const entries = col.entries ?? []; const already = entries.some((e) => e.id === entryId); if (already) return col; - return { ...col, entries: [...entries, { id: entryId } as Collection['entries'][0]] }; + return { + ...col, + entries: [...entries, { id: entryId } as Collection["entries"][0]], + }; } else { - return { ...col, entries: (col.entries ?? []).filter((e) => e.id !== entryId) }; + return { + ...col, + entries: (col.entries ?? []).filter((e) => e.id !== entryId), + }; } - }) + }), ); try { @@ -90,13 +96,16 @@ export function AddEntryToCollectionDialog({ if (!name) return; setCreating(true); try { - const newCollection = await collectionsApi.create({ name, is_user_collection: true } as Partial); + const newCollection = await collectionsApi.create({ + name, + is_user_collection: true, + } as Partial); await collectionsApi.addEntry(newCollection.id, entryId); await queryClient.invalidateQueries({ queryKey: collectionKeys.all }); toast.success(`Created "${name}" and added entry`); - setSearch(''); + setSearch(""); } catch { - toast.error('Failed to create collection'); + toast.error("Failed to create collection"); } finally { setCreating(false); } diff --git a/react_frontend/src/components/dialogs/CollectionEditDialog.tsx b/react_frontend/src/components/dialogs/CollectionEditDialog.tsx index c22bfbe..22f2ec5 100644 --- a/react_frontend/src/components/dialogs/CollectionEditDialog.tsx +++ b/react_frontend/src/components/dialogs/CollectionEditDialog.tsx @@ -1,19 +1,19 @@ -import { useState, useRef } from 'react'; +import { useState, useRef } from "react"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, -} from '@/components/ui/dialog'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Textarea } from '@/components/ui/textarea'; -import { ImageIcon } from 'lucide-react'; -import { StarRating } from '@/components/ui/star-rating'; -import { useUpdateCollection } from '@/hooks/useCollections'; -import type { Collection } from '@/types'; +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { ImageIcon } from "lucide-react"; +import { StarRating } from "@/components/ui/star-rating"; +import { useUpdateCollection } from "@/hooks/useCollections"; +import type { Collection } from "@/types"; interface CollectionEditDialogProps { open: boolean; @@ -27,10 +27,8 @@ export function CollectionEditDialog({ collection, }: CollectionEditDialogProps) { const [name, setName] = useState(collection.name); - const [description, setDescription] = useState(collection.description || ''); - const [userRating, setUserRating] = useState( - collection.user_rating ?? 0 - ); + const [description, setDescription] = useState(collection.description || ""); + const [userRating, setUserRating] = useState(collection.user_rating ?? 0); const [posterFile, setPosterFile] = useState(null); const [backdropFile, setBackdropFile] = useState(null); const [posterPreview, setPosterPreview] = useState(null); @@ -61,20 +59,20 @@ export function CollectionEditDialog({ e.preventDefault(); const formData = new FormData(); - formData.append('name', name); - formData.append('description', description); - formData.append('userRating', String(userRating || 0)); + formData.append("name", name); + formData.append("description", description); + formData.append("userRating", String(userRating || 0)); if (posterFile) { - formData.append('poster', posterFile); + formData.append("poster", posterFile); } if (backdropFile) { - formData.append('backdrop', backdropFile); + formData.append("backdrop", backdropFile); } updateCollection.mutate( { id: collection.id, data: formData }, - { onSuccess: () => onOpenChange(false) } + { onSuccess: () => onOpenChange(false) }, ); }; @@ -108,9 +106,13 @@ export function CollectionEditDialog({
- + - {userRating > 0 ? `${userRating}/10` : '—'} + {userRating > 0 ? `${userRating}/10` : "—"}
@@ -191,7 +193,7 @@ export function CollectionEditDialog({ Cancel diff --git a/react_frontend/src/components/dialogs/ConfirmDialog.tsx b/react_frontend/src/components/dialogs/ConfirmDialog.tsx index 83cdc2b..dbff10f 100644 --- a/react_frontend/src/components/dialogs/ConfirmDialog.tsx +++ b/react_frontend/src/components/dialogs/ConfirmDialog.tsx @@ -5,9 +5,9 @@ import { DialogFooter, DialogHeader, DialogTitle, -} from '@/components/ui/dialog'; -import { Button } from '@/components/ui/button'; -import { Loader2 } from 'lucide-react'; +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Loader2 } from "lucide-react"; interface ConfirmDialogProps { open: boolean; @@ -17,7 +17,7 @@ interface ConfirmDialogProps { confirmLabel?: string; cancelLabel?: string; onConfirm: () => void; - variant?: 'default' | 'destructive'; + variant?: "default" | "destructive"; isLoading?: boolean; } @@ -26,10 +26,10 @@ export function ConfirmDialog({ onOpenChange, title, description, - confirmLabel = 'Confirm', - cancelLabel = 'Cancel', + confirmLabel = "Confirm", + cancelLabel = "Cancel", onConfirm, - variant = 'default', + variant = "default", isLoading = false, }: ConfirmDialogProps) { return ( @@ -40,11 +40,15 @@ export function ConfirmDialog({ {description} - diff --git a/react_frontend/src/components/dialogs/EntrySettingsDialog.tsx b/react_frontend/src/components/dialogs/EntrySettingsDialog.tsx index 418066b..ee5899c 100644 --- a/react_frontend/src/components/dialogs/EntrySettingsDialog.tsx +++ b/react_frontend/src/components/dialogs/EntrySettingsDialog.tsx @@ -3,13 +3,13 @@ import { DialogContent, DialogHeader, DialogTitle, -} from '@/components/ui/dialog'; -import { Label } from '@/components/ui/label'; -import { Switch } from '@/components/ui/switch'; -import { Separator } from '@/components/ui/separator'; -import { useUpdateEntry, useUpdateEntryRatings } from '@/hooks/useEntries'; -import { StarRating } from '@/components/ui/star-rating'; -import type { Entry } from '@/types'; +} from "@/components/ui/dialog"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { Separator } from "@/components/ui/separator"; +import { useUpdateEntry, useUpdateEntryRatings } from "@/hooks/useEntries"; +import { StarRating } from "@/components/ui/star-rating"; +import type { Entry } from "@/types"; interface EntrySettingsDialogProps { open: boolean; @@ -30,11 +30,11 @@ export function EntrySettingsDialog({ }; const boolSettings = [ - { field: 'favorit' as const, label: 'Favorite' }, - { field: 'hidden' as const, label: 'Hidden' }, - { field: 'watchlist' as const, label: 'Watchlist' }, - { field: 'show_in_calendar' as const, label: 'Show in Calendar' }, - { field: 'auto_sync' as const, label: 'Auto Sync' }, + { field: "favorit" as const, label: "Favorite" }, + { field: "hidden" as const, label: "Hidden" }, + { field: "watchlist" as const, label: "Watchlist" }, + { field: "show_in_calendar" as const, label: "Show in Calendar" }, + { field: "auto_sync" as const, label: "Auto Sync" }, ]; const userRating = entry.entryRatings?.user_rating ?? 0; @@ -51,11 +51,16 @@ export function EntrySettingsDialog({ Entry Settings -

{entry.title}

+

+ {entry.title} +

{boolSettings.map(({ field, label }) => ( -
+
@@ -70,9 +75,13 @@ export function EntrySettingsDialog({
- + - {userRating > 0 ? `${userRating}/10` : '—'} + {userRating > 0 ? `${userRating}/10` : "—"}
diff --git a/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx b/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx index 0a283c4..4190e8a 100644 --- a/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx +++ b/react_frontend/src/components/dialogs/EpisodeSeenEditDialog.tsx @@ -1,23 +1,26 @@ -import { useState } from 'react'; +import { useState } from "react"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, -} from '@/components/ui/dialog'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, -} from '@/components/ui/select'; -import { useUpdateEpisodeSeen, useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen'; -import type { EpisodeSeen, SeenAccuracy } from '@/types'; +} from "@/components/ui/select"; +import { + useUpdateEpisodeSeen, + useCreateEpisodeSeen, +} from "@/hooks/useEpisodeSeen"; +import type { EpisodeSeen, SeenAccuracy } from "@/types"; interface EpisodeSeenEditDialogProps { open: boolean; @@ -28,9 +31,13 @@ interface EpisodeSeenEditDialogProps { episodeId?: number; entryId: number; seasonId?: number; - mode?: 'create' | 'edit'; + mode?: "create" | "edit"; /** If provided, called instead of the normal create/update mutation */ - overrideSubmit?: (date: string, seenWith: string, accuracy: SeenAccuracy) => void; + overrideSubmit?: ( + date: string, + seenWith: string, + accuracy: SeenAccuracy, + ) => void; } export function EpisodeSeenEditDialog({ @@ -40,13 +47,15 @@ export function EpisodeSeenEditDialog({ episodeId, entryId, seasonId, - mode = record ? 'edit' : 'create', + mode = record ? "edit" : "create", overrideSubmit, }: EpisodeSeenEditDialogProps) { - const today = new Date().toISOString().split('T')[0]; - const [date, setDate] = useState(record?.date_seen?.split('T')[0] ?? today); - const [seenWith, setSeenWith] = useState(record?.seen_with ?? ''); - const [accuracy, setAccuracy] = useState(record?.accuracy ?? 'EXACT'); + const today = new Date().toISOString().split("T")[0]; + const [date, setDate] = useState(record?.date_seen?.split("T")[0] ?? today); + const [seenWith, setSeenWith] = useState(record?.seen_with ?? ""); + const [accuracy, setAccuracy] = useState( + record?.accuracy ?? "EXACT", + ); const updateEpisodeSeen = useUpdateEpisodeSeen(); const createEpisodeSeen = useCreateEpisodeSeen(); @@ -56,7 +65,7 @@ export function EpisodeSeenEditDialog({ overrideSubmit(date, seenWith, accuracy); return; } - if (mode === 'edit' && record) { + if (mode === "edit" && record) { updateEpisodeSeen.mutate({ id: record.id, data: { @@ -86,7 +95,9 @@ export function EpisodeSeenEditDialog({ - {mode === 'edit' ? 'Edit Watch Record' : 'Mark as Watched'} + + {mode === "edit" ? "Edit Watch Record" : "Mark as Watched"} +
@@ -99,7 +110,10 @@ export function EpisodeSeenEditDialog({ onChange={(e) => setDate(e.target.value)} className="flex-1" /> - setAccuracy(v as SeenAccuracy)} + > @@ -122,9 +136,11 @@ export function EpisodeSeenEditDialog({
- +
diff --git a/react_frontend/src/components/dialogs/MarkSeasonWatchedDialog.tsx b/react_frontend/src/components/dialogs/MarkSeasonWatchedDialog.tsx index 1570169..81c1ad3 100644 --- a/react_frontend/src/components/dialogs/MarkSeasonWatchedDialog.tsx +++ b/react_frontend/src/components/dialogs/MarkSeasonWatchedDialog.tsx @@ -1,4 +1,4 @@ -import { useState, useMemo } from 'react'; +import { useState, useMemo } from "react"; import { Dialog, DialogContent, @@ -6,21 +6,21 @@ import { DialogHeader, DialogTitle, DialogDescription, -} from '@/components/ui/dialog'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Switch } from '@/components/ui/switch'; +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, -} from '@/components/ui/select'; -import { Loader2, CalendarRange, CalendarDays } from 'lucide-react'; -import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen'; -import type { Episode, SeenAccuracy } from '@/types'; +} from "@/components/ui/select"; +import { Loader2, CalendarRange, CalendarDays } from "lucide-react"; +import { useCreateEpisodeSeen } from "@/hooks/useEpisodeSeen"; +import type { Episode, SeenAccuracy } from "@/types"; interface MarkSeasonWatchedDialogProps { open: boolean; @@ -30,7 +30,7 @@ interface MarkSeasonWatchedDialogProps { episodes: Episode[]; } -type Mode = 'single' | 'scatter'; +type Mode = "single" | "scatter"; function addDays(date: Date, days: number): Date { const result = new Date(date); @@ -39,7 +39,7 @@ function addDays(date: Date, days: number): Date { } function toDateStr(date: Date): string { - return date.toISOString().split('T')[0]; + return date.toISOString().split("T")[0]; } /** @@ -79,18 +79,18 @@ export function MarkSeasonWatchedDialog({ seasonId, episodes, }: MarkSeasonWatchedDialogProps) { - const today = new Date().toISOString().split('T')[0]; + const today = new Date().toISOString().split("T")[0]; const createEpisodeSeen = useCreateEpisodeSeen(); // Shared fields - const [seenWith, setSeenWith] = useState(''); - const [accuracy, setAccuracy] = useState('EXACT'); + const [seenWith, setSeenWith] = useState(""); + const [accuracy, setAccuracy] = useState("EXACT"); // Single-date mode const [singleDate, setSingleDate] = useState(today); // Scatter mode - const [mode, setMode] = useState('single'); + const [mode, setMode] = useState("single"); const [startDate, setStartDate] = useState(today); const [endDate, setEndDate] = useState(today); @@ -107,7 +107,7 @@ export function MarkSeasonWatchedDialog({ ); const scatterPreview = useMemo(() => { - if (mode !== 'scatter' || !startDate || !endDate) return null; + if (mode !== "scatter" || !startDate || !endDate) return null; const start = new Date(startDate); const end = new Date(endDate); if (end < start) return null; @@ -131,7 +131,7 @@ export function MarkSeasonWatchedDialog({ setIsSubmitting(true); try { - if (mode === 'single') { + if (mode === "single") { for (const ep of unwatched) { await createEpisodeSeen.mutateAsync({ entry_id: entryId, @@ -171,7 +171,8 @@ export function MarkSeasonWatchedDialog({ Mark Season as Watched - {unwatched.length} unwatched episode{unwatched.length !== 1 ? 's' : ''} will be marked as seen. + {unwatched.length} unwatched episode + {unwatched.length !== 1 ? "s" : ""} will be marked as seen. @@ -179,25 +180,25 @@ export function MarkSeasonWatchedDialog({ {/* Mode toggle */}
- {mode === 'single' ? ( + {mode === "single" ? ( ) : ( )} - {mode === 'single' ? 'Single Date' : 'Scatter Mode'} + {mode === "single" ? "Single Date" : "Scatter Mode"}
- setMode(checked ? 'scatter' : 'single') + setMode(checked ? "scatter" : "single") } />
{/* Date inputs */} - {mode === 'single' ? ( + {mode === "single" ? (

- {unwatched.length} episodes across {scatterPreview.totalDays} day{scatterPreview.totalDays !== 1 ? 's' : ''} + {unwatched.length} episodes across{" "} + {scatterPreview.totalDays} day + {scatterPreview.totalDays !== 1 ? "s" : ""}

- ~{scatterPreview.maxPerDay} episode{scatterPreview.maxPerDay !== 1 ? 's' : ''}/day max + ~{scatterPreview.maxPerDay} episode + {scatterPreview.maxPerDay !== 1 ? "s" : ""}/day max

)} - {startDate && endDate && new Date(endDate) < new Date(startDate) && ( -

- End date must be after start date. -

- )} + {startDate && + endDate && + new Date(endDate) < new Date(startDate) && ( +

+ End date must be after start date. +

+ )}
)} @@ -293,19 +299,17 @@ export function MarkSeasonWatchedDialog({ disabled={ isSubmitting || unwatched.length === 0 || - (mode === 'single' && !singleDate) || - (mode === 'scatter' && + (mode === "single" && !singleDate) || + (mode === "scatter" && (!startDate || !endDate || new Date(endDate) < new Date(startDate))) } > - {isSubmitting && ( - - )} + {isSubmitting && } {isSubmitting - ? 'Marking...' - : `Mark ${unwatched.length} Episode${unwatched.length !== 1 ? 's' : ''}`} + ? "Marking..." + : `Mark ${unwatched.length} Episode${unwatched.length !== 1 ? "s" : ""}`} diff --git a/react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx b/react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx index 21387d6..4d7262c 100644 --- a/react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx +++ b/react_frontend/src/components/dialogs/MovieWatchHistoryDialog.tsx @@ -1,13 +1,13 @@ -import { format } from 'date-fns'; +import { format } from "date-fns"; import { Dialog, DialogContent, DialogHeader, DialogTitle, -} from '@/components/ui/dialog'; -import { Button } from '@/components/ui/button'; -import { Trash2 } from 'lucide-react'; -import type { EntrySeen } from '@/types'; +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Trash2 } from "lucide-react"; +import type { EntrySeen } from "@/types"; interface MovieWatchHistoryDialogProps { open: boolean; @@ -51,11 +51,11 @@ export function MovieWatchHistoryDialog({ > {record.date_seen - ? format(new Date(record.date_seen), 'MMM d, yyyy') - : '-'} + ? format(new Date(record.date_seen), "MMM d, yyyy") + : "-"} - {record.seen_with || '-'} + {record.seen_with || "-"}
diff --git a/react_frontend/src/components/dialogs/RatingDialog.tsx b/react_frontend/src/components/dialogs/RatingDialog.tsx index 8c795b6..72a743f 100644 --- a/react_frontend/src/components/dialogs/RatingDialog.tsx +++ b/react_frontend/src/components/dialogs/RatingDialog.tsx @@ -1,14 +1,14 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect } from "react"; import { Dialog, DialogContent, DialogHeader, DialogTitle, -} from '@/components/ui/dialog'; -import { Button } from '@/components/ui/button'; -import { StarRating } from '@/components/ui/star-rating'; -import { useUpdateEntryRatings } from '@/hooks/useEntries'; -import type { Entry } from '@/types'; +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { StarRating } from "@/components/ui/star-rating"; +import { useUpdateEntryRatings } from "@/hooks/useEntries"; +import type { Entry } from "@/types"; interface RatingDialogProps { open: boolean; @@ -48,14 +48,16 @@ export function RatingDialog({ open, onOpenChange, entry }: RatingDialogProps) { Rate -

{entry.title}

+

+ {entry.title} +

- {selected > 0 ? `${selected} / 10` : '—'} + {selected > 0 ? `${selected} / 10` : "—"}

{(selected > 0 || currentRating > 0) && ( diff --git a/react_frontend/src/components/entries/EpisodeWatchHistory.tsx b/react_frontend/src/components/entries/EpisodeWatchHistory.tsx index 408b966..871a444 100644 --- a/react_frontend/src/components/entries/EpisodeWatchHistory.tsx +++ b/react_frontend/src/components/entries/EpisodeWatchHistory.tsx @@ -1,7 +1,7 @@ -import { format } from 'date-fns'; -import type { EntrySeen, EpisodeSeen } from '@/types'; -import { Button } from '@/components/ui/button'; -import { Pencil, Trash2 } from 'lucide-react'; +import { format } from "date-fns"; +import type { EntrySeen, EpisodeSeen } from "@/types"; +import { Button } from "@/components/ui/button"; +import { Pencil, Trash2 } from "lucide-react"; interface EpisodeWatchHistoryProps { watchHistory: (EntrySeen | EpisodeSeen)[]; @@ -40,11 +40,11 @@ export function EpisodeWatchHistory({ > {record.date_seen - ? format(new Date(record.date_seen), 'MMM d, yyyy') - : '-'} + ? format(new Date(record.date_seen), "MMM d, yyyy") + : "-"} - {record.seen_with || '-'} + {record.seen_with || "-"}
diff --git a/react_frontend/src/components/entries/SeasonsContainer.tsx b/react_frontend/src/components/entries/SeasonsContainer.tsx index 06cc660..72590cb 100644 --- a/react_frontend/src/components/entries/SeasonsContainer.tsx +++ b/react_frontend/src/components/entries/SeasonsContainer.tsx @@ -1,21 +1,18 @@ -import { useState } from 'react'; -import { Link } from 'react-router-dom'; -import { ChevronDown, ChevronUp, Play } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { Progress } from '@/components/ui/progress'; -import { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog'; -import { getYear, getTmdbPosterUrl } from '@/lib/media-utils'; -import type { Season } from '@/types'; +import { useState } from "react"; +import { Link } from "react-router-dom"; +import { ChevronDown, ChevronUp, Play } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Progress } from "@/components/ui/progress"; +import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog"; +import { getYear, getTmdbPosterUrl } from "@/lib/media-utils"; +import type { Season } from "@/types"; interface SeasonsContainerProps { seasons: Season[]; entryId: number; } -export function SeasonsContainer({ - seasons, - entryId, -}: SeasonsContainerProps) { +export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) { const [expanded, setExpanded] = useState(false); // Sort: specials (season 0) at bottom, rest latest to oldest @@ -48,8 +45,8 @@ export function SeasonsContainer({ ) : ( <> - Show All ( - {sorted.length}) + Show All ({sorted.length} + ) )} @@ -58,17 +55,12 @@ export function SeasonsContainer({ ); } -function SeasonItem({ - season, - entryId, -}: { - season: Season; - entryId: number; -}) { +function SeasonItem({ season, entryId }: { season: Season; entryId: number }) { const [dialogOpen, setDialogOpen] = useState(false); const watchedCount = season.episodes?.filter( - (ep) => ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0) + (ep) => + ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0), ).length ?? 0; const totalEpisodes = season.episode_count || season.episodes?.length || 0; const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0; @@ -76,7 +68,11 @@ function SeasonItem({ const nextUnwatched = season.episodes ?.slice() .sort((a, b) => a.episode_number - b.episode_number) - .find((ep) => !ep.date_first_seen && (!ep.episodeSeens || ep.episodeSeens.length === 0)); + .find( + (ep) => + !ep.date_first_seen && + (!ep.episodeSeens || ep.episodeSeens.length === 0), + ); return ( <> @@ -87,7 +83,7 @@ function SeasonItem({ {/* Poster thumbnail */}
{season.name}('movie'); - const entries = activeTab === 'movie' ? movieEntries : tvEntries; + const [activeTab, setActiveTab] = useState<"movie" | "tv">("movie"); + const entries = activeTab === "movie" ? movieEntries : tvEntries; const displayEntries = entries.slice(0, 14); return ( @@ -33,7 +33,7 @@ export function TrendingGrid({
setActiveTab(v as 'movie' | 'tv')} + onValueChange={(v) => setActiveTab(v as "movie" | "tv")} > diff --git a/react_frontend/src/components/entries/TrendingSlider.tsx b/react_frontend/src/components/entries/TrendingSlider.tsx index f61a2d6..efb55ea 100644 --- a/react_frontend/src/components/entries/TrendingSlider.tsx +++ b/react_frontend/src/components/entries/TrendingSlider.tsx @@ -1,10 +1,10 @@ -import { useState, useEffect, useCallback, useRef } from 'react'; -import { Link } from 'react-router-dom'; -import { ChevronLeft, ChevronRight, Star } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { useCreateEntry } from '@/hooks/useEntries'; -import { useLibraryStore } from '@/stores/useLibraryStore'; -import type { TmdbEntry } from '@/types'; +import { useState, useEffect, useCallback, useRef } from "react"; +import { Link } from "react-router-dom"; +import { ChevronLeft, ChevronRight, Star } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { useCreateEntry } from "@/hooks/useEntries"; +import { useLibraryStore } from "@/stores/useLibraryStore"; +import type { TmdbEntry } from "@/types"; interface TrendingSliderProps { entries: TmdbEntry[]; @@ -48,14 +48,14 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) { const safeIndex = currentIndex < display.length ? currentIndex : 0; const item = display[safeIndex]; - const title = item.title || item.name || 'Untitled'; + const title = item.title || item.name || "Untitled"; const backdropUrl = item.backdrop_path ? `https://image.tmdb.org/t/p/w1280${item.backdrop_path}` : null; - const isTv = item.media_type === 'tv' || !!item.name; + const isTv = item.media_type === "tv" || !!item.name; const matchedEntry = Array.from(libraryEntries.values()).find( - (e) => e.entryIds?.tmdb_id === item.id + (e) => e.entryIds?.tmdb_id === item.id, ); const isInLibrary = !!matchedEntry; @@ -77,14 +77,20 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) { @@ -94,7 +100,7 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) {
- {isTv ? 'TV Series' : 'Movie'} + {isTv ? "TV Series" : "Movie"} {item.vote_average > 0 && ( @@ -122,7 +128,9 @@ export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) { @@ -121,7 +132,12 @@ export function HeroSlider({ entries }: HeroSliderProps) { size="sm" variant="secondary" className="rounded-full gap-1.5 text-xs" - onClick={() => createEntry.mutate({ tmdb_id: entry.id, is_tvserie: isTv })} + onClick={() => + createEntry.mutate({ + tmdb_id: entry.id, + is_tvserie: isTv, + }) + } disabled={createEntry.isPending} > @@ -144,7 +160,7 @@ export function HeroSlider({ entries }: HeroSliderProps) { placeholder="Search movies, TV shows..." value={searchInput} onChange={(e) => setSearchInput(e.target.value)} - onKeyDown={(e) => e.key === 'Enter' && handleSearch()} + onKeyDown={(e) => e.key === "Enter" && handleSearch()} className="w-full rounded-full border border-white/20 bg-black/40 py-2.5 pl-9 pr-4 text-sm text-white backdrop-blur-md placeholder-white/50 transition-colors focus:border-white/50 focus:outline-none" />
@@ -153,7 +169,10 @@ export function HeroSlider({ entries }: HeroSliderProps) { {/* Left arrow */}
diff --git a/react_frontend/src/components/home/SectionHeader.tsx b/react_frontend/src/components/home/SectionHeader.tsx index 4363b80..24876de 100644 --- a/react_frontend/src/components/home/SectionHeader.tsx +++ b/react_frontend/src/components/home/SectionHeader.tsx @@ -1,4 +1,4 @@ -import { Link } from 'react-router-dom'; +import { Link } from "react-router-dom"; interface SectionHeaderProps { icon: React.ReactNode; diff --git a/react_frontend/src/components/home/index.ts b/react_frontend/src/components/home/index.ts index ad59777..2d525d5 100644 --- a/react_frontend/src/components/home/index.ts +++ b/react_frontend/src/components/home/index.ts @@ -1,7 +1,7 @@ -export { HeroSlider } from './HeroSlider'; -export { BackdropCard, BackdropScrollCard } from './BackdropCard'; -export { NumberedListItem } from './NumberedListItem'; -export { MiniPosterCard } from './MiniPosterCard'; -export { UpcomingCard } from './UpcomingCard'; -export { SectionHeader } from './SectionHeader'; -export { PopularBelt } from './PopularBelt'; +export { HeroSlider } from "./HeroSlider"; +export { BackdropCard, BackdropScrollCard } from "./BackdropCard"; +export { NumberedListItem } from "./NumberedListItem"; +export { MiniPosterCard } from "./MiniPosterCard"; +export { UpcomingCard } from "./UpcomingCard"; +export { SectionHeader } from "./SectionHeader"; +export { PopularBelt } from "./PopularBelt"; diff --git a/react_frontend/src/components/layout/AppLayout.tsx b/react_frontend/src/components/layout/AppLayout.tsx index 378a870..2638233 100644 --- a/react_frontend/src/components/layout/AppLayout.tsx +++ b/react_frontend/src/components/layout/AppLayout.tsx @@ -1,19 +1,20 @@ -import { Outlet, useLocation } from 'react-router-dom'; -import { useState, useRef, useEffect } from 'react'; -import { Menu } from 'lucide-react'; -import { Button } from '@/components/ui/button'; +import { Outlet, useLocation } from "react-router-dom"; +import { useState, useRef, useEffect } from "react"; +import { Menu } from "lucide-react"; +import { Button } from "@/components/ui/button"; import { Sheet, SheetContent, SheetHeader, SheetTitle, -} from '@/components/ui/sheet'; -import { Sidebar, MobileSidebarContent } from './Sidebar'; -import { TitleBar } from './TitleBar'; -import { CommandPalette } from '@/components/CommandPalette'; -import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore'; +} from "@/components/ui/sheet"; +import { Sidebar, MobileSidebarContent } from "./Sidebar"; +import { TitleBar } from "./TitleBar"; +import { CommandPalette } from "@/components/CommandPalette"; +import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore"; -const isElectron = import.meta.env.VITE_ELECTRON === 'true' || !!window.electron?.isElectron; +const isElectron = + import.meta.env.VITE_ELECTRON === "true" || !!window.electron?.isElectron; export function AppLayout() { const [mobileOpen, setMobileOpen] = useState(false); @@ -28,13 +29,13 @@ export function AppLayout() { // Global keyboard shortcut: Ctrl+P or "/" when not in input useEffect(() => { function handleKeyDown(e: KeyboardEvent) { - if ((e.ctrlKey || e.metaKey) && e.key === 'p') { + if ((e.ctrlKey || e.metaKey) && e.key === "p") { e.preventDefault(); openPalette(); return; } if ( - e.key === '/' && + e.key === "/" && !e.ctrlKey && !e.metaKey && !e.altKey && @@ -46,8 +47,8 @@ export function AppLayout() { openPalette(); } } - document.addEventListener('keydown', handleKeyDown); - return () => document.removeEventListener('keydown', handleKeyDown); + document.addEventListener("keydown", handleKeyDown); + return () => document.removeEventListener("keydown", handleKeyDown); }, [openPalette]); return ( @@ -63,7 +64,11 @@ export function AppLayout() { {/* Mobile header */}
- Showy @@ -71,7 +76,11 @@ export function AppLayout() { {/* Mobile sidebar sheet */} - + Navigation diff --git a/react_frontend/src/components/layout/Sidebar.tsx b/react_frontend/src/components/layout/Sidebar.tsx index 656b536..7e2a7df 100644 --- a/react_frontend/src/components/layout/Sidebar.tsx +++ b/react_frontend/src/components/layout/Sidebar.tsx @@ -1,4 +1,4 @@ -import { NavLink } from 'react-router-dom'; +import { NavLink } from "react-router-dom"; import { LayoutDashboard, Home, @@ -12,25 +12,25 @@ import { Moon, Sun, Film, -} from 'lucide-react'; -import { useThemeStore } from '@/stores/useThemeStore'; -import { Separator } from '@/components/ui/separator'; +} from "lucide-react"; +import { useThemeStore } from "@/stores/useThemeStore"; +import { Separator } from "@/components/ui/separator"; const mainNav = [ - { to: '/dashboard', icon: LayoutDashboard, label: 'Dashboard' }, - { to: '/', icon: Home, label: 'Home' }, + { to: "/dashboard", icon: LayoutDashboard, label: "Dashboard" }, + { to: "/", icon: Home, label: "Home" }, ]; const libraryNav = [ - { to: '/library', icon: Library, label: 'Library' }, - { to: '/watchlist', icon: ListVideo, label: 'Watchlist' }, - { to: '/collections', icon: FolderOpen, label: 'Collections' }, - { to: '/media', icon: Image, label: 'Media' }, + { to: "/library", icon: Library, label: "Library" }, + { to: "/watchlist", icon: ListVideo, label: "Watchlist" }, + { to: "/collections", icon: FolderOpen, label: "Collections" }, + { to: "/media", icon: Image, label: "Media" }, ]; const otherNav = [ - { to: '/calendar', icon: CalendarDays, label: 'Calendar' }, - { to: '/people', icon: Users, label: 'People' }, + { to: "/calendar", icon: CalendarDays, label: "Calendar" }, + { to: "/people", icon: Users, label: "People" }, ]; function NavItem({ @@ -45,17 +45,19 @@ function NavItem({ return ( `relative flex flex-col items-center gap-1 rounded-md px-2 py-2.5 transition-colors ${ isActive - ? 'bg-sidebar-accent text-sidebar-primary' - : 'text-sidebar-foreground/50 hover:bg-sidebar-accent/40 hover:text-sidebar-foreground' + ? "bg-sidebar-accent text-sidebar-primary" + : "text-sidebar-foreground/50 hover:bg-sidebar-accent/40 hover:text-sidebar-foreground" }` } > - {label} + + {label} + ); } @@ -97,13 +99,13 @@ export function Sidebar() { className="w-full flex flex-col items-center gap-1 rounded-md px-2 py-2.5 text-sidebar-foreground/50 hover:bg-sidebar-accent/40 hover:text-sidebar-foreground transition-colors" onClick={toggleTheme} > - {theme === 'dark' ? ( + {theme === "dark" ? ( ) : ( )} - {theme === 'dark' ? 'Light' : 'Dark'} + {theme === "dark" ? "Light" : "Dark"} @@ -126,13 +128,13 @@ function MobileNavItem({ return ( `flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors ${ isActive - ? 'bg-sidebar-accent text-sidebar-primary font-medium' - : 'text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground' + ? "bg-sidebar-accent text-sidebar-primary font-medium" + : "text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground" }` } > @@ -142,7 +144,11 @@ function MobileNavItem({ ); } -export function MobileSidebarContent({ onNavigate }: { onNavigate: () => void }) { +export function MobileSidebarContent({ + onNavigate, +}: { + onNavigate: () => void; +}) { const { theme, toggleTheme } = useThemeStore(); return ( @@ -189,14 +195,19 @@ export function MobileSidebarContent({ onNavigate }: { onNavigate: () => void }) className="w-full flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm text-sidebar-foreground/70 hover:bg-sidebar-accent/50 hover:text-sidebar-foreground transition-colors" onClick={toggleTheme} > - {theme === 'dark' ? ( + {theme === "dark" ? ( ) : ( )} - {theme === 'dark' ? 'Light Mode' : 'Dark Mode'} + {theme === "dark" ? "Light Mode" : "Dark Mode"} - +
); diff --git a/react_frontend/src/components/layout/TitleBar.tsx b/react_frontend/src/components/layout/TitleBar.tsx index 29a8693..cbf3424 100644 --- a/react_frontend/src/components/layout/TitleBar.tsx +++ b/react_frontend/src/components/layout/TitleBar.tsx @@ -1,4 +1,4 @@ -import { Minus, Square, X } from 'lucide-react'; +import { Minus, Square, X } from "lucide-react"; export function TitleBar() { const minimize = () => window.electron?.windowControls.minimize(); @@ -6,14 +6,20 @@ export function TitleBar() { const close = () => window.electron?.windowControls.close(); return ( -
- SHOWY + + SHOWY +
-
+
@@ -77,14 +86,18 @@ export function EpisodeNavigator({ .map((ep) => ( diff --git a/react_frontend/src/components/streaming/EpisodesSidebar.tsx b/react_frontend/src/components/streaming/EpisodesSidebar.tsx index b8e4617..76344bf 100644 --- a/react_frontend/src/components/streaming/EpisodesSidebar.tsx +++ b/react_frontend/src/components/streaming/EpisodesSidebar.tsx @@ -1,14 +1,14 @@ -import { useEffect, useRef, useState } from 'react'; -import { getTmdbImageUrl } from '@/lib/api'; +import { useEffect, useRef, useState } from "react"; +import { getTmdbImageUrl } from "@/lib/api"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, -} from '@/components/ui/select'; -import { CheckCircle2, PlayCircle, Tv } from 'lucide-react'; -import type { Season } from '@/types'; +} from "@/components/ui/select"; +import { CheckCircle2, PlayCircle, Tv } from "lucide-react"; +import type { Season } from "@/types"; interface EpisodesSidebarProps { seasons: Season[]; @@ -36,13 +36,20 @@ export function EpisodesSidebar({ // Auto-scroll to the currently playing episode useEffect(() => { if (activeEpisodeRef.current) { - activeEpisodeRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' }); + activeEpisodeRef.current.scrollIntoView({ + behavior: "smooth", + block: "center", + }); } }, [currentSeason, currentEpisode, selectedSeason]); - const browsingSeason = seasons.find((s) => s.season_number === selectedSeason); + const browsingSeason = seasons.find( + (s) => s.season_number === selectedSeason, + ); const episodes = browsingSeason?.episodes - ? [...browsingSeason.episodes].sort((a, b) => a.episode_number - b.episode_number) + ? [...browsingSeason.episodes].sort( + (a, b) => a.episode_number - b.episode_number, + ) : []; const playableSeasons = seasons @@ -58,9 +65,7 @@ export function EpisodesSidebar({ onValueChange={(v) => setSelectedSeason(Number(v))} > - - Season {selectedSeason} - + Season {selectedSeason} {playableSeasons.map((season) => ( @@ -86,28 +91,32 @@ export function EpisodesSidebar({ {episodes.map((ep) => { const isPlaying = - selectedSeason === currentSeason && ep.episode_number === currentEpisode; + selectedSeason === currentSeason && + ep.episode_number === currentEpisode; const isWatched = !!ep.date_first_seen || (ep.episodeSeens != null && ep.episodeSeens.length > 0); const isUnreleased = !!ep.air_date && new Date(ep.air_date) > new Date(); const stillUrl = ep.still_path - ? getTmdbImageUrl(ep.still_path, 'w300') + ? getTmdbImageUrl(ep.still_path, "w300") : null; return ( diff --git a/react_frontend/src/components/streaming/StreamingDialog.tsx b/react_frontend/src/components/streaming/StreamingDialog.tsx index 60bb505..2be1c67 100644 --- a/react_frontend/src/components/streaming/StreamingDialog.tsx +++ b/react_frontend/src/components/streaming/StreamingDialog.tsx @@ -1,6 +1,6 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { createPortal } from 'react-dom'; -import { useStreamingStore } from '@/stores/useStreamingStore'; +import { useCallback, useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { useStreamingStore } from "@/stores/useStreamingStore"; import { isValidEventOrigin, updateProgressFromEvent, @@ -8,19 +8,14 @@ import { logWatchCompleted, isValidEmbedUrl, getEntryWatchProgress, -} from '@/lib/streaming'; -import type { PlayerEvent } from '@/lib/streaming'; -import { ServerSelector } from './ServerSelector'; -import { EpisodesSidebar } from './EpisodesSidebar'; -import { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt'; -import { Button } from '@/components/ui/button'; -import { - X, - List, - AlertTriangle, - RefreshCw, -} from 'lucide-react'; -import type { Entry, Season } from '@/types'; +} from "@/lib/streaming"; +import type { PlayerEvent } from "@/lib/streaming"; +import { ServerSelector } from "./ServerSelector"; +import { EpisodesSidebar } from "./EpisodesSidebar"; +import { AutoMarkWatchedPrompt } from "./AutoMarkWatchedPrompt"; +import { Button } from "@/components/ui/button"; +import { X, List, AlertTriangle, RefreshCw } from "lucide-react"; +import type { Entry, Season } from "@/types"; interface StreamingDialogProps { entry: Entry; @@ -67,11 +62,21 @@ export function StreamingDialog({ const autoMarkPromptShownRef = useRef(autoMarkPromptShown); const onMarkAsWatchedRef = useRef(onMarkAsWatched); - useEffect(() => { currentSeasonRef.current = currentSeason; }, [currentSeason]); - useEffect(() => { currentEpisodeRef.current = currentEpisode; }, [currentEpisode]); - useEffect(() => { autoMarkRef.current = autoMarkWatched; }, [autoMarkWatched]); - useEffect(() => { autoMarkPromptShownRef.current = autoMarkPromptShown; }, [autoMarkPromptShown]); - useEffect(() => { onMarkAsWatchedRef.current = onMarkAsWatched; }, [onMarkAsWatched]); + useEffect(() => { + currentSeasonRef.current = currentSeason; + }, [currentSeason]); + useEffect(() => { + currentEpisodeRef.current = currentEpisode; + }, [currentEpisode]); + useEffect(() => { + autoMarkRef.current = autoMarkWatched; + }, [autoMarkWatched]); + useEffect(() => { + autoMarkPromptShownRef.current = autoMarkPromptShown; + }, [autoMarkPromptShown]); + useEffect(() => { + onMarkAsWatchedRef.current = onMarkAsWatched; + }, [onMarkAsWatched]); // Sync initial values when dialog opens useEffect(() => { @@ -87,13 +92,13 @@ export function StreamingDialog({ useEffect(() => { if (!isOpen) return; const handler = (e: KeyboardEvent) => { - if (e.key === 'Escape') { + if (e.key === "Escape") { closePlayer(); onClose(); } }; - window.addEventListener('keydown', handler); - return () => window.removeEventListener('keydown', handler); + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); }, [isOpen, onClose, closePlayer]); // postMessage listener — handles episode sync + progress + auto-mark @@ -107,13 +112,17 @@ export function StreamingDialog({ const episode = currentEpisodeRef.current; // VidLink MEDIA_DATA: sync current episode from embed navigation - if (event.data?.type === 'MEDIA_DATA') { + if (event.data?.type === "MEDIA_DATA") { const allData = event.data.data; const tmdbId = entry.entryIds?.tmdb_id; if (tmdbId && allData?.[String(tmdbId)]) { const d = allData[String(tmdbId)]; - const s = d.last_season_watched ? parseInt(d.last_season_watched) : null; - const e = d.last_episode_watched ? parseInt(d.last_episode_watched) : null; + const s = d.last_season_watched + ? parseInt(d.last_season_watched) + : null; + const e = d.last_episode_watched + ? parseInt(d.last_episode_watched) + : null; if (s && e && (s !== season || e !== episode)) { setCurrentSeason(s); setCurrentEpisode(e); @@ -125,13 +134,15 @@ export function StreamingDialog({ // PLAYER_EVENT (VidLink + VidKing JSON) let playerData: Record | null = null; - if (event.data?.type === 'PLAYER_EVENT') { + if (event.data?.type === "PLAYER_EVENT") { playerData = event.data.data; - } else if (typeof event.data === 'string') { + } else if (typeof event.data === "string") { try { const parsed = JSON.parse(event.data); - if (parsed?.type === 'PLAYER_EVENT') playerData = parsed.data; - } catch { /* not JSON */ } + if (parsed?.type === "PLAYER_EVENT") playerData = parsed.data; + } catch { + /* not JSON */ + } } if (!playerData) return; @@ -147,10 +158,10 @@ export function StreamingDialog({ } const playerEvent: PlayerEvent = { - event: playerData.event as PlayerEvent['event'], + event: playerData.event as PlayerEvent["event"], currentTime: Number(playerData.currentTime) || 0, duration: Number(playerData.duration) || 0, - mediaType: entry.is_tvseries ? 'tv' : 'movie', + mediaType: entry.is_tvseries ? "tv" : "movie", tmdbId: entry.entryIds?.tmdb_id || 0, season: playerData.season ? Number(playerData.season) : season, episode: playerData.episode ? Number(playerData.episode) : episode, @@ -158,16 +169,20 @@ export function StreamingDialog({ }; if (entry.entryIds?.tmdb_id) { - updateProgressFromEvent(playerEvent, entry.title, entry.poster_path || undefined); + updateProgressFromEvent( + playerEvent, + entry.title, + entry.poster_path || undefined, + ); } const isFinished = - playerEvent.event === 'ended' || - (playerEvent.event === 'timeupdate' && + playerEvent.event === "ended" || + (playerEvent.event === "timeupdate" && isConsideredWatched( playerEvent.currentTime, playerEvent.duration, - autoMarkRef.current.threshold + autoMarkRef.current.threshold, )); if (isFinished) { @@ -187,7 +202,10 @@ export function StreamingDialog({ }); if (autoMarkRef.current.enabled) { - onMarkAsWatchedRef.current?.(playerEvent.season, playerEvent.episode); + onMarkAsWatchedRef.current?.( + playerEvent.season, + playerEvent.episode, + ); markedAsWatched.current.add(key); } else if (!autoMarkPromptShownRef.current) { setShowAutoMarkPrompt(true); @@ -196,8 +214,8 @@ export function StreamingDialog({ } }; - window.addEventListener('message', handler); - return () => window.removeEventListener('message', handler); + window.addEventListener("message", handler); + return () => window.removeEventListener("message", handler); }, [isOpen, entry]); const handleEpisodeSelect = useCallback( @@ -209,7 +227,7 @@ export function StreamingDialog({ const watchProgress = getEntryWatchProgress(entry.entryIds.tmdb_id); const epProgress = watchProgress?.showProgress?.[`s${season}e${episode}`]; play({ - type: 'tv', + type: "tv", tmdbId: entry.entryIds.tmdb_id, imdbId: entry.entryIds?.imdb_id || undefined, season, @@ -217,7 +235,7 @@ export function StreamingDialog({ startAt: epProgress?.watched, }); }, - [entry, play] + [entry, play], ); // Current episode name for the top bar @@ -248,7 +266,8 @@ export function StreamingDialog({ {entry.is_tvseries && ( - S{String(currentSeason).padStart(2, '0')}E{String(currentEpisode).padStart(2, '0')} + S{String(currentSeason).padStart(2, "0")}E + {String(currentEpisode).padStart(2, "0")} {currentEpisodeName && ` — ${currentEpisodeName}`} )} @@ -263,8 +282,8 @@ export function StreamingDialog({ size="sm" className={`h-8 gap-1.5 text-xs transition-colors ${ showSidebar - ? 'text-white bg-white/10 hover:bg-white/15' - : 'text-white/60 hover:text-white hover:bg-white/10' + ? "text-white bg-white/10 hover:bg-white/15" + : "text-white/60 hover:text-white hover:bg-white/10" }`} onClick={() => setShowSidebar((v) => !v)} > @@ -276,7 +295,10 @@ export function StreamingDialog({ variant="ghost" size="icon" className="h-8 w-8 text-white/60 hover:text-white hover:bg-white/10" - onClick={() => { closePlayer(); onClose(); }} + onClick={() => { + closePlayer(); + onClose(); + }} > @@ -305,7 +327,9 @@ export function StreamingDialog({
-

Stream Unavailable

+

+ Stream Unavailable +

{error.message}

@@ -321,7 +345,10 @@ export function StreamingDialog({
, - document.body + document.body, ); } diff --git a/react_frontend/src/components/streaming/index.ts b/react_frontend/src/components/streaming/index.ts index 202b62c..c06cdcd 100644 --- a/react_frontend/src/components/streaming/index.ts +++ b/react_frontend/src/components/streaming/index.ts @@ -1,7 +1,7 @@ -export { StreamingPlayer } from './StreamingPlayer'; -export { StreamingDialog } from './StreamingDialog'; -export { StreamingSection } from './StreamingSection'; -export { ServerSelector } from './ServerSelector'; -export { EpisodesSidebar } from './EpisodesSidebar'; -export { EpisodeNavigator } from './EpisodeNavigator'; -export { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt'; +export { StreamingPlayer } from "./StreamingPlayer"; +export { StreamingDialog } from "./StreamingDialog"; +export { StreamingSection } from "./StreamingSection"; +export { ServerSelector } from "./ServerSelector"; +export { EpisodesSidebar } from "./EpisodesSidebar"; +export { EpisodeNavigator } from "./EpisodeNavigator"; +export { AutoMarkWatchedPrompt } from "./AutoMarkWatchedPrompt"; diff --git a/react_frontend/src/components/ui/avatar.tsx b/react_frontend/src/components/ui/avatar.tsx index e4fed86..7436dc7 100644 --- a/react_frontend/src/components/ui/avatar.tsx +++ b/react_frontend/src/components/ui/avatar.tsx @@ -1,16 +1,16 @@ -"use client" +"use client"; -import * as React from "react" -import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar" +import * as React from "react"; +import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Avatar({ className, size = "default", ...props }: AvatarPrimitive.Root.Props & { - size?: "default" | "sm" | "lg" + size?: "default" | "sm" | "lg"; }) { return ( - ) + ); } function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) { @@ -31,11 +31,11 @@ function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) { data-slot="avatar-image" className={cn( "aspect-square size-full rounded-full object-cover", - className + className, )} {...props} /> - ) + ); } function AvatarFallback({ @@ -47,11 +47,11 @@ function AvatarFallback({ data-slot="avatar-fallback" className={cn( "flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs", - className + className, )} {...props} /> - ) + ); } function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) { @@ -63,11 +63,11 @@ function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) { "group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden", "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2", "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2", - className + className, )} {...props} /> - ) + ); } function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) { @@ -76,11 +76,11 @@ function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) { data-slot="avatar-group" className={cn( "group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background", - className + className, )} {...props} /> - ) + ); } function AvatarGroupCount({ @@ -92,11 +92,11 @@ function AvatarGroupCount({ data-slot="avatar-group-count" className={cn( "relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3", - className + className, )} {...props} /> - ) + ); } export { @@ -106,4 +106,4 @@ export { AvatarGroup, AvatarGroupCount, AvatarBadge, -} +}; diff --git a/react_frontend/src/components/ui/badge.tsx b/react_frontend/src/components/ui/badge.tsx index b20959d..a8cbbac 100644 --- a/react_frontend/src/components/ui/badge.tsx +++ b/react_frontend/src/components/ui/badge.tsx @@ -1,8 +1,8 @@ -import { mergeProps } from "@base-ui/react/merge-props" -import { useRender } from "@base-ui/react/use-render" -import { cva, type VariantProps } from "class-variance-authority" +import { mergeProps } from "@base-ui/react/merge-props"; +import { useRender } from "@base-ui/react/use-render"; +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; const badgeVariants = cva( "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!", @@ -24,8 +24,8 @@ const badgeVariants = cva( defaultVariants: { variant: "default", }, - } -) + }, +); function Badge({ className, @@ -39,14 +39,14 @@ function Badge({ { className: cn(badgeVariants({ variant }), className), }, - props + props, ), render, state: { slot: "badge", variant, }, - }) + }); } -export { Badge, badgeVariants } +export { Badge, badgeVariants }; diff --git a/react_frontend/src/components/ui/button.tsx b/react_frontend/src/components/ui/button.tsx index 444f4ef..145f601 100644 --- a/react_frontend/src/components/ui/button.tsx +++ b/react_frontend/src/components/ui/button.tsx @@ -1,7 +1,7 @@ -import { Button as ButtonPrimitive } from "@base-ui/react/button" -import { cva, type VariantProps } from "class-variance-authority" +import { Button as ButtonPrimitive } from "@base-ui/react/button"; +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; const buttonVariants = cva( "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", @@ -37,8 +37,8 @@ const buttonVariants = cva( variant: "default", size: "default", }, - } -) + }, +); function Button({ className, @@ -52,7 +52,7 @@ function Button({ className={cn(buttonVariants({ variant, size, className }))} {...props} /> - ) + ); } -export { Button, buttonVariants } +export { Button, buttonVariants }; diff --git a/react_frontend/src/components/ui/calendar.tsx b/react_frontend/src/components/ui/calendar.tsx index 1d3044a..5d0de17 100644 --- a/react_frontend/src/components/ui/calendar.tsx +++ b/react_frontend/src/components/ui/calendar.tsx @@ -1,16 +1,20 @@ -"use client" +"use client"; -import * as React from "react" +import * as React from "react"; import { DayPicker, getDefaultClassNames, type DayButton, type Locale, -} from "react-day-picker" +} from "react-day-picker"; -import { cn } from "@/lib/utils" -import { Button, buttonVariants } from "@/components/ui/button" -import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react" +import { cn } from "@/lib/utils"; +import { Button, buttonVariants } from "@/components/ui/button"; +import { + ChevronLeftIcon, + ChevronRightIcon, + ChevronDownIcon, +} from "lucide-react"; function Calendar({ className, @@ -23,9 +27,9 @@ function Calendar({ components, ...props }: React.ComponentProps & { - buttonVariant?: React.ComponentProps["variant"] + buttonVariant?: React.ComponentProps["variant"]; }) { - const defaultClassNames = getDefaultClassNames() + const defaultClassNames = getDefaultClassNames(); return ( svg]:rotate-180`, String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`, - className + className, )} captionLayout={captionLayout} locale={locale} @@ -47,88 +51,88 @@ function Calendar({ root: cn("w-fit", defaultClassNames.root), months: cn( "relative flex flex-col gap-4 md:flex-row", - defaultClassNames.months + defaultClassNames.months, ), month: cn("flex w-full flex-col gap-4", defaultClassNames.month), nav: cn( "absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1", - defaultClassNames.nav + defaultClassNames.nav, ), button_previous: cn( buttonVariants({ variant: buttonVariant }), "size-(--cell-size) p-0 select-none aria-disabled:opacity-50", - defaultClassNames.button_previous + defaultClassNames.button_previous, ), button_next: cn( buttonVariants({ variant: buttonVariant }), "size-(--cell-size) p-0 select-none aria-disabled:opacity-50", - defaultClassNames.button_next + defaultClassNames.button_next, ), month_caption: cn( "flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)", - defaultClassNames.month_caption + defaultClassNames.month_caption, ), dropdowns: cn( "flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium", - defaultClassNames.dropdowns + defaultClassNames.dropdowns, ), dropdown_root: cn( "relative rounded-(--cell-radius)", - defaultClassNames.dropdown_root + defaultClassNames.dropdown_root, ), dropdown: cn( "absolute inset-0 bg-popover opacity-0", - defaultClassNames.dropdown + defaultClassNames.dropdown, ), caption_label: cn( "font-medium select-none", captionLayout === "label" ? "text-sm" : "flex items-center gap-1 rounded-(--cell-radius) text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground", - defaultClassNames.caption_label + defaultClassNames.caption_label, ), table: "w-full border-collapse", weekdays: cn("flex", defaultClassNames.weekdays), weekday: cn( "flex-1 rounded-(--cell-radius) text-[0.8rem] font-normal text-muted-foreground select-none", - defaultClassNames.weekday + defaultClassNames.weekday, ), week: cn("mt-2 flex w-full", defaultClassNames.week), week_number_header: cn( "w-(--cell-size) select-none", - defaultClassNames.week_number_header + defaultClassNames.week_number_header, ), week_number: cn( "text-[0.8rem] text-muted-foreground select-none", - defaultClassNames.week_number + defaultClassNames.week_number, ), day: cn( "group/day relative aspect-square h-full w-full rounded-(--cell-radius) p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius)", props.showWeekNumber ? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)" : "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)", - defaultClassNames.day + defaultClassNames.day, ), range_start: cn( "relative isolate z-0 rounded-l-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted", - defaultClassNames.range_start + defaultClassNames.range_start, ), range_middle: cn("rounded-none", defaultClassNames.range_middle), range_end: cn( "relative isolate z-0 rounded-r-(--cell-radius) bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted", - defaultClassNames.range_end + defaultClassNames.range_end, ), today: cn( "rounded-(--cell-radius) bg-muted text-foreground data-[selected=true]:rounded-none", - defaultClassNames.today + defaultClassNames.today, ), outside: cn( "text-muted-foreground aria-selected:text-muted-foreground", - defaultClassNames.outside + defaultClassNames.outside, ), disabled: cn( "text-muted-foreground opacity-50", - defaultClassNames.disabled + defaultClassNames.disabled, ), hidden: cn("invisible", defaultClassNames.hidden), ...classNames, @@ -142,24 +146,27 @@ function Calendar({ className={cn(className)} {...props} /> - ) + ); }, Chevron: ({ className, orientation, ...props }) => { if (orientation === "left") { return ( - ) + ); } if (orientation === "right") { return ( - - ) + + ); } return ( - ) + ); }, DayButton: ({ ...props }) => ( @@ -171,13 +178,13 @@ function Calendar({ {children}
- ) + ); }, ...components, }} {...props} /> - ) + ); } function CalendarDayButton({ @@ -187,12 +194,12 @@ function CalendarDayButton({ locale, ...props }: React.ComponentProps & { locale?: Partial }) { - const defaultClassNames = getDefaultClassNames() + const defaultClassNames = getDefaultClassNames(); - const ref = React.useRef(null) + const ref = React.useRef(null); React.useEffect(() => { - if (modifiers.focused) ref.current?.focus() - }, [modifiers.focused]) + if (modifiers.focused) ref.current?.focus(); + }, [modifiers.focused]); return (
diff --git a/react_frontend/src/components/ui/switch.tsx b/react_frontend/src/components/ui/switch.tsx index 9498efe..d0b82e2 100644 --- a/react_frontend/src/components/ui/switch.tsx +++ b/react_frontend/src/components/ui/switch.tsx @@ -1,13 +1,13 @@ -import { Switch as SwitchPrimitive } from "@base-ui/react/switch" +import { Switch as SwitchPrimitive } from "@base-ui/react/switch"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Switch({ className, size = "default", ...props }: SwitchPrimitive.Root.Props & { - size?: "sm" | "default" + size?: "sm" | "default"; }) { return ( @@ -24,7 +24,7 @@ function Switch({ className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground" /> - ) + ); } -export { Switch } +export { Switch }; diff --git a/react_frontend/src/components/ui/tabs.tsx b/react_frontend/src/components/ui/tabs.tsx index 56c4288..ff8532e 100644 --- a/react_frontend/src/components/ui/tabs.tsx +++ b/react_frontend/src/components/ui/tabs.tsx @@ -1,9 +1,9 @@ -"use client" +"use client"; -import { Tabs as TabsPrimitive } from "@base-ui/react/tabs" -import { cva, type VariantProps } from "class-variance-authority" +import { Tabs as TabsPrimitive } from "@base-ui/react/tabs"; +import { cva, type VariantProps } from "class-variance-authority"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Tabs({ className, @@ -16,11 +16,11 @@ function Tabs({ data-orientation={orientation} className={cn( "group/tabs flex gap-2 data-horizontal:flex-col", - className + className, )} {...props} /> - ) + ); } const tabsListVariants = cva( @@ -35,8 +35,8 @@ const tabsListVariants = cva( defaultVariants: { variant: "default", }, - } -) + }, +); function TabsList({ className, @@ -50,7 +50,7 @@ function TabsList({ className={cn(tabsListVariants({ variant }), className)} {...props} /> - ) + ); } function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) { @@ -62,11 +62,11 @@ function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) { "group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent", "data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground", "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100", - className + className, )} {...props} /> - ) + ); } function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) { @@ -76,7 +76,7 @@ function TabsContent({ className, ...props }: TabsPrimitive.Panel.Props) { className={cn("flex-1 text-sm outline-none", className)} {...props} /> - ) + ); } -export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants } +export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }; diff --git a/react_frontend/src/components/ui/textarea.tsx b/react_frontend/src/components/ui/textarea.tsx index 04d27f7..d102c70 100644 --- a/react_frontend/src/components/ui/textarea.tsx +++ b/react_frontend/src/components/ui/textarea.tsx @@ -1,6 +1,6 @@ -import * as React from "react" +import * as React from "react"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function Textarea({ className, ...props }: React.ComponentProps<"textarea">) { return ( @@ -8,11 +8,11 @@ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) { data-slot="textarea" className={cn( "flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40", - className + className, )} {...props} /> - ) + ); } -export { Textarea } +export { Textarea }; diff --git a/react_frontend/src/hooks/useCollections.ts b/react_frontend/src/hooks/useCollections.ts index cb22eeb..189be2b 100644 --- a/react_frontend/src/hooks/useCollections.ts +++ b/react_frontend/src/hooks/useCollections.ts @@ -1,10 +1,10 @@ -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { toast } from 'sonner'; -import { collectionsApi } from '@/api/collections'; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { collectionsApi } from "@/api/collections"; export const collectionKeys = { - all: ['collections'] as const, - detail: (id: number) => ['collections', id] as const, + all: ["collections"] as const, + detail: (id: number) => ["collections", id] as const, }; export function useCollections() { @@ -29,12 +29,14 @@ export function useUpdateCollection() { mutationFn: ({ id, data }: { id: number; data: FormData }) => collectionsApi.updateWithMedia(id, data), onSuccess: (_data, variables) => { - queryClient.invalidateQueries({ queryKey: collectionKeys.detail(variables.id) }); + queryClient.invalidateQueries({ + queryKey: collectionKeys.detail(variables.id), + }); queryClient.invalidateQueries({ queryKey: collectionKeys.all }); - toast.success('Collection updated'); + toast.success("Collection updated"); }, onError: () => { - toast.error('Failed to update collection'); + toast.error("Failed to update collection"); }, }); } @@ -46,10 +48,10 @@ export function useDeleteCollection() { mutationFn: (id: number) => collectionsApi.delete(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: collectionKeys.all }); - toast.success('Collection deleted'); + toast.success("Collection deleted"); }, onError: () => { - toast.error('Failed to delete collection'); + toast.error("Failed to delete collection"); }, }); } @@ -62,10 +64,10 @@ export function useGetCollectionParts() { onSuccess: (_data, id) => { queryClient.invalidateQueries({ queryKey: collectionKeys.detail(id) }); queryClient.invalidateQueries({ queryKey: collectionKeys.all }); - toast.success('Collection parts fetched'); + toast.success("Collection parts fetched"); }, onError: () => { - toast.error('Failed to fetch collection parts'); + toast.error("Failed to fetch collection parts"); }, }); } @@ -74,15 +76,22 @@ export function useRemoveEntryFromCollection() { const queryClient = useQueryClient(); return useMutation({ - mutationFn: ({ collectionId, entryId }: { collectionId: number; entryId: number }) => - collectionsApi.removeEntry(collectionId, entryId), + mutationFn: ({ + collectionId, + entryId, + }: { + collectionId: number; + entryId: number; + }) => collectionsApi.removeEntry(collectionId, entryId), onSuccess: (_data, { collectionId }) => { - queryClient.invalidateQueries({ queryKey: collectionKeys.detail(collectionId) }); + queryClient.invalidateQueries({ + queryKey: collectionKeys.detail(collectionId), + }); queryClient.invalidateQueries({ queryKey: collectionKeys.all }); - toast.success('Entry removed from collection'); + toast.success("Entry removed from collection"); }, onError: () => { - toast.error('Failed to remove entry from collection'); + toast.error("Failed to remove entry from collection"); }, }); } diff --git a/react_frontend/src/hooks/useDebounce.ts b/react_frontend/src/hooks/useDebounce.ts index 680704e..e3ab66c 100644 --- a/react_frontend/src/hooks/useDebounce.ts +++ b/react_frontend/src/hooks/useDebounce.ts @@ -1,4 +1,4 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect } from "react"; export function useDebounce(value: T, delay = 300): T { const [debouncedValue, setDebouncedValue] = useState(value); diff --git a/react_frontend/src/hooks/useEntrySeen.ts b/react_frontend/src/hooks/useEntrySeen.ts index 6666fee..4618ae5 100644 --- a/react_frontend/src/hooks/useEntrySeen.ts +++ b/react_frontend/src/hooks/useEntrySeen.ts @@ -1,11 +1,11 @@ -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { toast } from 'sonner'; -import { entrySeenApi } from '@/api/entry-seen'; -import { entryKeys } from './useEntries'; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { entrySeenApi } from "@/api/entry-seen"; +import { entryKeys } from "./useEntries"; export const entrySeenKeys = { - all: ['entry-seen'] as const, - byEntry: (entryId: number) => ['entry-seen', 'by-entry', entryId] as const, + all: ["entry-seen"] as const, + byEntry: (entryId: number) => ["entry-seen", "by-entry", entryId] as const, }; export function useEntrySeenByEntry(entryId: number) { @@ -34,10 +34,10 @@ export function useCreateEntrySeen() { queryKey: entryKeys.detail(variables.entry_id), }); queryClient.invalidateQueries({ queryKey: entryKeys.all }); - toast.success('Marked as watched'); + toast.success("Marked as watched"); }, onError: () => { - toast.error('Failed to mark as watched'); + toast.error("Failed to mark as watched"); }, }); } @@ -51,16 +51,21 @@ export function useUpdateEntrySeen() { data, }: { id: number; - data: { entry_id: number; date_seen?: string; seen_with?: string; accuracy?: 'EXACT' | 'ESTIMATED' | 'UNKNOWN' }; + data: { + entry_id: number; + date_seen?: string; + seen_with?: string; + accuracy?: "EXACT" | "ESTIMATED" | "UNKNOWN"; + }; }) => entrySeenApi.update(id, data), onSuccess: (_data, variables) => { queryClient.invalidateQueries({ queryKey: entrySeenKeys.byEntry(variables.data.entry_id), }); - toast.success('Watch record updated'); + toast.success("Watch record updated"); }, onError: () => { - toast.error('Failed to update watch record'); + toast.error("Failed to update watch record"); }, }); } @@ -76,10 +81,10 @@ export function useDeleteEntrySeen() { queryKey: entrySeenKeys.byEntry(variables.entryId), }); queryClient.invalidateQueries({ queryKey: entryKeys.all }); - toast.success('Watch record removed'); + toast.success("Watch record removed"); }, onError: () => { - toast.error('Failed to remove watch record'); + toast.error("Failed to remove watch record"); }, }); } diff --git a/react_frontend/src/hooks/useEpisodeSeen.ts b/react_frontend/src/hooks/useEpisodeSeen.ts index 381cf5d..dad5da3 100644 --- a/react_frontend/src/hooks/useEpisodeSeen.ts +++ b/react_frontend/src/hooks/useEpisodeSeen.ts @@ -1,13 +1,13 @@ -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { toast } from 'sonner'; -import { episodeSeenApi } from '@/api/episode-seen'; -import { entryKeys } from './useEntries'; -import { seasonKeys } from './useSeasons'; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { episodeSeenApi } from "@/api/episode-seen"; +import { entryKeys } from "./useEntries"; +import { seasonKeys } from "./useSeasons"; export const episodeSeenKeys = { - all: ['episode-seen'] as const, + all: ["episode-seen"] as const, byEpisode: (episodeId: number) => - ['episode-seen', 'by-episode', episodeId] as const, + ["episode-seen", "by-episode", episodeId] as const, }; export function useEpisodeSeenByEpisode(episodeId: number) { @@ -45,10 +45,10 @@ export function useCreateEpisodeSeen() { queryKey: seasonKeys.episodes(variables.season_id), }); } - toast.success('Episode marked as watched'); + toast.success("Episode marked as watched"); }, onError: () => { - toast.error('Failed to mark episode as watched'); + toast.error("Failed to mark episode as watched"); }, }); } @@ -62,7 +62,13 @@ export function useUpdateEpisodeSeen() { data, }: { id: number; - data: { episode_id: number; entry_id: number; date_seen?: string; seen_with?: string | null; accuracy?: 'EXACT' | 'ESTIMATED' | 'UNKNOWN' }; + data: { + episode_id: number; + entry_id: number; + date_seen?: string; + seen_with?: string | null; + accuracy?: "EXACT" | "ESTIMATED" | "UNKNOWN"; + }; }) => episodeSeenApi.update(id, data), onSuccess: (_data, variables) => { queryClient.invalidateQueries({ @@ -71,10 +77,10 @@ export function useUpdateEpisodeSeen() { queryClient.invalidateQueries({ queryKey: entryKeys.detail(variables.data.entry_id), }); - toast.success('Episode watch record updated'); + toast.success("Episode watch record updated"); }, onError: () => { - toast.error('Failed to update episode watch record'); + toast.error("Failed to update episode watch record"); }, }); } @@ -108,10 +114,10 @@ export function useDeleteEpisodeSeen() { queryKey: seasonKeys.episodes(variables.seasonId), }); } - toast.success('Episode watch record removed'); + toast.success("Episode watch record removed"); }, onError: () => { - toast.error('Failed to remove episode watch record'); + toast.error("Failed to remove episode watch record"); }, }); } diff --git a/react_frontend/src/hooks/useEpisodes.ts b/react_frontend/src/hooks/useEpisodes.ts index 3186043..9e17d93 100644 --- a/react_frontend/src/hooks/useEpisodes.ts +++ b/react_frontend/src/hooks/useEpisodes.ts @@ -1,9 +1,9 @@ -import { useQuery } from '@tanstack/react-query'; -import { episodesApi } from '@/api/episodes'; +import { useQuery } from "@tanstack/react-query"; +import { episodesApi } from "@/api/episodes"; export const episodeKeys = { byMonth: (start: string, end: string) => - ['episodes', 'month', start, end] as const, + ["episodes", "month", start, end] as const, }; export function useEpisodesByMonth(startDate: string, endDate: string) { diff --git a/react_frontend/src/hooks/usePeople.ts b/react_frontend/src/hooks/usePeople.ts index f88bf59..403c729 100644 --- a/react_frontend/src/hooks/usePeople.ts +++ b/react_frontend/src/hooks/usePeople.ts @@ -1,13 +1,18 @@ -import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from '@tanstack/react-query'; -import { toast } from 'sonner'; -import { peopleApi } from '@/api/people'; +import { + useQuery, + useMutation, + useQueryClient, + useInfiniteQuery, +} from "@tanstack/react-query"; +import { toast } from "sonner"; +import { peopleApi } from "@/api/people"; export const peopleKeys = { - all: ['people'] as const, - detail: (id: number) => ['people', id] as const, - credits: (id: number) => ['people', id, 'credits'] as const, - tmdbFilmography: (id: number) => ['people', id, 'tmdb-filmography'] as const, - tmdbPreview: (tmdbId: number) => ['people', 'tmdb-preview', tmdbId] as const, + all: ["people"] as const, + detail: (id: number) => ["people", id] as const, + credits: (id: number) => ["people", id, "credits"] as const, + tmdbFilmography: (id: number) => ["people", id, "tmdb-filmography"] as const, + tmdbPreview: (tmdbId: number) => ["people", "tmdb-preview", tmdbId] as const, }; export function usePerson(id: number) { @@ -54,22 +59,30 @@ export function useUpdatePerson() { const queryClient = useQueryClient(); return useMutation({ - mutationFn: ({ id, data }: { id: number; data: Partial }) => - peopleApi.update(id, data), + mutationFn: ({ + id, + data, + }: { + id: number; + data: Partial; + }) => peopleApi.update(id, data), onSuccess: (updatedPerson) => { - queryClient.invalidateQueries({ queryKey: peopleKeys.detail(updatedPerson.id) }); - toast.success('Person updated'); + queryClient.invalidateQueries({ + queryKey: peopleKeys.detail(updatedPerson.id), + }); + toast.success("Person updated"); }, onError: () => { - toast.error('Failed to update person'); + toast.error("Failed to update person"); }, }); } export function useSearchLocalPeople(query: string) { return useQuery({ - queryKey: ['people', 'search', query], - queryFn: () => query === '*' ? peopleApi.getAll() : peopleApi.search(query), + queryKey: ["people", "search", query], + queryFn: () => + query === "*" ? peopleApi.getAll() : peopleApi.search(query), enabled: query.length > 0, }); } @@ -78,9 +91,13 @@ const LOCAL_PEOPLE_PAGE_SIZE = 48; export function useLocalPeopleInfinite(search: string, enabled: boolean) { return useInfiniteQuery({ - queryKey: ['people', 'paginated', search], + queryKey: ["people", "paginated", search], queryFn: ({ pageParam = 1 }) => - peopleApi.getAllPaginated(pageParam, LOCAL_PEOPLE_PAGE_SIZE, search || undefined), + peopleApi.getAllPaginated( + pageParam, + LOCAL_PEOPLE_PAGE_SIZE, + search || undefined, + ), getNextPageParam: (lastPage) => lastPage.page < lastPage.totalPages ? lastPage.page + 1 : undefined, initialPageParam: 1, diff --git a/react_frontend/src/hooks/useSeasons.ts b/react_frontend/src/hooks/useSeasons.ts index 9b3987f..1dceb2a 100644 --- a/react_frontend/src/hooks/useSeasons.ts +++ b/react_frontend/src/hooks/useSeasons.ts @@ -1,10 +1,10 @@ -import { useQuery } from '@tanstack/react-query'; -import { seasonsApi } from '@/api/seasons'; +import { useQuery } from "@tanstack/react-query"; +import { seasonsApi } from "@/api/seasons"; export const seasonKeys = { - all: ['seasons'] as const, - detail: (id: number) => ['seasons', id] as const, - episodes: (id: number) => ['seasons', id, 'episodes'] as const, + all: ["seasons"] as const, + detail: (id: number) => ["seasons", id] as const, + episodes: (id: number) => ["seasons", id, "episodes"] as const, }; export function useSeason(id: number) { diff --git a/react_frontend/src/hooks/useStatistics.ts b/react_frontend/src/hooks/useStatistics.ts index 511842e..ca201ee 100644 --- a/react_frontend/src/hooks/useStatistics.ts +++ b/react_frontend/src/hooks/useStatistics.ts @@ -1,30 +1,30 @@ -import { useQuery } from '@tanstack/react-query'; -import { statisticsApi } from '@/api/statistics'; +import { useQuery } from "@tanstack/react-query"; +import { statisticsApi } from "@/api/statistics"; export function useStatistics() { return useQuery({ - queryKey: ['statistics', 'watch-time-all'], + queryKey: ["statistics", "watch-time-all"], queryFn: statisticsApi.getAllTimeWatchTime, }); } export function useYearlyWatchCount(year: number) { return useQuery({ - queryKey: ['statistics', 'watch-count', year], + queryKey: ["statistics", "watch-count", year], queryFn: () => statisticsApi.getYearlyWatchCount(year), }); } export function useYearlyWatchTime(year: number) { return useQuery({ - queryKey: ['statistics', 'watch-time', year], + queryKey: ["statistics", "watch-time", year], queryFn: () => statisticsApi.getYearlyWatchTime(year), }); } export function useWatchdayDistribution() { return useQuery({ - queryKey: ['statistics', 'watch-weekday'], + queryKey: ["statistics", "watch-weekday"], queryFn: statisticsApi.getWatchdayDistribution, }); } diff --git a/react_frontend/src/hooks/useTmdb.ts b/react_frontend/src/hooks/useTmdb.ts index ebb4019..6043fc1 100644 --- a/react_frontend/src/hooks/useTmdb.ts +++ b/react_frontend/src/hooks/useTmdb.ts @@ -1,9 +1,9 @@ -import { useInfiniteQuery } from '@tanstack/react-query'; -import { tmdbApi } from '@/api/tmdb'; +import { useInfiniteQuery } from "@tanstack/react-query"; +import { tmdbApi } from "@/api/tmdb"; export function usePopularMovies() { return useInfiniteQuery({ - queryKey: ['tmdb', 'popular', 'movie'], + queryKey: ["tmdb", "popular", "movie"], queryFn: ({ pageParam }) => tmdbApi.getPopularMovies(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -13,7 +13,7 @@ export function usePopularMovies() { export function usePopularTv() { return useInfiniteQuery({ - queryKey: ['tmdb', 'popular', 'tv'], + queryKey: ["tmdb", "popular", "tv"], queryFn: ({ pageParam }) => tmdbApi.getPopularTv(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -23,7 +23,7 @@ export function usePopularTv() { export function useTrendingMovies() { return useInfiniteQuery({ - queryKey: ['tmdb', 'trending', 'movie'], + queryKey: ["tmdb", "trending", "movie"], queryFn: ({ pageParam }) => tmdbApi.getTrendingMovies(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -33,7 +33,7 @@ export function useTrendingMovies() { export function useTrendingTv() { return useInfiniteQuery({ - queryKey: ['tmdb', 'trending', 'tv'], + queryKey: ["tmdb", "trending", "tv"], queryFn: ({ pageParam }) => tmdbApi.getTrendingTv(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -43,7 +43,7 @@ export function useTrendingTv() { export function useTopRatedMovies() { return useInfiniteQuery({ - queryKey: ['tmdb', 'top-rated', 'movie'], + queryKey: ["tmdb", "top-rated", "movie"], queryFn: ({ pageParam }) => tmdbApi.getTopRatedMovies(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -53,7 +53,7 @@ export function useTopRatedMovies() { export function useTopRatedTv() { return useInfiniteQuery({ - queryKey: ['tmdb', 'top-rated', 'tv'], + queryKey: ["tmdb", "top-rated", "tv"], queryFn: ({ pageParam }) => tmdbApi.getTopRatedTv(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -63,7 +63,7 @@ export function useTopRatedTv() { export function useUpcomingMovies() { return useInfiniteQuery({ - queryKey: ['tmdb', 'upcoming', 'movie'], + queryKey: ["tmdb", "upcoming", "movie"], queryFn: ({ pageParam }) => tmdbApi.getUpcomingMovies(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -73,7 +73,7 @@ export function useUpcomingMovies() { export function useTmdbSearch(query: string) { return useInfiniteQuery({ - queryKey: ['tmdb', 'search', query], + queryKey: ["tmdb", "search", query], queryFn: ({ pageParam }) => tmdbApi.search(query, pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -84,7 +84,7 @@ export function useTmdbSearch(query: string) { export function usePopularPeople() { return useInfiniteQuery({ - queryKey: ['tmdb', 'popular', 'people'], + queryKey: ["tmdb", "popular", "people"], queryFn: ({ pageParam }) => tmdbApi.getPopularPeople(pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => @@ -94,7 +94,7 @@ export function usePopularPeople() { export function useTmdbSearchPeople(query: string) { return useInfiniteQuery({ - queryKey: ['tmdb', 'search', 'people', query], + queryKey: ["tmdb", "search", "people", query], queryFn: ({ pageParam }) => tmdbApi.searchPeople(query, pageParam), initialPageParam: 1, getNextPageParam: (lastPage) => diff --git a/react_frontend/src/hooks/useTmdbEntryLink.ts b/react_frontend/src/hooks/useTmdbEntryLink.ts index 01163f1..fe497dd 100644 --- a/react_frontend/src/hooks/useTmdbEntryLink.ts +++ b/react_frontend/src/hooks/useTmdbEntryLink.ts @@ -1,6 +1,6 @@ -import { useMemo } from 'react'; -import { useLibraryStore } from '@/stores/useLibraryStore'; -import type { TmdbEntry } from '@/types'; +import { useMemo } from "react"; +import { useLibraryStore } from "@/stores/useLibraryStore"; +import type { TmdbEntry } from "@/types"; interface TmdbEntryLink { /** The resolved link — either /entry/:id if in library, or /entry/tmdb/:type/:id */ @@ -20,7 +20,7 @@ export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink { const libraryEntries = useLibraryStore((s) => s.entries); return useMemo(() => { - const isTv = entry.media_type === 'tv' || !!entry.name; + const isTv = entry.media_type === "tv" || !!entry.name; const libraryEntry = Array.from(libraryEntries.values()).find( (e) => e.entryIds?.tmdb_id === entry.id, ); @@ -34,7 +34,7 @@ export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink { } return { - linkTo: `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`, + linkTo: `/entry/tmdb/${isTv ? "tv" : "movie"}/${entry.id}`, isInLibrary: false, libraryEntryId: null, }; diff --git a/react_frontend/src/lib/api.ts b/react_frontend/src/lib/api.ts index d38279c..736e8ff 100644 --- a/react_frontend/src/lib/api.ts +++ b/react_frontend/src/lib/api.ts @@ -1,22 +1,23 @@ -import axios from 'axios'; +import axios from "axios"; -const API_BASE_URL = import.meta.env.VITE_ELECTRON === 'true' - ? 'http://localhost:4000/api/v1' - : (import.meta.env.VITE_API_URL || '/api/v1'); +const API_BASE_URL = + import.meta.env.VITE_ELECTRON === "true" + ? "http://localhost:4000/api/v1" + : import.meta.env.VITE_API_URL || "/api/v1"; export const api = axios.create({ baseURL: API_BASE_URL, headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, }); export const getMediaUrl = ( category: string, type: string, - size: 'preview' | 'full', - file: string + size: "preview" | "full", + file: string, ) => `${API_BASE_URL}/media/${category}/${type}/${size}/${file}`; -export const getTmdbImageUrl = (path: string, size = 'w342') => +export const getTmdbImageUrl = (path: string, size = "w342") => `https://image.tmdb.org/t/p/${size}${path}`; diff --git a/react_frontend/src/lib/media-utils.ts b/react_frontend/src/lib/media-utils.ts index 275e9fb..0cda7da 100644 --- a/react_frontend/src/lib/media-utils.ts +++ b/react_frontend/src/lib/media-utils.ts @@ -1,29 +1,29 @@ -import { getMediaUrl, getTmdbImageUrl } from '@/lib/api'; -import type { Entry, Collection, Media } from '@/types'; +import { getMediaUrl, getTmdbImageUrl } from "@/lib/api"; +import type { Entry, Collection, Media } from "@/types"; -const DEFAULT_POSTER = '/images/default-poster.png'; +const DEFAULT_POSTER = "/images/default-poster.png"; export function getPosterUrl(entry: Entry): string { // Not in library, use TMDB poster if (!entry.isInLibrary) { return entry.poster_path - ? getTmdbImageUrl(entry.poster_path, 'w342') + ? getTmdbImageUrl(entry.poster_path, "w342") : DEFAULT_POSTER; } // In library: try local selected poster if (entry.medias) { const selectedPoster = entry.medias.find( - (m: Media) => m.type === 'poster' && m.is_selected + (m: Media) => m.type === "poster" && m.is_selected, ); if (selectedPoster?.path) { - return getMediaUrl('entries', 'posters', 'preview', selectedPoster.path); + return getMediaUrl("entries", "posters", "preview", selectedPoster.path); } } // Fallback to TMDB poster if (entry.poster_path) { - return getTmdbImageUrl(entry.poster_path, 'w300'); + return getTmdbImageUrl(entry.poster_path, "w300"); } return DEFAULT_POSTER; @@ -32,28 +32,23 @@ export function getPosterUrl(entry: Entry): string { export function getBackdropUrl(entry: Entry): string { if (entry.medias) { const selectedBackdrop = entry.medias.find( - (m: Media) => m.type === 'backdrop' && m.is_selected + (m: Media) => m.type === "backdrop" && m.is_selected, ); if (selectedBackdrop?.path) { - return getMediaUrl( - 'entries', - 'backdrops', - 'full', - selectedBackdrop.path - ); + return getMediaUrl("entries", "backdrops", "full", selectedBackdrop.path); } } if (entry.banner_path) { - return getTmdbImageUrl(entry.banner_path, 'w1280'); + return getTmdbImageUrl(entry.banner_path, "w1280"); } - return ''; + return ""; } export function getTmdbPosterUrl( posterPath: string | null, - size = 'w342' + size = "w342", ): string { if (!posterPath) return DEFAULT_POSTER; return getTmdbImageUrl(posterPath, size); @@ -62,14 +57,19 @@ export function getTmdbPosterUrl( export function getCollectionBackdropUrl(collection: Collection): string { if (collection.medias) { const selectedBackdrop = collection.medias.find( - (m: Media) => m.type === 'backdrop' && m.is_selected + (m: Media) => m.type === "backdrop" && m.is_selected, ); if (selectedBackdrop?.path) { - return getMediaUrl('collections', 'backdrops', 'full', selectedBackdrop.path); + return getMediaUrl( + "collections", + "backdrops", + "full", + selectedBackdrop.path, + ); } } if (collection.backdrop_path) { - return getTmdbImageUrl(collection.backdrop_path, 'w780'); + return getTmdbImageUrl(collection.backdrop_path, "w780"); } return getCollectionPosterUrl(collection); } @@ -77,42 +77,47 @@ export function getCollectionBackdropUrl(collection: Collection): string { export function getCollectionPosterUrl(collection: Collection): string { if (collection.medias) { const selectedPoster = collection.medias.find( - (m: Media) => m.type === 'poster' && m.is_selected + (m: Media) => m.type === "poster" && m.is_selected, ); if (selectedPoster?.path) { - return getMediaUrl('collections', 'posters', 'preview', selectedPoster.path); + return getMediaUrl( + "collections", + "posters", + "preview", + selectedPoster.path, + ); } } if (collection.poster_path) { - return getTmdbImageUrl(collection.poster_path, 'w342'); + return getTmdbImageUrl(collection.poster_path, "w342"); } return DEFAULT_POSTER; } export function getProfileUrl(profilePath: string | null): string { - if (!profilePath) return '/images/default-profile.png'; - return getTmdbImageUrl(profilePath, 'w185'); + if (!profilePath) return "/images/default-profile.png"; + return getTmdbImageUrl(profilePath, "w185"); } export function formatRuntime(minutes: number | null): string { - if (!minutes) return ''; + if (!minutes) return ""; const h = Math.floor(minutes / 60); const m = minutes % 60; return h > 0 ? `${h}h ${m}m` : `${m}m`; } export function formatDate(dateStr: string | null): string { - if (!dateStr) return ''; - return new Date(dateStr).toLocaleDateString('en-US', { - year: 'numeric', - month: 'short', - day: 'numeric', + if (!dateStr) return ""; + return new Date(dateStr).toLocaleDateString("en-US", { + year: "numeric", + month: "short", + day: "numeric", }); } export function getYear(dateStr: string | null): string { - if (!dateStr) return ''; + if (!dateStr) return ""; return new Date(dateStr).getFullYear().toString(); } diff --git a/react_frontend/src/lib/streaming/index.ts b/react_frontend/src/lib/streaming/index.ts index 70d9a1e..d9f749b 100644 --- a/react_frontend/src/lib/streaming/index.ts +++ b/react_frontend/src/lib/streaming/index.ts @@ -1,4 +1,15 @@ -export type { StreamingProvider, StreamingServer, StreamRequest, StreamResponse, StreamError, PlayerEvent, WatchProgressData, AutoMarkWatchedConfig, StreamingState, MediaType } from './types'; +export type { + StreamingProvider, + StreamingServer, + StreamRequest, + StreamResponse, + StreamError, + PlayerEvent, + WatchProgressData, + AutoMarkWatchedConfig, + StreamingState, + MediaType, +} from "./types"; export { getAllServers, getProviderForServer, @@ -23,4 +34,4 @@ export { isConsideredWatched, isValidEmbedUrl, isValidEventOrigin, -} from './streaming-manager'; +} from "./streaming-manager"; diff --git a/react_frontend/src/lib/streaming/providers/anyembed.ts b/react_frontend/src/lib/streaming/providers/anyembed.ts index fe1087f..63b9cc2 100644 --- a/react_frontend/src/lib/streaming/providers/anyembed.ts +++ b/react_frontend/src/lib/streaming/providers/anyembed.ts @@ -1,42 +1,46 @@ -import type { StreamingProvider, StreamingServer, StreamRequest } from '../types'; +import type { + StreamingProvider, + StreamingServer, + StreamRequest, +} from "../types"; const ANYEMBED_SERVERS: StreamingServer[] = [ { - id: 'anyembed-1', - name: 'AnyEmbed (Server 1)', - provider: 'anyembed', + id: "anyembed-1", + name: "AnyEmbed (Server 1)", + provider: "anyembed", serverIndex: 1, supportsEvents: false, supportsProgress: false, }, { - id: 'anyembed-2', - name: 'AnyEmbed (Server 2)', - provider: 'anyembed', + id: "anyembed-2", + name: "AnyEmbed (Server 2)", + provider: "anyembed", serverIndex: 2, supportsEvents: false, supportsProgress: false, }, { - id: 'anyembed-3', - name: 'AnyEmbed (Server 3)', - provider: 'anyembed', + id: "anyembed-3", + name: "AnyEmbed (Server 3)", + provider: "anyembed", serverIndex: 3, supportsEvents: false, supportsProgress: false, }, { - id: 'anyembed-4', - name: 'AnyEmbed (Server 4)', - provider: 'anyembed', + id: "anyembed-4", + name: "AnyEmbed (Server 4)", + provider: "anyembed", serverIndex: 4, supportsEvents: false, supportsProgress: false, }, { - id: 'anyembed-5', - name: 'AnyEmbed (Server 5)', - provider: 'anyembed', + id: "anyembed-5", + name: "AnyEmbed (Server 5)", + provider: "anyembed", serverIndex: 5, supportsEvents: false, supportsProgress: false, @@ -44,8 +48,8 @@ const ANYEMBED_SERVERS: StreamingServer[] = [ ]; export const anyembedProvider: StreamingProvider = { - id: 'anyembed', - name: 'AnyEmbed', + id: "anyembed", + name: "AnyEmbed", servers: ANYEMBED_SERVERS, getStreamUrl(request: StreamRequest, server: StreamingServer): string { @@ -53,7 +57,7 @@ export const anyembedProvider: StreamingProvider = { const id = request.imdbId || String(request.tmdbId); let basePath: string; - if (request.type === 'movie') { + if (request.type === "movie") { basePath = `/movie/${id}`; } else { basePath = `/tv/${id}/${request.season}/${request.episode}`; @@ -61,18 +65,18 @@ export const anyembedProvider: StreamingProvider = { const params = new URLSearchParams(); if (server.serverIndex) { - params.set('server', String(server.serverIndex)); + params.set("server", String(server.serverIndex)); } const query = params.toString(); - return `https://anyembed.xyz${basePath}${query ? `?${query}` : ''}`; + return `https://anyembed.xyz${basePath}${query ? `?${query}` : ""}`; }, getSandboxPolicy(): string { - return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation'; + return "allow-scripts allow-same-origin allow-forms allow-popups allow-presentation"; }, getAllowedFeatures(): string { - return 'autoplay; fullscreen; picture-in-picture; encrypted-media'; + return "autoplay; fullscreen; picture-in-picture; encrypted-media"; }, }; diff --git a/react_frontend/src/lib/streaming/providers/index.ts b/react_frontend/src/lib/streaming/providers/index.ts index 694d9f4..c192983 100644 --- a/react_frontend/src/lib/streaming/providers/index.ts +++ b/react_frontend/src/lib/streaming/providers/index.ts @@ -1,3 +1,3 @@ -export { vidlinkProvider } from './vidlink'; -export { vidkingProvider } from './vidking'; -export { anyembedProvider } from './anyembed'; +export { vidlinkProvider } from "./vidlink"; +export { vidkingProvider } from "./vidking"; +export { anyembedProvider } from "./anyembed"; diff --git a/react_frontend/src/lib/streaming/providers/vidking.ts b/react_frontend/src/lib/streaming/providers/vidking.ts index c82188e..2c05b80 100644 --- a/react_frontend/src/lib/streaming/providers/vidking.ts +++ b/react_frontend/src/lib/streaming/providers/vidking.ts @@ -1,32 +1,36 @@ -import type { StreamingProvider, StreamingServer, StreamRequest } from '../types'; +import type { + StreamingProvider, + StreamingServer, + StreamRequest, +} from "../types"; const VIDKING_SERVERS: StreamingServer[] = [ { - id: 'vidking-default', - name: 'VidKing', - provider: 'vidking', + id: "vidking-default", + name: "VidKing", + provider: "vidking", supportsEvents: true, supportsProgress: true, }, ]; export const vidkingProvider: StreamingProvider = { - id: 'vidking', - name: 'VidKing', + id: "vidking", + name: "VidKing", servers: VIDKING_SERVERS, getStreamUrl(request: StreamRequest, _server: StreamingServer): string { const params = new URLSearchParams(); - params.set('autoPlay', 'true'); - params.set('nextEpisode', 'true'); - params.set('episodeSelector', 'true'); + params.set("autoPlay", "true"); + params.set("nextEpisode", "true"); + params.set("episodeSelector", "true"); if (request.startAt && request.startAt > 0) { - params.set('progress', String(Math.floor(request.startAt))); + params.set("progress", String(Math.floor(request.startAt))); } let basePath: string; - if (request.type === 'movie') { + if (request.type === "movie") { basePath = `/embed/movie/${request.tmdbId}`; } else { basePath = `/embed/tv/${request.tmdbId}/${request.season}/${request.episode}`; @@ -36,10 +40,10 @@ export const vidkingProvider: StreamingProvider = { }, getSandboxPolicy(): string { - return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation'; + return "allow-scripts allow-same-origin allow-forms allow-popups allow-presentation"; }, getAllowedFeatures(): string { - return 'autoplay; fullscreen; picture-in-picture; encrypted-media'; + return "autoplay; fullscreen; picture-in-picture; encrypted-media"; }, }; diff --git a/react_frontend/src/lib/streaming/providers/vidlink.ts b/react_frontend/src/lib/streaming/providers/vidlink.ts index 2a5ab82..68e2910 100644 --- a/react_frontend/src/lib/streaming/providers/vidlink.ts +++ b/react_frontend/src/lib/streaming/providers/vidlink.ts @@ -1,17 +1,21 @@ -import type { StreamingProvider, StreamingServer, StreamRequest } from '../types'; +import type { + StreamingProvider, + StreamingServer, + StreamRequest, +} from "../types"; const VIDLINK_SERVERS: StreamingServer[] = [ { - id: 'vidlink-default', - name: 'VidLink (Default)', - provider: 'vidlink', + id: "vidlink-default", + name: "VidLink (Default)", + provider: "vidlink", supportsEvents: true, supportsProgress: true, }, { - id: 'vidlink-jw', - name: 'VidLink (JW Player)', - provider: 'vidlink', + id: "vidlink-jw", + name: "VidLink (JW Player)", + provider: "vidlink", serverIndex: 2, supportsEvents: true, supportsProgress: true, @@ -19,27 +23,27 @@ const VIDLINK_SERVERS: StreamingServer[] = [ ]; export const vidlinkProvider: StreamingProvider = { - id: 'vidlink', - name: 'VidLink', + id: "vidlink", + name: "VidLink", servers: VIDLINK_SERVERS, getStreamUrl(request: StreamRequest, server: StreamingServer): string { const params = new URLSearchParams(); - params.set('autoplay', 'true'); - params.set('title', 'false'); - params.set('poster', 'true'); - params.set('nextbutton', 'true'); + params.set("autoplay", "true"); + params.set("title", "false"); + params.set("poster", "true"); + params.set("nextbutton", "true"); if (server.serverIndex === 2) { - params.set('player', 'jw'); + params.set("player", "jw"); } if (request.startAt && request.startAt > 0) { - params.set('startAt', String(Math.floor(request.startAt))); + params.set("startAt", String(Math.floor(request.startAt))); } let basePath: string; - if (request.type === 'movie') { + if (request.type === "movie") { basePath = `/movie/${request.tmdbId}`; } else { basePath = `/tv/${request.tmdbId}/${request.season}/${request.episode}`; @@ -49,10 +53,10 @@ export const vidlinkProvider: StreamingProvider = { }, getSandboxPolicy(): string { - return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation'; + return "allow-scripts allow-same-origin allow-forms allow-popups allow-presentation"; }, getAllowedFeatures(): string { - return 'autoplay; fullscreen; picture-in-picture; encrypted-media'; + return "autoplay; fullscreen; picture-in-picture; encrypted-media"; }, }; diff --git a/react_frontend/src/lib/streaming/streaming-manager.ts b/react_frontend/src/lib/streaming/streaming-manager.ts index 5884d5f..768eed8 100644 --- a/react_frontend/src/lib/streaming/streaming-manager.ts +++ b/react_frontend/src/lib/streaming/streaming-manager.ts @@ -7,15 +7,19 @@ import type { WatchProgressData, AutoMarkWatchedConfig, PlayerEvent, -} from './types'; -import { vidlinkProvider, vidkingProvider, anyembedProvider } from './providers'; +} from "./types"; +import { + vidlinkProvider, + vidkingProvider, + anyembedProvider, +} from "./providers"; const STORAGE_KEYS = { - PREFERRED_SERVER: 'showy_preferred_server', - WATCH_PROGRESS: 'showy_watch_progress', - AUTO_MARK_WATCHED: 'showy_auto_mark_watched', - AUTO_MARK_PROMPT_SHOWN: 'showy_auto_mark_prompt_shown', - WATCH_LOGS: 'showy_watch_logs', + PREFERRED_SERVER: "showy_preferred_server", + WATCH_PROGRESS: "showy_watch_progress", + AUTO_MARK_WATCHED: "showy_auto_mark_watched", + AUTO_MARK_PROMPT_SHOWN: "showy_auto_mark_prompt_shown", + WATCH_LOGS: "showy_watch_logs", } as const; /** All registered streaming providers */ @@ -31,7 +35,9 @@ export function getAllServers(): StreamingServer[] { } /** Get a provider by server ID */ -export function getProviderForServer(serverId: string): StreamingProvider | undefined { +export function getProviderForServer( + serverId: string, +): StreamingProvider | undefined { return providers.find((p) => p.servers.some((s) => s.id === serverId)); } @@ -41,13 +47,16 @@ export function getServerById(serverId: string): StreamingServer | undefined { } /** Build a stream URL for the given request and server */ -export function getStreamUrl(request: StreamRequest, server: StreamingServer): StreamResponse | StreamError { +export function getStreamUrl( + request: StreamRequest, + server: StreamingServer, +): StreamResponse | StreamError { const provider = getProviderForServer(server.id); if (!provider) { return { server, - message: 'Provider not found for this server', - code: 'UNAVAILABLE', + message: "Provider not found for this server", + code: "UNAVAILABLE", }; } @@ -55,16 +64,16 @@ export function getStreamUrl(request: StreamRequest, server: StreamingServer): S if (!request.tmdbId && !request.imdbId) { return { server, - message: 'A valid TMDB or IMDB ID is required', - code: 'INVALID_ID', + message: "A valid TMDB or IMDB ID is required", + code: "INVALID_ID", }; } - if (request.type === 'tv' && (!request.season || !request.episode)) { + if (request.type === "tv" && (!request.season || !request.episode)) { return { server, - message: 'Season and episode numbers are required for TV shows', - code: 'MISSING_EPISODE', + message: "Season and episode numbers are required for TV shows", + code: "MISSING_EPISODE", }; } @@ -74,27 +83,29 @@ export function getStreamUrl(request: StreamRequest, server: StreamingServer): S } catch { return { server, - message: 'Failed to build stream URL', - code: 'UNKNOWN', + message: "Failed to build stream URL", + code: "UNKNOWN", }; } } /** Check if a response is an error */ -export function isStreamError(result: StreamResponse | StreamError): result is StreamError { - return 'code' in result; +export function isStreamError( + result: StreamResponse | StreamError, +): result is StreamError { + return "code" in result; } /** Get iframe sandbox policy for a server */ export function getServerSandboxPolicy(serverId: string): string { const provider = getProviderForServer(serverId); - return provider?.getSandboxPolicy() ?? 'allow-scripts allow-same-origin'; + return provider?.getSandboxPolicy() ?? "allow-scripts allow-same-origin"; } /** Get iframe allowed features for a server */ export function getServerAllowedFeatures(serverId: string): string { const provider = getProviderForServer(serverId); - return provider?.getAllowedFeatures() ?? 'autoplay; fullscreen'; + return provider?.getAllowedFeatures() ?? "autoplay; fullscreen"; } // --- Persistence --- @@ -140,7 +151,9 @@ export function getWatchProgress(): Record { } /** Get watch progress for a specific entry */ -export function getEntryWatchProgress(tmdbId: number): WatchProgressData | null { +export function getEntryWatchProgress( + tmdbId: number, +): WatchProgressData | null { const progress = getWatchProgress(); return progress[String(tmdbId)] || null; } @@ -165,7 +178,7 @@ function getEpisodeKey(season: number, episode: number): string { export function updateProgressFromEvent( event: PlayerEvent, title: string, - posterPath?: string + posterPath?: string, ): void { const existing = getEntryWatchProgress(event.tmdbId); @@ -180,7 +193,7 @@ export function updateProgressFromEvent( ...(existing?.showProgress ? { showProgress: existing.showProgress } : {}), }; - if (event.mediaType === 'tv' && event.season && event.episode) { + if (event.mediaType === "tv" && event.season && event.episode) { data.lastSeasonWatched = event.season; data.lastEpisodeWatched = event.episode; const key = getEpisodeKey(event.season, event.episode); @@ -213,7 +226,10 @@ export function getAutoMarkWatchedConfig(): AutoMarkWatchedConfig { /** Save auto-mark-watched config */ export function setAutoMarkWatchedConfig(config: AutoMarkWatchedConfig): void { try { - localStorage.setItem(STORAGE_KEYS.AUTO_MARK_WATCHED, JSON.stringify(config)); + localStorage.setItem( + STORAGE_KEYS.AUTO_MARK_WATCHED, + JSON.stringify(config), + ); } catch { // Storage not available } @@ -222,7 +238,7 @@ export function setAutoMarkWatchedConfig(config: AutoMarkWatchedConfig): void { /** Check if the auto-mark prompt has been shown */ export function hasAutoMarkPromptBeenShown(): boolean { try { - return localStorage.getItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN) === 'true'; + return localStorage.getItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN) === "true"; } catch { return false; } @@ -231,7 +247,7 @@ export function hasAutoMarkPromptBeenShown(): boolean { /** Mark that the auto-mark prompt has been shown */ export function markAutoMarkPromptShown(): void { try { - localStorage.setItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN, 'true'); + localStorage.setItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN, "true"); } catch { // Storage not available } @@ -241,7 +257,7 @@ export function markAutoMarkPromptShown(): void { interface WatchLog { tmdbId: number; - type: 'movie' | 'tv'; + type: "movie" | "tv"; title: string; season?: number; episode?: number; @@ -274,7 +290,11 @@ export function getWatchLogs(): WatchLog[] { } /** Check if an episode/movie is considered "watched" based on progress */ -export function isConsideredWatched(watched: number, duration: number, threshold = 90): boolean { +export function isConsideredWatched( + watched: number, + duration: number, + threshold = 90, +): boolean { if (duration <= 0) return false; const percent = (watched / duration) * 100; return percent >= threshold; @@ -283,9 +303,9 @@ export function isConsideredWatched(watched: number, duration: number, threshold // --- URL Validation --- const ALLOWED_ORIGINS = [ - 'https://vidlink.pro', - 'https://www.vidking.net', - 'https://anyembed.xyz', + "https://vidlink.pro", + "https://www.vidking.net", + "https://anyembed.xyz", ]; /** Validate that an embed URL is from an allowed origin */ diff --git a/react_frontend/src/lib/streaming/types.ts b/react_frontend/src/lib/streaming/types.ts index b40d85b..8f649d4 100644 --- a/react_frontend/src/lib/streaming/types.ts +++ b/react_frontend/src/lib/streaming/types.ts @@ -1,6 +1,6 @@ // Streaming system types -export type MediaType = 'movie' | 'tv'; +export type MediaType = "movie" | "tv"; export interface StreamingServer { id: string; @@ -34,11 +34,17 @@ export interface StreamResponse { export interface StreamError { server: StreamingServer; message: string; - code: 'INVALID_ID' | 'MISSING_EPISODE' | 'TIMEOUT' | 'NETWORK' | 'UNAVAILABLE' | 'UNKNOWN'; + code: + | "INVALID_ID" + | "MISSING_EPISODE" + | "TIMEOUT" + | "NETWORK" + | "UNAVAILABLE" + | "UNKNOWN"; } export interface PlayerEvent { - event: 'play' | 'pause' | 'seeked' | 'ended' | 'timeupdate'; + event: "play" | "pause" | "seeked" | "ended" | "timeupdate"; currentTime: number; duration: number; mediaType: MediaType; @@ -61,12 +67,15 @@ export interface WatchProgressData { lastSeasonWatched?: number; lastEpisodeWatched?: number; /** Per-episode progress for TV shows */ - showProgress?: Record; + showProgress?: Record< + string, + { + season: number; + episode: number; + watched: number; + duration: number; + } + >; lastUpdated: number; } diff --git a/react_frontend/src/lib/utils.ts b/react_frontend/src/lib/utils.ts index bd0c391..a5ef193 100644 --- a/react_frontend/src/lib/utils.ts +++ b/react_frontend/src/lib/utils.ts @@ -1,6 +1,6 @@ -import { clsx, type ClassValue } from "clsx" -import { twMerge } from "tailwind-merge" +import { clsx, type ClassValue } from "clsx"; +import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)) + return twMerge(clsx(inputs)); } diff --git a/react_frontend/src/main.tsx b/react_frontend/src/main.tsx index 831cb4e..861daaf 100644 --- a/react_frontend/src/main.tsx +++ b/react_frontend/src/main.tsx @@ -1,10 +1,10 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import './index.css' -import { App } from './App' +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import "./index.css"; +import { App } from "./App"; -createRoot(document.getElementById('root')!).render( +createRoot(document.getElementById("root")!).render( , -) +); diff --git a/react_frontend/src/pages/CalendarPage.tsx b/react_frontend/src/pages/CalendarPage.tsx index 4af6a59..fff4f36 100644 --- a/react_frontend/src/pages/CalendarPage.tsx +++ b/react_frontend/src/pages/CalendarPage.tsx @@ -1,31 +1,56 @@ -import { useState, useMemo } from 'react'; -import { Link } from 'react-router-dom'; -import { format, startOfMonth, endOfMonth, eachDayOfInterval, getDay, addMonths, subMonths, isSameDay } from 'date-fns'; -import { ChevronLeft, ChevronRight, LayoutGrid, List } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; -import { useEpisodesByMonth } from '@/hooks/useEpisodes'; -import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip'; -import { getTmdbPosterUrl } from '@/lib/media-utils'; -import type { Episode } from '@/types'; +import { useState, useMemo } from "react"; +import { Link } from "react-router-dom"; +import { + format, + startOfMonth, + endOfMonth, + eachDayOfInterval, + getDay, + addMonths, + subMonths, + isSameDay, +} from "date-fns"; +import { ChevronLeft, ChevronRight, LayoutGrid, List } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { useEpisodesByMonth } from "@/hooks/useEpisodes"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, + TooltipProvider, +} from "@/components/ui/tooltip"; +import { getTmdbPosterUrl } from "@/lib/media-utils"; +import type { Episode } from "@/types"; -const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; +const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; export function CalendarPage() { const [currentDate, setCurrentDate] = useState(new Date()); - const [viewMode, setViewMode] = useState<'grid' | 'list'>( - () => (typeof window !== 'undefined' && window.innerWidth < 640 ? 'list' : 'grid') + const [viewMode, setViewMode] = useState<"grid" | "list">(() => + typeof window !== "undefined" && window.innerWidth < 640 ? "list" : "grid", ); - const [selectedDay, setSelectedDay] = useState<{ date: Date; episodes: Episode[] } | null>(null); + const [selectedDay, setSelectedDay] = useState<{ + date: Date; + episodes: Episode[]; + } | null>(null); const monthStart = startOfMonth(currentDate); const monthEnd = endOfMonth(currentDate); - const startDateStr = format(monthStart, 'yyyy-MM-dd'); - const endDateStr = format(monthEnd, 'yyyy-MM-dd'); + const startDateStr = format(monthStart, "yyyy-MM-dd"); + const endDateStr = format(monthEnd, "yyyy-MM-dd"); const { data: episodes = [] } = useEpisodesByMonth(startDateStr, endDateStr); - const days = useMemo(() => eachDayOfInterval({ start: monthStart, end: monthEnd }), [monthStart, monthEnd]); + const days = useMemo( + () => eachDayOfInterval({ start: monthStart, end: monthEnd }), + [monthStart, monthEnd], + ); const startDayOfWeek = getDay(monthStart); // Group episodes by date @@ -33,7 +58,7 @@ export function CalendarPage() { const map = new Map(); episodes.forEach((ep) => { if (!ep.air_date) return; - const key = format(new Date(ep.air_date), 'yyyy-MM-dd'); + const key = format(new Date(ep.air_date), "yyyy-MM-dd"); const existing = map.get(key) || []; existing.push(ep); map.set(key, existing); @@ -54,7 +79,7 @@ export function CalendarPage() { - {format(currentDate, 'MMMM yyyy')} + {format(currentDate, "MMMM yyyy")}
@@ -84,12 +117,15 @@ export function CalendarPage() { onClose={() => setSelectedDay(null)} /> )} - {viewMode === 'grid' ? ( + {viewMode === "grid" ? (
{/* Day headers */}
{DAYS.map((day) => ( -
+
{day}
))} @@ -99,34 +135,44 @@ export function CalendarPage() {
{/* Empty cells for offset */} {Array.from({ length: startDayOfWeek }).map((_, i) => ( -
+
))} {days.map((day) => { - const key = format(day, 'yyyy-MM-dd'); + const key = format(day, "yyyy-MM-dd"); const dayEpisodes = episodesByDate.get(key) || []; const isToday = isSameDay(day, new Date()); return (
dayEpisodes.length > 0 && setSelectedDay({ date: day, episodes: dayEpisodes })} + onClick={() => + dayEpisodes.length > 0 && + setSelectedDay({ date: day, episodes: dayEpisodes }) + } className={`border-t border-r border-border p-1 overflow-hidden flex flex-col min-h-0 ${ - isToday ? 'bg-primary/5' : '' - } ${dayEpisodes.length > 0 ? 'cursor-pointer hover:bg-accent/30 transition-colors' : ''}`} + isToday ? "bg-primary/5" : "" + } ${dayEpisodes.length > 0 ? "cursor-pointer hover:bg-accent/30 transition-colors" : ""}`} > - {format(day, 'd')} + {format(day, "d")}
{dayEpisodes.slice(0, 3).map((ep) => ( - + ))} {dayEpisodes.length > 3 && ( @@ -143,7 +189,7 @@ export function CalendarPage() { /* List / Agenda view */
{days.map((day) => { - const key = format(day, 'yyyy-MM-dd'); + const key = format(day, "yyyy-MM-dd"); const dayEpisodes = episodesByDate.get(key) || []; const isToday = isSameDay(day, new Date()); @@ -152,34 +198,39 @@ export function CalendarPage() { key={key} className={`rounded-lg border ${ isToday - ? 'border-primary/30 bg-primary/5' + ? "border-primary/30 bg-primary/5" : dayEpisodes.length > 0 - ? 'border-border' - : 'border-transparent' + ? "border-border" + : "border-transparent" }`} >
0 ? 'border-b border-border/40' : '' + dayEpisodes.length > 0 ? "border-b border-border/40" : "" }`} > - {format(day, 'd')} + {format(day, "d")} - - {format(day, 'EEEE, MMM d')} + + {format(day, "EEEE, MMM d")} {dayEpisodes.length > 0 && ( - {dayEpisodes.length} ep{dayEpisodes.length !== 1 ? 's' : ''} + {dayEpisodes.length} ep + {dayEpisodes.length !== 1 ? "s" : ""} )}
@@ -200,14 +251,20 @@ export function CalendarPage() { ); } -function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; variant?: 'grid' | 'list' | 'dialog' }) { +function EpisodeCalendarItem({ + episode, + variant = "list", +}: { + episode: Episode; + variant?: "grid" | "list" | "dialog"; +}) { type EpisodeWithEntry = Episode & { entry?: { id: number; title?: string; poster_path?: string | null }; }; const ep = episode as EpisodeWithEntry; const entry = ep.entry; const entryId = entry?.id; - const entryTitle = entry?.title ?? ''; + const entryTitle = entry?.title ?? ""; // Hide episodes with no known entry title if (!entryTitle) return null; @@ -215,18 +272,17 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; const seasonId = episode.season_id; const seasonNumber = episode.season?.season_number ?? null; - const seasonLabel = seasonNumber != null - ? `S${String(seasonNumber).padStart(2, '0')}` - : ''; - const episodeLabel = `E${String(episode.episode_number).padStart(2, '0')}`; + const seasonLabel = + seasonNumber != null ? `S${String(seasonNumber).padStart(2, "0")}` : ""; + const episodeLabel = `E${String(episode.episode_number).padStart(2, "0")}`; const thumbSrc = entry?.poster_path - ? getTmdbPosterUrl(entry.poster_path, 'w92') + ? getTmdbPosterUrl(entry.poster_path, "w92") : undefined; const isMovie = entry && !(entry as any).is_tvseries; - if (variant === 'grid') { + if (variant === "grid") { const gridContent = (
{thumbSrc ? ( @@ -237,7 +293,9 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; /> ) : (
- {entryTitle} + + {entryTitle} +
)}

@@ -250,7 +308,10 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; {entryId ? ( - + {gridContent} ) : ( @@ -274,7 +335,7 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; ); } - if (variant === 'dialog') { + if (variant === "dialog") { const dialogContent = (

{thumbSrc ? ( @@ -285,25 +346,35 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; /> ) : (
- {entryTitle} + + {entryTitle} +
)}
-

{entryTitle}

+

+ {entryTitle} +

{!isMovie && (

- {seasonLabel}{episodeLabel} + {seasonLabel} + {episodeLabel}

)} {episode.name && ( -

{episode.name}

+

+ {episode.name} +

)}
); return entryId ? ( - + {dialogContent} ) : ( @@ -362,12 +433,20 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; ); } -function DayDialog({ date, episodes, onClose }: { date: Date; episodes: Episode[]; onClose: () => void }) { +function DayDialog({ + date, + episodes, + onClose, +}: { + date: Date; + episodes: Episode[]; + onClose: () => void; +}) { return ( !open && onClose()}> - {format(date, 'EEEE, MMMM d')} + {format(date, "EEEE, MMMM d")}
{episodes.map((ep) => ( diff --git a/react_frontend/src/pages/CollectionsPage.tsx b/react_frontend/src/pages/CollectionsPage.tsx index 181e450..ae44e3d 100644 --- a/react_frontend/src/pages/CollectionsPage.tsx +++ b/react_frontend/src/pages/CollectionsPage.tsx @@ -1,26 +1,26 @@ -import { useState, useMemo, useCallback, useEffect } from 'react'; -import { useCollections } from '@/hooks/useCollections'; -import { useDebounce } from '@/hooks/useDebounce'; -import { CollectionsGrid } from '@/components/collections/CollectionsGrid'; -import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Input } from '@/components/ui/input'; -import { Search } from 'lucide-react'; +import { useState, useMemo, useCallback, useEffect } from "react"; +import { useCollections } from "@/hooks/useCollections"; +import { useDebounce } from "@/hooks/useDebounce"; +import { CollectionsGrid } from "@/components/collections/CollectionsGrid"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Input } from "@/components/ui/input"; +import { Search } from "lucide-react"; const PAGE_SIZE = 24; export function CollectionsPage() { const { data: collections = [], isLoading } = useCollections(); - const [search, setSearch] = useState(''); + const [search, setSearch] = useState(""); const debouncedSearch = useDebounce(search, 300); - const [filter, setFilter] = useState<'all' | 'official' | 'custom'>('all'); + const [filter, setFilter] = useState<"all" | "official" | "custom">("all"); const [visibleCount, setVisibleCount] = useState(PAGE_SIZE); const filtered = useMemo(() => { let result = collections; - if (filter === 'official') { + if (filter === "official") { result = result.filter((c) => !c.is_user_collection); - } else if (filter === 'custom') { + } else if (filter === "custom") { result = result.filter((c) => c.is_user_collection); } @@ -38,7 +38,7 @@ export function CollectionsPage() { const paginatedCollections = useMemo( () => filtered.slice(0, visibleCount), - [filtered, visibleCount] + [filtered, visibleCount], ); const hasMore = visibleCount < filtered.length; const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []); @@ -60,7 +60,7 @@ export function CollectionsPage() { setFilter(v as 'all' | 'official' | 'custom')} + onValueChange={(v) => setFilter(v as "all" | "official" | "custom")} > All @@ -70,7 +70,12 @@ export function CollectionsPage() {
- +
); } diff --git a/react_frontend/src/pages/DashboardPage.tsx b/react_frontend/src/pages/DashboardPage.tsx index e32153b..194c0c2 100644 --- a/react_frontend/src/pages/DashboardPage.tsx +++ b/react_frontend/src/pages/DashboardPage.tsx @@ -1,19 +1,19 @@ -import { useMemo, useState } from 'react'; -import { Link } from 'react-router-dom'; -import { useLibrary } from '@/hooks/useEntries'; -import { useStatistics } from '@/hooks/useStatistics'; -import { useLibraryEntries } from '@/stores/useLibraryStore'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { Skeleton } from '@/components/ui/skeleton'; -import { Film, Tv, Heart, ListVideo, Clock } from 'lucide-react'; -import { formatRuntime, getPosterUrl } from '@/lib/media-utils'; -import { WatchActivityChart } from '@/components/dashboard/WatchActivityChart'; -import { WatchTimeChart } from '@/components/dashboard/WatchTimeChart'; -import { RatingsChart } from '@/components/dashboard/RatingsChart'; -import { TopGenresChart } from '@/components/dashboard/TopGenresChart'; -import { CouchDayChart } from '@/components/dashboard/CouchDayChart'; -import { LibraryGrowthChart } from '@/components/dashboard/LibraryGrowthChart'; -import { MediaTypeChart } from '@/components/dashboard/MediaTypeChart'; +import { useMemo, useState } from "react"; +import { Link } from "react-router-dom"; +import { useLibrary } from "@/hooks/useEntries"; +import { useStatistics } from "@/hooks/useStatistics"; +import { useLibraryEntries } from "@/stores/useLibraryStore"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Film, Tv, Heart, ListVideo, Clock } from "lucide-react"; +import { formatRuntime, getPosterUrl } from "@/lib/media-utils"; +import { WatchActivityChart } from "@/components/dashboard/WatchActivityChart"; +import { WatchTimeChart } from "@/components/dashboard/WatchTimeChart"; +import { RatingsChart } from "@/components/dashboard/RatingsChart"; +import { TopGenresChart } from "@/components/dashboard/TopGenresChart"; +import { CouchDayChart } from "@/components/dashboard/CouchDayChart"; +import { LibraryGrowthChart } from "@/components/dashboard/LibraryGrowthChart"; +import { MediaTypeChart } from "@/components/dashboard/MediaTypeChart"; export function DashboardPage() { useLibrary(); @@ -21,43 +21,58 @@ export function DashboardPage() { const allEntries = useLibraryEntries(); const [watchYear, setWatchYear] = useState(new Date().getFullYear()); - const movies = useMemo(() => allEntries.filter((e) => !e.is_tvseries && !e.watchlist), [allEntries]); - const tvSeries = useMemo(() => allEntries.filter((e) => e.is_tvseries && !e.watchlist), [allEntries]); - const favorites = useMemo(() => allEntries.filter((e) => e.favorit && !e.watchlist), [allEntries]); - const watchlist = useMemo(() => allEntries.filter((e) => e.watchlist), [allEntries]); + const movies = useMemo( + () => allEntries.filter((e) => !e.is_tvseries && !e.watchlist), + [allEntries], + ); + const tvSeries = useMemo( + () => allEntries.filter((e) => e.is_tvseries && !e.watchlist), + [allEntries], + ); + const favorites = useMemo( + () => allEntries.filter((e) => e.favorit && !e.watchlist), + [allEntries], + ); + const watchlist = useMemo( + () => allEntries.filter((e) => e.watchlist), + [allEntries], + ); const statCards = [ { - title: 'Movies', + title: "Movies", value: movies.length, icon: Film, - color: 'text-blue-500', + color: "text-blue-500", }, { - title: 'TV Series', + title: "TV Series", value: tvSeries.length, icon: Tv, - color: 'text-green-500', + color: "text-green-500", }, { - title: 'Favorites', + title: "Favorites", value: favorites.length, icon: Heart, - color: 'text-red-500', + color: "text-red-500", }, { - title: 'Watchlist', + title: "Watchlist", value: watchlist.length, icon: ListVideo, - color: 'text-purple-500', + color: "text-purple-500", }, { - title: 'Watch Time', + title: "Watch Time", value: stats - ? formatRuntime((parseInt(stats.series || '0') || 0) + (parseInt(stats.movies || '0') || 0)) - : '0h', + ? formatRuntime( + (parseInt(stats.series || "0") || 0) + + (parseInt(stats.movies || "0") || 0), + ) + : "0h", icon: Clock, - color: 'text-orange-500', + color: "text-orange-500", }, ]; @@ -108,7 +123,7 @@ export function DashboardPage() { .sort( (a, b) => new Date(b.date_last_seen!).getTime() - - new Date(a.date_last_seen!).getTime() + new Date(a.date_last_seen!).getTime(), ) .slice(0, 14) .map((entry, index) => ( diff --git a/react_frontend/src/pages/DiscoverPage.tsx b/react_frontend/src/pages/DiscoverPage.tsx index f054785..2e0d421 100644 --- a/react_frontend/src/pages/DiscoverPage.tsx +++ b/react_frontend/src/pages/DiscoverPage.tsx @@ -1,41 +1,41 @@ -import { useState, useEffect, useRef, useCallback } from 'react'; -import { useParams } from 'react-router-dom'; -import { useInfiniteQuery } from '@tanstack/react-query'; -import { tmdbApi } from '@/api/tmdb'; -import { useLibrary } from '@/hooks/useEntries'; -import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { EntryCard, EntryCardSkeleton } from '@/components/entries/EntryCard'; -import { Loader2 } from 'lucide-react'; -import type { TmdbEntry, TmdbPaginatedResponse } from '@/types'; +import { useState, useEffect, useRef, useCallback } from "react"; +import { useParams } from "react-router-dom"; +import { useInfiniteQuery } from "@tanstack/react-query"; +import { tmdbApi } from "@/api/tmdb"; +import { useLibrary } from "@/hooks/useEntries"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { EntryCard, EntryCardSkeleton } from "@/components/entries/EntryCard"; +import { Loader2 } from "lucide-react"; +import type { TmdbEntry, TmdbPaginatedResponse } from "@/types"; const CATEGORY_LABELS: Record = { - trending: 'Trending', - popular: 'Popular', - 'top-rated': 'Top Rated', - upcoming: 'Upcoming', + trending: "Trending", + popular: "Popular", + "top-rated": "Top Rated", + upcoming: "Upcoming", }; -type MediaTab = 'movie' | 'tv'; +type MediaTab = "movie" | "tv"; function useCategoryQuery(category: string, mediaType: MediaTab) { return useInfiniteQuery>({ - queryKey: ['tmdb', category, mediaType], + queryKey: ["tmdb", category, mediaType], queryFn: ({ pageParam }) => { const page = pageParam as number; switch (category) { - case 'trending': - return mediaType === 'movie' + case "trending": + return mediaType === "movie" ? tmdbApi.getTrendingMovies(page) : tmdbApi.getTrendingTv(page); - case 'popular': - return mediaType === 'movie' + case "popular": + return mediaType === "movie" ? tmdbApi.getPopularMovies(page) : tmdbApi.getPopularTv(page); - case 'top-rated': - return mediaType === 'movie' + case "top-rated": + return mediaType === "movie" ? tmdbApi.getTopRatedMovies(page) : tmdbApi.getTopRatedTv(page); - case 'upcoming': + case "upcoming": return tmdbApi.getUpcomingMovies(page); default: return tmdbApi.getPopularMovies(page); @@ -48,20 +48,24 @@ function useCategoryQuery(category: string, mediaType: MediaTab) { } export function DiscoverPage() { - const { category = 'trending' } = useParams<{ category: string }>(); - const [mediaType, setMediaType] = useState('movie'); + const { category = "trending" } = useParams<{ category: string }>(); + const [mediaType, setMediaType] = useState("movie"); const sentinelRef = useRef(null); useLibrary(); - const isUpcoming = category === 'upcoming'; + const isUpcoming = category === "upcoming"; const query = useCategoryQuery(category, mediaType); const entries = query.data?.pages.flatMap((p) => p.results) ?? []; // Infinite scroll via IntersectionObserver const handleIntersect = useCallback( (entries: IntersectionObserverEntry[]) => { - if (entries[0]?.isIntersecting && query.hasNextPage && !query.isFetchingNextPage) { + if ( + entries[0]?.isIntersecting && + query.hasNextPage && + !query.isFetchingNextPage + ) { query.fetchNextPage(); } }, @@ -71,12 +75,14 @@ export function DiscoverPage() { useEffect(() => { const el = sentinelRef.current; if (!el) return; - const observer = new IntersectionObserver(handleIntersect, { rootMargin: '400px' }); + const observer = new IntersectionObserver(handleIntersect, { + rootMargin: "400px", + }); observer.observe(el); return () => observer.disconnect(); }, [handleIntersect]); - const title = CATEGORY_LABELS[category] || 'Discover'; + const title = CATEGORY_LABELS[category] || "Discover"; return (
diff --git a/react_frontend/src/pages/EntryCastsPage.tsx b/react_frontend/src/pages/EntryCastsPage.tsx index 5bd1584..1ab80dc 100644 --- a/react_frontend/src/pages/EntryCastsPage.tsx +++ b/react_frontend/src/pages/EntryCastsPage.tsx @@ -1,69 +1,83 @@ -import { useState, useMemo, useEffect, useRef } from 'react'; -import { useParams, Link } from 'react-router-dom'; -import { useEntry, useEntryCredits } from '@/hooks/useEntries'; -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; -import { Skeleton } from '@/components/ui/skeleton'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; +import { useState, useMemo, useEffect, useRef } from "react"; +import { useParams, Link } from "react-router-dom"; +import { useEntry, useEntryCredits } from "@/hooks/useEntries"; +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, -} from '@/components/ui/select'; -import { getProfileUrl } from '@/lib/media-utils'; -import { ArrowUpDown } from 'lucide-react'; -import type { Credit } from '@/types'; +} from "@/components/ui/select"; +import { getProfileUrl } from "@/lib/media-utils"; +import { ArrowUpDown } from "lucide-react"; +import type { Credit } from "@/types"; -type SortField = 'order' | 'popularity' | 'name' | 'birthday' | 'gender' | 'episode_count'; -type SortDir = 'asc' | 'desc'; -type CastFilter = 'all' | 'cast' | 'crew'; +type SortField = + | "order" + | "popularity" + | "name" + | "birthday" + | "gender" + | "episode_count"; +type SortDir = "asc" | "desc"; +type CastFilter = "all" | "cast" | "crew"; const PAGE_SIZE = 24; const SORT_LABELS: Record = { - order: 'Credit Order', - popularity: 'Popularity', - name: 'Name', - birthday: 'Birthday', - gender: 'Gender', - episode_count: 'Episodes', + order: "Credit Order", + popularity: "Popularity", + name: "Name", + birthday: "Birthday", + gender: "Gender", + episode_count: "Episodes", }; const FILTER_LABELS: Record = { - all: 'All', - cast: 'Cast', - crew: 'Crew', + all: "All", + cast: "Cast", + crew: "Crew", }; -function sortCredits(credits: Credit[], field: SortField, dir: SortDir): Credit[] { +function sortCredits( + credits: Credit[], + field: SortField, + dir: SortDir, +): Credit[] { return [...credits].sort((a, b) => { let cmp = 0; switch (field) { - case 'order': + case "order": cmp = (a.order ?? 9999) - (b.order ?? 9999); break; - case 'popularity': + case "popularity": cmp = (b.people?.popularity ?? 0) - (a.people?.popularity ?? 0); break; - case 'name': - cmp = (a.people?.name ?? '').localeCompare(b.people?.name ?? ''); + case "name": + cmp = (a.people?.name ?? "").localeCompare(b.people?.name ?? ""); break; - case 'birthday': { - const da = a.people?.birthday ? new Date(a.people.birthday).getTime() : 0; - const db = b.people?.birthday ? new Date(b.people.birthday).getTime() : 0; + case "birthday": { + const da = a.people?.birthday + ? new Date(a.people.birthday).getTime() + : 0; + const db = b.people?.birthday + ? new Date(b.people.birthday).getTime() + : 0; cmp = da - db; break; } - case 'gender': + case "gender": cmp = (a.people?.gender ?? 0) - (b.people?.gender ?? 0); break; - case 'episode_count': + case "episode_count": cmp = (b.episode_count ?? 0) - (a.episode_count ?? 0); break; } - return dir === 'asc' ? cmp : -cmp; + return dir === "asc" ? cmp : -cmp; }); } @@ -71,38 +85,51 @@ export function EntryCastsPage() { const { id } = useParams<{ id: string }>(); const entryId = parseInt(id!, 10); const { data: entry, isLoading } = useEntry(entryId); - const { data: allCredits = [], isLoading: creditsLoading } = useEntryCredits(entryId); + const { data: allCredits = [], isLoading: creditsLoading } = + useEntryCredits(entryId); - const [sortField, setSortField] = useState('episode_count'); - const [sortDir, setSortDir] = useState('asc'); - const [filter, setFilter] = useState('cast'); - const [search, setSearch] = useState(''); + const [sortField, setSortField] = useState("episode_count"); + const [sortDir, setSortDir] = useState("asc"); + const [filter, setFilter] = useState("cast"); + const [search, setSearch] = useState(""); const [visibleCount, setVisibleCount] = useState(PAGE_SIZE); const filtered = useMemo(() => { if (!allCredits) return []; let result = allCredits; - if (filter === 'cast') result = result.filter((c) => c.cast_type === 'cast'); - else if (filter === 'crew') result = result.filter((c) => c.cast_type === 'crew'); + if (filter === "cast") + result = result.filter((c) => c.cast_type === "cast"); + else if (filter === "crew") + result = result.filter((c) => c.cast_type === "crew"); if (search.trim()) { const q = search.trim().toLowerCase(); result = result.filter((c) => { - const name = c.people?.name?.toLowerCase() ?? ''; - const role = (c.cast_type === 'cast' ? c.character : (c.job || c.department))?.toLowerCase() ?? ''; + const name = c.people?.name?.toLowerCase() ?? ""; + const role = + (c.cast_type === "cast" + ? c.character + : c.job || c.department + )?.toLowerCase() ?? ""; return name.includes(q) || role.includes(q); }); } return result; }, [allCredits, filter, search]); - const sorted = useMemo(() => sortCredits(filtered, sortField, sortDir), [filtered, sortField, sortDir]); + const sorted = useMemo( + () => sortCredits(filtered, sortField, sortDir), + [filtered, sortField, sortDir], + ); // Reset visible window whenever filter/sort/search changes useEffect(() => { setVisibleCount(PAGE_SIZE); }, [filter, sortField, sortDir, search]); - const visible = useMemo(() => sorted.slice(0, visibleCount), [sorted, visibleCount]); + const visible = useMemo( + () => sorted.slice(0, visibleCount), + [sorted, visibleCount], + ); const hasMore = visibleCount < sorted.length; // IntersectionObserver-based lazy load on scroll @@ -117,7 +144,7 @@ export function EntryCastsPage() { setVisibleCount((c) => Math.min(c + PAGE_SIZE, sorted.length)); } }, - { rootMargin: '400px 0px' } + { rootMargin: "400px 0px" }, ); observer.observe(node); return () => observer.disconnect(); @@ -165,12 +192,15 @@ export function EntryCastsPage() { className="w-48" /> - {sorted.length} {sorted.length === 1 ? 'credit' : 'credits'} + {sorted.length} {sorted.length === 1 ? "credit" : "credits"} {/* Right: filter + sort */}
- setFilter(v as CastFilter)} + > {FILTER_LABELS[filter]} @@ -181,7 +211,10 @@ export function EntryCastsPage() { - setSortField(v as SortField)} + > {SORT_LABELS[sortField]} @@ -199,7 +232,7 @@ export function EntryCastsPage() { variant="ghost" size="icon" className="h-9 w-9" - onClick={() => setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'))} + onClick={() => setSortDir((d) => (d === "asc" ? "desc" : "asc"))} > @@ -208,7 +241,9 @@ export function EntryCastsPage() { {/* Grid */} {sorted.length === 0 ? ( -

No credits found.

+

+ No credits found. +

) : ( <>
@@ -219,7 +254,9 @@ export function EntryCastsPage() { {hasMore && (
- {Array.from({ length: Math.min(PAGE_SIZE, sorted.length - visibleCount) }).map((_, i) => ( + {Array.from({ + length: Math.min(PAGE_SIZE, sorted.length - visibleCount), + }).map((_, i) => (
@@ -244,7 +281,7 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) { : `/people/tmdb/${credit.people?.tmdb_id ?? credit.people_id}`; const roleLabel = - credit.cast_type === 'cast' + credit.cast_type === "cast" ? credit.character : credit.job || credit.department; @@ -257,13 +294,15 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) { {credit.people?.name - ?.split(' ') + ?.split(" ") .map((n) => n[0]) - .join('')} + .join("")}
-

{credit.people?.name}

+

+ {credit.people?.name} +

{roleLabel && (

{roleLabel} @@ -271,7 +310,8 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) { )} {isTv && credit.episode_count != null && credit.episode_count > 0 && (

- {credit.episode_count} {credit.episode_count === 1 ? 'episode' : 'episodes'} + {credit.episode_count}{" "} + {credit.episode_count === 1 ? "episode" : "episodes"}

)}
diff --git a/react_frontend/src/pages/EpisodePage.tsx b/react_frontend/src/pages/EpisodePage.tsx index 2a28d57..517754a 100644 --- a/react_frontend/src/pages/EpisodePage.tsx +++ b/react_frontend/src/pages/EpisodePage.tsx @@ -1,26 +1,32 @@ -import { useState } from 'react'; -import { useParams, useNavigate, Link } from 'react-router-dom'; -import { useQuery } from '@tanstack/react-query'; -import { seasonsApi } from '@/api/seasons'; -import { useSeason } from '@/hooks/useSeasons'; -import { useEntry, useEntrySeasons } from '@/hooks/useEntries'; -import { useLibraryStore } from '@/stores/useLibraryStore'; +import { useState } from "react"; +import { useParams, useNavigate, Link } from "react-router-dom"; +import { useQuery } from "@tanstack/react-query"; +import { seasonsApi } from "@/api/seasons"; +import { useSeason } from "@/hooks/useSeasons"; +import { useEntry, useEntrySeasons } from "@/hooks/useEntries"; +import { useLibraryStore } from "@/stores/useLibraryStore"; import { useEpisodeSeenByEpisode, useDeleteEpisodeSeen, -} from '@/hooks/useEpisodeSeen'; -import { StreamingDialog } from '@/components/streaming/StreamingDialog'; -import { useStreamingStore } from '@/stores/useStreamingStore'; -import { Skeleton } from '@/components/ui/skeleton'; -import { Button } from '@/components/ui/button'; -import { Separator } from '@/components/ui/separator'; -import { EpisodeWatchHistory } from '@/components/entries/EpisodeWatchHistory'; -import { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog'; -import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog'; -import { CastList } from '@/components/entries/CastList'; -import { Eye, ChevronLeft, ChevronRight, Clock, PlayCircle } from 'lucide-react'; -import { getTmdbPosterUrl, formatDate, formatRuntime } from '@/lib/media-utils'; -import type { Episode, EpisodeSeen } from '@/types'; +} from "@/hooks/useEpisodeSeen"; +import { StreamingDialog } from "@/components/streaming/StreamingDialog"; +import { useStreamingStore } from "@/stores/useStreamingStore"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Button } from "@/components/ui/button"; +import { Separator } from "@/components/ui/separator"; +import { EpisodeWatchHistory } from "@/components/entries/EpisodeWatchHistory"; +import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog"; +import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog"; +import { CastList } from "@/components/entries/CastList"; +import { + Eye, + ChevronLeft, + ChevronRight, + Clock, + PlayCircle, +} from "lucide-react"; +import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils"; +import type { Episode, EpisodeSeen } from "@/types"; export function EpisodePage() { const { entryId, seasonId, episodeId } = useParams<{ @@ -31,14 +37,16 @@ export function EpisodePage() { const navigate = useNavigate(); const { data: episodes = [] } = useQuery({ - queryKey: ['seasons', parseInt(seasonId!, 10), 'episodes'], + queryKey: ["seasons", parseInt(seasonId!, 10), "episodes"], queryFn: () => seasonsApi.getEpisodes(parseInt(seasonId!, 10)), }); const { data: season } = useSeason(parseInt(seasonId!, 10)); const { data: entry } = useEntry(parseInt(entryId!, 10)); const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10)); - const entryTitle = entry?.title ?? useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title; + const entryTitle = + entry?.title ?? + useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title; const seasonNumber = season?.season_number; const { initialize, play } = useStreamingStore(); @@ -46,7 +54,9 @@ export function EpisodePage() { const epId = parseInt(episodeId!, 10); const entryIdNum = parseInt(entryId!, 10); - const episode: Episode | undefined = episodes.find((ep: Episode) => ep.id === epId); + const episode: Episode | undefined = episodes.find( + (ep: Episode) => ep.id === epId, + ); const { data: watchHistory = [] } = useEpisodeSeenByEpisode(epId); const deleteEpisodeSeen = useDeleteEpisodeSeen(); @@ -56,7 +66,8 @@ export function EpisodePage() { // Find prev/next episode const currentIndex = episodes.findIndex((ep: Episode) => ep.id === epId); - const prevEpisode: Episode | undefined = currentIndex > 0 ? episodes[currentIndex - 1] : undefined; + const prevEpisode: Episode | undefined = + currentIndex > 0 ? episodes[currentIndex - 1] : undefined; const nextEpisode: Episode | undefined = currentIndex < episodes.length - 1 ? episodes[currentIndex + 1] : undefined; @@ -78,24 +89,27 @@ export function EpisodePage() { to={`/entry/${entryId}`} className="hover:text-foreground transition-colors truncate max-w-50" > - {entryTitle || 'Entry'} + {entryTitle || "Entry"} / - Season {seasonNumber ?? '?'} + Season {seasonNumber ?? "?"} / - Episode {episode.episode_number} + + Episode {episode.episode_number} +
{/* Top bar: nav breadcrumb + Mark Watched */}
- S{String(seasonNumber ?? 0).padStart(2, '0')} E{String(episode.episode_number).padStart(2, '0')} + S{String(seasonNumber ?? 0).padStart(2, "0")} E + {String(episode.episode_number).padStart(2, "0")}
@@ -171,7 +187,9 @@ export function EpisodePage() { { - const rec = watchHistory.find((r) => r.id === id) as EpisodeSeen | undefined; + const rec = watchHistory.find((r) => r.id === id) as + | EpisodeSeen + | undefined; if (rec) setEditRecord(rec); }} onDelete={(id) => setDeleteTarget(id)} @@ -188,7 +206,9 @@ export function EpisodePage() { size="sm" className="flex items-center gap-1 max-w-60" onClick={() => - navigate(`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`) + navigate( + `/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`, + ) } > @@ -205,7 +225,9 @@ export function EpisodePage() { size="sm" className="flex items-center gap-1 max-w-60 ml-auto" onClick={() => - navigate(`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`) + navigate( + `/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`, + ) } > @@ -234,7 +256,9 @@ export function EpisodePage() { {editRecord && ( { if (!open) setEditRecord(null); }} + onOpenChange={(open) => { + if (!open) setEditRecord(null); + }} mode="edit" record={editRecord} entryId={entryIdNum} @@ -245,14 +269,21 @@ export function EpisodePage() { {/* Delete confirm dialog */} { if (!open) setDeleteTarget(null); }} + onOpenChange={(open) => { + if (!open) setDeleteTarget(null); + }} title="Delete Watch Record" description="Are you sure you want to remove this watch record? This cannot be undone." confirmLabel="Delete" variant="destructive" onConfirm={() => { if (deleteTarget !== null) { - deleteEpisodeSeen.mutate({ id: deleteTarget, entryId: entryIdNum, episodeId: epId, seasonId: parseInt(seasonId!, 10) }); + deleteEpisodeSeen.mutate({ + id: deleteTarget, + entryId: entryIdNum, + episodeId: epId, + seasonId: parseInt(seasonId!, 10), + }); setDeleteTarget(null); } }} diff --git a/react_frontend/src/pages/MediaPage.tsx b/react_frontend/src/pages/MediaPage.tsx index 2c31a7d..28cf8c4 100644 --- a/react_frontend/src/pages/MediaPage.tsx +++ b/react_frontend/src/pages/MediaPage.tsx @@ -1,22 +1,26 @@ -import { useState, useMemo, useCallback, useEffect, useRef } from 'react'; -import { useLibrary } from '@/hooks/useEntries'; -import { useLibraryEntries } from '@/stores/useLibraryStore'; -import { useDebounce } from '@/hooks/useDebounce'; -import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Input } from '@/components/ui/input'; -import { Skeleton } from '@/components/ui/skeleton'; -import { Search } from 'lucide-react'; -import { getMediaUrl } from '@/lib/api'; -import type { Media } from '@/types'; +import { useState, useMemo, useCallback, useEffect, useRef } from "react"; +import { useLibrary } from "@/hooks/useEntries"; +import { useLibraryEntries } from "@/stores/useLibraryStore"; +import { useDebounce } from "@/hooks/useDebounce"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Input } from "@/components/ui/input"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Search } from "lucide-react"; +import { getMediaUrl } from "@/lib/api"; +import type { Media } from "@/types"; const PAGE_SIZE = 36; export function MediaPage() { const { isLoading } = useLibrary(); - const [search, setSearch] = useState(''); + const [search, setSearch] = useState(""); const debouncedSearch = useDebounce(search, 300); - const [mediaType, setMediaType] = useState<'all' | 'poster' | 'backdrop' | 'logo'>('all'); - const [customFilter, setCustomFilter] = useState<'all' | 'custom' | 'official'>('custom'); + const [mediaType, setMediaType] = useState< + "all" | "poster" | "backdrop" | "logo" + >("all"); + const [customFilter, setCustomFilter] = useState< + "all" | "custom" | "official" + >("custom"); const [visibleCount, setVisibleCount] = useState(PAGE_SIZE); const entries = useLibraryEntries(); @@ -34,7 +38,7 @@ export function MediaPage() { if (node) observerRef.current.observe(node); }, // eslint-disable-next-line react-hooks/exhaustive-deps - [isLoading] + [isLoading], ); useEffect(() => { @@ -54,13 +58,13 @@ export function MediaPage() { const filtered = useMemo(() => { let result = allMedias; - if (mediaType !== 'all') { + if (mediaType !== "all") { result = result.filter((m) => m.type === mediaType); } - if (customFilter === 'custom') { + if (customFilter === "custom") { result = result.filter((m) => m.is_custom); - } else if (customFilter === 'official') { + } else if (customFilter === "official") { result = result.filter((m) => !m.is_custom); } @@ -78,7 +82,7 @@ export function MediaPage() { const paginatedMedia = useMemo( () => filtered.slice(0, visibleCount), - [filtered, visibleCount] + [filtered, visibleCount], ); const hasMore = visibleCount < filtered.length; @@ -129,9 +133,9 @@ export function MediaPage() { ))} @@ -143,27 +147,29 @@ export function MediaPage() { ) : (
{paginatedMedia.map((media, index) => (
{media.entryTitle} diff --git a/react_frontend/src/pages/PeoplePage.tsx b/react_frontend/src/pages/PeoplePage.tsx index 995fc79..a7035c8 100644 --- a/react_frontend/src/pages/PeoplePage.tsx +++ b/react_frontend/src/pages/PeoplePage.tsx @@ -1,22 +1,22 @@ -import { useState, useCallback, useRef, useEffect, useMemo } from 'react'; -import { Link } from 'react-router-dom'; -import { usePopularPeople, useTmdbSearchPeople } from '@/hooks/useTmdb'; -import { useLocalPeopleInfinite } from '@/hooks/usePeople'; -import { Input } from '@/components/ui/input'; -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; -import { Skeleton } from '@/components/ui/skeleton'; -import { Switch } from '@/components/ui/switch'; -import { Label } from '@/components/ui/label'; -import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Search, Heart } from 'lucide-react'; -import { getProfileUrl } from '@/lib/media-utils'; +import { useState, useCallback, useRef, useEffect, useMemo } from "react"; +import { Link } from "react-router-dom"; +import { usePopularPeople, useTmdbSearchPeople } from "@/hooks/useTmdb"; +import { useLocalPeopleInfinite } from "@/hooks/usePeople"; +import { Input } from "@/components/ui/input"; +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Search, Heart } from "lucide-react"; +import { getProfileUrl } from "@/lib/media-utils"; -type PeopleFilter = 'all' | 'favorite'; +type PeopleFilter = "all" | "favorite"; export function PeoplePage() { - const [search, setSearch] = useState(''); - const [debouncedSearch, setDebouncedSearch] = useState(''); - const [filter, setFilter] = useState('all'); + const [search, setSearch] = useState(""); + const [debouncedSearch, setDebouncedSearch] = useState(""); + const [filter, setFilter] = useState("all"); const [localOnly, setLocalOnly] = useState(false); // Debounce search input @@ -28,16 +28,21 @@ export function PeoplePage() { const isSearching = debouncedSearch.length > 0; const popularQuery = usePopularPeople(); - const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? '' : debouncedSearch); + const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? "" : debouncedSearch); // Paginated local people (handles both search and browse) const localPeopleQuery = useLocalPeopleInfinite( - localOnly ? debouncedSearch : '', + localOnly ? debouncedSearch : "", localOnly, ); // For TMDB mode, use infinite scroll queries - const activeQuery = isSearching && !localOnly ? tmdbSearchQuery : !localOnly ? popularQuery : null; + const activeQuery = + isSearching && !localOnly + ? tmdbSearchQuery + : !localOnly + ? popularQuery + : null; const tmdbPeople = activeQuery?.data?.pages.flatMap((p) => p.results) ?? []; // Flatten paginated local results @@ -49,7 +54,7 @@ export function PeoplePage() { // Apply client-side favorite filter const filteredLocalPeople = useMemo(() => { if (!localOnly) return []; - if (filter === 'favorite') { + if (filter === "favorite") { return allLocalPeople.filter((p: any) => p.favorite); } return allLocalPeople; @@ -68,16 +73,31 @@ export function PeoplePage() { observerRef.current = new IntersectionObserver((entries) => { if (!entries[0].isIntersecting) return; if (localOnly) { - if (localPeopleQuery.hasNextPage && !localPeopleQuery.isFetchingNextPage) { + if ( + localPeopleQuery.hasNextPage && + !localPeopleQuery.isFetchingNextPage + ) { localPeopleQuery.fetchNextPage(); } - } else if (activeQuery && !activeQuery.isFetchingNextPage && activeQuery.hasNextPage) { + } else if ( + activeQuery && + !activeQuery.isFetchingNextPage && + activeQuery.hasNextPage + ) { activeQuery.fetchNextPage(); } }); observerRef.current.observe(node); }, - [localOnly, localPeopleQuery.hasNextPage, localPeopleQuery.isFetchingNextPage, localPeopleQuery.fetchNextPage, activeQuery?.isFetchingNextPage, activeQuery?.hasNextPage, activeQuery?.fetchNextPage] + [ + localOnly, + localPeopleQuery.hasNextPage, + localPeopleQuery.isFetchingNextPage, + localPeopleQuery.fetchNextPage, + activeQuery?.isFetchingNextPage, + activeQuery?.hasNextPage, + activeQuery?.fetchNextPage, + ], ); useEffect(() => { @@ -160,7 +180,11 @@ export function PeoplePage() { style={{ animationDelay: `${Math.min(index * 20, 300)}ms` }} >
@@ -171,9 +195,9 @@ export function PeoplePage() { /> {person.name - .split(' ') + .split(" ") .map((n: string) => n[0]) - .join('')} + .join("")} {person.favorite && ( diff --git a/react_frontend/src/pages/PersonDetailsPage.tsx b/react_frontend/src/pages/PersonDetailsPage.tsx index b07d329..11257e1 100644 --- a/react_frontend/src/pages/PersonDetailsPage.tsx +++ b/react_frontend/src/pages/PersonDetailsPage.tsx @@ -1,30 +1,37 @@ -import { useParams, useNavigate, useLocation } from 'react-router-dom'; -import { useState, useEffect } from 'react'; +import { useParams, useNavigate, useLocation } from "react-router-dom"; +import { useState, useEffect } from "react"; import { usePerson, usePersonTmdbFilmography, useUpdatePerson, useTmdbPersonPreview, useFetchPersonByTmdbId, -} from '@/hooks/usePeople'; -import { useLibrary } from '@/hooks/useEntries'; -import { useLibraryStore } from '@/stores/useLibraryStore'; -import { Skeleton } from '@/components/ui/skeleton'; -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; -import { Separator } from '@/components/ui/separator'; -import { Button } from '@/components/ui/button'; -import { EntryCard } from '@/components/entries/EntryCard'; -import { getProfileUrl, formatDate } from '@/lib/media-utils'; -import { ChevronLeft, ChevronRight, Heart, Plus, Loader2, ExternalLink } from 'lucide-react'; -import type { TmdbEntry } from '@/types'; -import type { TmdbFilmographyItem } from '@/api/people'; +} from "@/hooks/usePeople"; +import { useLibrary } from "@/hooks/useEntries"; +import { useLibraryStore } from "@/stores/useLibraryStore"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; +import { Separator } from "@/components/ui/separator"; +import { Button } from "@/components/ui/button"; +import { EntryCard } from "@/components/entries/EntryCard"; +import { getProfileUrl, formatDate } from "@/lib/media-utils"; +import { + ChevronLeft, + ChevronRight, + Heart, + Plus, + Loader2, + ExternalLink, +} from "lucide-react"; +import type { TmdbEntry } from "@/types"; +import type { TmdbFilmographyItem } from "@/api/people"; -const TMDB_IMG = 'https://image.tmdb.org/t/p'; +const TMDB_IMG = "https://image.tmdb.org/t/p"; export function PersonDetailsPage() { const { id, tmdbId } = useParams<{ id?: string; tmdbId?: string }>(); const location = useLocation(); - const isTmdbMode = location.pathname.startsWith('/people/tmdb/'); + const isTmdbMode = location.pathname.startsWith("/people/tmdb/"); if (isTmdbMode && tmdbId) { return ; @@ -38,7 +45,8 @@ export function PersonDetailsPage() { function LocalPersonView({ personId }: { personId: number }) { const navigate = useNavigate(); const { data: person, isLoading, isError } = usePerson(personId); - const { data: tmdbFilmography, isLoading: tmdbLoading } = usePersonTmdbFilmography(personId); + const { data: tmdbFilmography, isLoading: tmdbLoading } = + usePersonTmdbFilmography(personId); const updatePerson = useUpdatePerson(); useLibrary(); const libraryMap = useLibraryStore((s) => s.entries); @@ -51,7 +59,7 @@ function LocalPersonView({ personId }: { personId: number }) {

This person could not be loaded. They may not exist in the database.

-
@@ -66,9 +74,15 @@ function LocalPersonView({ personId }: { personId: number }) {
- + - {person.name.split(' ').map((n: string) => n[0]).join('')} + {person.name + .split(" ") + .map((n: string) => n[0]) + .join("")}
@@ -78,10 +92,17 @@ function LocalPersonView({ personId }: { personId: number }) { variant="ghost" size="icon" className="h-8 w-8 shrink-0" - onClick={() => updatePerson.mutate({ id: person.id, data: { favorite: !person.favorite } })} + onClick={() => + updatePerson.mutate({ + id: person.id, + data: { favorite: !person.favorite }, + }) + } disabled={updatePerson.isPending} > - +
Could not load person data from TMDB.

- +
); } @@ -167,19 +190,26 @@ function TmdbPersonView({ tmdbId }: { tmdbId: number }) { - {preview.name.split(' ').map((n: string) => n[0]).join('')} + {preview.name + .split(" ") + .map((n: string) => n[0]) + .join("")}

{preview.name}

-
{known_for_department && {known_for_department}} - {birthday && (<>•Born: {formatDate(birthday)})} - {deathday && (<>•Died: {formatDate(deathday)})} - {place_of_birth && (<>•{place_of_birth})} + {birthday && ( + <> + • + Born: {formatDate(birthday)} + + )} + {deathday && ( + <> + • + Died: {formatDate(deathday)} + + )} + {place_of_birth && ( + <> + • + {place_of_birth} + + )} {tmdb_id && ( <> • @@ -266,17 +311,26 @@ function PersonSkeleton() { /* ─── Filmography ─── */ interface FilmographySectionProps { - libraryMap: Map; + libraryMap: Map; libraryLoaded: boolean; - tmdbFilmography?: { cast: TmdbFilmographyItem[]; crew: TmdbFilmographyItem[] }; + tmdbFilmography?: { + cast: TmdbFilmographyItem[]; + crew: TmdbFilmographyItem[]; + }; tmdbLoading: boolean; } -function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLoading }: FilmographySectionProps) { +function FilmographySection({ + libraryMap, + libraryLoaded, + tmdbFilmography, + tmdbLoading, +}: FilmographySectionProps) { const [libraryPage, setLibraryPage] = useState(0); const [otherPage, setOtherPage] = useState(0); const PAGE_SIZE = 6; // 6 cols × 1 row - const GRID = 'grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'; + const GRID = + "grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"; if (tmdbLoading || !libraryLoaded) { return ( @@ -293,7 +347,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo const allTmdbCredits = [ ...(tmdbFilmography?.cast ?? []), - ...(tmdbFilmography?.crew?.filter((c) => c.job === 'Director' || c.department === 'Directing') ?? []), + ...(tmdbFilmography?.crew?.filter( + (c) => c.job === "Director" || c.department === "Directing", + ) ?? []), ]; const seenTmdbIds = new Set(); const dedupedCredits = allTmdbCredits.filter((c) => { @@ -302,7 +358,7 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo return true; }); - const tmdbIdToLibraryEntry = new Map(); + const tmdbIdToLibraryEntry = new Map(); for (const entry of libraryMap.values()) { if (entry.entryIds?.tmdb_id != null) { tmdbIdToLibraryEntry.set(Number(entry.entryIds.tmdb_id), entry); @@ -310,14 +366,23 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo } // Sort by popularity descending - const sorted = [...dedupedCredits].sort((a, b) => (b.popularity ?? 0) - (a.popularity ?? 0)); + const sorted = [...dedupedCredits].sort( + (a, b) => (b.popularity ?? 0) - (a.popularity ?? 0), + ); const libraryCredits = sorted.filter((c) => tmdbIdToLibraryEntry.has(c.id)); // "Not in library": sort by release date (new→old), push "self" roles to the end const isSelfRole = (character?: string) => { if (!character) return false; const lower = character.toLowerCase().trim(); - return lower === 'self' || lower.startsWith('self -') || lower.startsWith('self (') || lower === 'themselves' || lower === 'himself' || lower === 'herself'; + return ( + lower === "self" || + lower.startsWith("self -") || + lower.startsWith("self (") || + lower === "themselves" || + lower === "himself" || + lower === "herself" + ); }; const otherCreditsSorted = sorted .filter((c) => !tmdbIdToLibraryEntry.has(c.id)) @@ -326,8 +391,12 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo const bSelf = isSelfRole(b.character) ? 1 : 0; if (aSelf !== bSelf) return aSelf - bSelf; // Both same self status → sort by date descending (new first) - const dateA = new Date(a.release_date || a.first_air_date || '1900').getTime(); - const dateB = new Date(b.release_date || b.first_air_date || '1900').getTime(); + const dateA = new Date( + a.release_date || a.first_air_date || "1900", + ).getTime(); + const dateB = new Date( + b.release_date || b.first_air_date || "1900", + ).getTime(); return dateB - dateA; }); const otherCredits = otherCreditsSorted; @@ -341,8 +410,14 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo ); } - const librarySlice = libraryCredits.slice(libraryPage * PAGE_SIZE, (libraryPage + 1) * PAGE_SIZE); - const otherSlice = otherCredits.slice(otherPage * PAGE_SIZE, (otherPage + 1) * PAGE_SIZE); + const librarySlice = libraryCredits.slice( + libraryPage * PAGE_SIZE, + (libraryPage + 1) * PAGE_SIZE, + ); + const otherSlice = otherCredits.slice( + otherPage * PAGE_SIZE, + (otherPage + 1) * PAGE_SIZE, + ); const libraryTotalPages = Math.ceil(libraryCredits.length / PAGE_SIZE); const otherTotalPages = Math.ceil(otherCredits.length / PAGE_SIZE); @@ -359,7 +434,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo {libraryTotalPages > 1 && (
+
); } @@ -71,26 +76,50 @@ export function PersonTmdbRedirectPage() { - {preview.name.split(' ').map((n: string) => n[0]).join('')} + {preview.name + .split(" ") + .map((n: string) => n[0]) + .join("")}

{preview.name}

-
- {preview.known_for_department && {preview.known_for_department}} - {preview.birthday && (<>•Born: {formatDate(preview.birthday)})} - {preview.deathday && (<>•Died: {formatDate(preview.deathday)})} - {preview.place_of_birth && (<>•{preview.place_of_birth})} + {preview.known_for_department && ( + {preview.known_for_department} + )} + {preview.birthday && ( + <> + • + Born: {formatDate(preview.birthday)} + + )} + {preview.deathday && ( + <> + • + Died: {formatDate(preview.deathday)} + + )} + {preview.place_of_birth && ( + <> + • + {preview.place_of_birth} + + )}
{preview.biography && (

@@ -113,15 +142,20 @@ export function PersonTmdbRedirectPage() { interface TmdbFilmographySectionProps { filmography: { cast: TmdbFilmographyItem[]; crew: TmdbFilmographyItem[] }; - libraryMap: Map; + libraryMap: Map; libraryLoaded: boolean; } -function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: TmdbFilmographySectionProps) { +function TmdbFilmographySection({ + filmography, + libraryMap, + libraryLoaded, +}: TmdbFilmographySectionProps) { const [libraryPage, setLibraryPage] = useState(0); const [otherPage, setOtherPage] = useState(0); const PAGE_SIZE = 6; - const GRID = 'grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'; + const GRID = + "grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"; if (!libraryLoaded) { return ( @@ -138,7 +172,9 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb const allCredits = [ ...(filmography.cast ?? []), - ...(filmography.crew?.filter((c) => c.job === 'Director' || c.department === 'Directing') ?? []), + ...(filmography.crew?.filter( + (c) => c.job === "Director" || c.department === "Directing", + ) ?? []), ]; const seenIds = new Set(); const deduped = allCredits.filter((c) => { @@ -147,20 +183,29 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb return true; }); - const tmdbIdToLibraryEntry = new Map(); + const tmdbIdToLibraryEntry = new Map(); for (const entry of libraryMap.values()) { if (entry.entryIds?.tmdb_id != null) { tmdbIdToLibraryEntry.set(Number(entry.entryIds.tmdb_id), entry); } } - const sorted = [...deduped].sort((a, b) => (b.popularity ?? 0) - (a.popularity ?? 0)); + const sorted = [...deduped].sort( + (a, b) => (b.popularity ?? 0) - (a.popularity ?? 0), + ); const libraryCredits = sorted.filter((c) => tmdbIdToLibraryEntry.has(c.id)); const isSelfRole = (character?: string) => { if (!character) return false; const lower = character.toLowerCase().trim(); - return lower === 'self' || lower.startsWith('self -') || lower.startsWith('self (') || lower === 'themselves' || lower === 'himself' || lower === 'herself'; + return ( + lower === "self" || + lower.startsWith("self -") || + lower.startsWith("self (") || + lower === "themselves" || + lower === "himself" || + lower === "herself" + ); }; const otherCredits = sorted .filter((c) => !tmdbIdToLibraryEntry.has(c.id)) @@ -168,8 +213,12 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb const aSelf = isSelfRole(a.character) ? 1 : 0; const bSelf = isSelfRole(b.character) ? 1 : 0; if (aSelf !== bSelf) return aSelf - bSelf; - const dateA = new Date(a.release_date || a.first_air_date || '1900').getTime(); - const dateB = new Date(b.release_date || b.first_air_date || '1900').getTime(); + const dateA = new Date( + a.release_date || a.first_air_date || "1900", + ).getTime(); + const dateB = new Date( + b.release_date || b.first_air_date || "1900", + ).getTime(); return dateB - dateA; }); @@ -182,8 +231,14 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb ); } - const librarySlice = libraryCredits.slice(libraryPage * PAGE_SIZE, (libraryPage + 1) * PAGE_SIZE); - const otherSlice = otherCredits.slice(otherPage * PAGE_SIZE, (otherPage + 1) * PAGE_SIZE); + const librarySlice = libraryCredits.slice( + libraryPage * PAGE_SIZE, + (libraryPage + 1) * PAGE_SIZE, + ); + const otherSlice = otherCredits.slice( + otherPage * PAGE_SIZE, + (otherPage + 1) * PAGE_SIZE, + ); const libraryTotalPages = Math.ceil(libraryCredits.length / PAGE_SIZE); const otherTotalPages = Math.ceil(otherCredits.length / PAGE_SIZE); @@ -199,17 +254,25 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb {libraryTotalPages > 1 && (

- {libraryPage + 1}/{libraryTotalPages} -
@@ -222,7 +285,9 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
{credit.character && ( -

{credit.character}

+

+ {credit.character} +

)}
); @@ -239,17 +304,25 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb {otherTotalPages > 1 && (
- {otherPage + 1}/{otherTotalPages} -
@@ -266,7 +339,7 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb release_date: credit.release_date, first_air_date: credit.first_air_date, media_type: credit.media_type, - overview: '', + overview: "", vote_average: 0, vote_count: 0, genre_ids: [], @@ -276,7 +349,9 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
{credit.character && ( -

{credit.character}

+

+ {credit.character} +

)}
); diff --git a/react_frontend/src/pages/SearchPage.tsx b/react_frontend/src/pages/SearchPage.tsx index fff03e5..1f3c9b0 100644 --- a/react_frontend/src/pages/SearchPage.tsx +++ b/react_frontend/src/pages/SearchPage.tsx @@ -1,16 +1,16 @@ -import { useState, useEffect, useRef } from 'react'; -import { useSearchParams, Link } from 'react-router-dom'; -import { useTmdbSearch, useTmdbSearchPeople } from '@/hooks/useTmdb'; -import { useLibrary } from '@/hooks/useEntries'; -import { Input } from '@/components/ui/input'; -import { Search } from 'lucide-react'; -import { EntryCard } from '@/components/entries/EntryCard'; -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; -import { getTmdbImageUrl } from '@/lib/api'; +import { useState, useEffect, useRef } from "react"; +import { useSearchParams, Link } from "react-router-dom"; +import { useTmdbSearch, useTmdbSearchPeople } from "@/hooks/useTmdb"; +import { useLibrary } from "@/hooks/useEntries"; +import { Input } from "@/components/ui/input"; +import { Search } from "lucide-react"; +import { EntryCard } from "@/components/entries/EntryCard"; +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; +import { getTmdbImageUrl } from "@/lib/api"; export function SearchPage() { const [searchParams, setSearchParams] = useSearchParams(); - const initialQuery = searchParams.get('q') || ''; + const initialQuery = searchParams.get("q") || ""; const [searchInput, setSearchInput] = useState(initialQuery); const [debouncedQuery, setDebouncedQuery] = useState(initialQuery); const debounceRef = useRef>(); @@ -39,8 +39,10 @@ export function SearchPage() { const searchResults = useTmdbSearch(debouncedQuery); const peopleResults = useTmdbSearchPeople(debouncedQuery); - const searchEntries = searchResults.data?.pages.flatMap((p) => p.results) ?? []; - const searchPeople = peopleResults.data?.pages.flatMap((p) => p.results) ?? []; + const searchEntries = + searchResults.data?.pages.flatMap((p) => p.results) ?? []; + const searchPeople = + peopleResults.data?.pages.flatMap((p) => p.results) ?? []; const isSearching = debouncedQuery.length > 0; @@ -73,16 +75,26 @@ export function SearchPage() { > - {person.name.split(' ').map((n) => n[0]).join('').slice(0, 2)} + {person.name + .split(" ") + .map((n) => n[0]) + .join("") + .slice(0, 2)} {person.name} {person.known_for_department && ( - {person.known_for_department} + + {person.known_for_department} + )} ))} diff --git a/react_frontend/src/pages/SeasonPage.tsx b/react_frontend/src/pages/SeasonPage.tsx index 375785c..8d7aa83 100644 --- a/react_frontend/src/pages/SeasonPage.tsx +++ b/react_frontend/src/pages/SeasonPage.tsx @@ -1,19 +1,24 @@ -import { useState } from 'react'; -import { useParams, Link } from 'react-router-dom'; -import { useSeason, useSeasonEpisodes } from '@/hooks/useSeasons'; -import { useEntry, useEntrySeasons } from '@/hooks/useEntries'; -import { useLibraryStore } from '@/stores/useLibraryStore'; -import { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog'; -import { MarkSeasonWatchedDialog } from '@/components/dialogs/MarkSeasonWatchedDialog'; -import { StreamingDialog } from '@/components/streaming/StreamingDialog'; -import { useStreamingStore } from '@/stores/useStreamingStore'; -import { Skeleton } from '@/components/ui/skeleton'; -import { Progress } from '@/components/ui/progress'; -import { Button } from '@/components/ui/button'; -import { Eye, CheckCircle2, ListChecks, PlayCircle } from 'lucide-react'; -import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; -import { getTmdbPosterUrl, getYear, formatDate } from '@/lib/media-utils'; -import type { Episode, EpisodeSeen } from '@/types'; +import { useState } from "react"; +import { useParams, Link } from "react-router-dom"; +import { useSeason, useSeasonEpisodes } from "@/hooks/useSeasons"; +import { useEntry, useEntrySeasons } from "@/hooks/useEntries"; +import { useLibraryStore } from "@/stores/useLibraryStore"; +import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog"; +import { MarkSeasonWatchedDialog } from "@/components/dialogs/MarkSeasonWatchedDialog"; +import { StreamingDialog } from "@/components/streaming/StreamingDialog"; +import { useStreamingStore } from "@/stores/useStreamingStore"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Progress } from "@/components/ui/progress"; +import { Button } from "@/components/ui/button"; +import { Eye, CheckCircle2, ListChecks, PlayCircle } from "lucide-react"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { getTmdbPosterUrl, getYear, formatDate } from "@/lib/media-utils"; +import type { Episode, EpisodeSeen } from "@/types"; export function SeasonPage() { const { entryId, seasonId } = useParams<{ @@ -24,7 +29,9 @@ export function SeasonPage() { const { data: episodes = [] } = useSeasonEpisodes(parseInt(seasonId!, 10)); const { data: entry } = useEntry(parseInt(entryId!, 10)); const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10)); - const entryTitle = entry?.title ?? useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title; + const entryTitle = + entry?.title ?? + useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title; const { initialize, play } = useStreamingStore(); const [dialogEpisode, setDialogEpisode] = useState(null); const [showMarkAllDialog, setShowMarkAllDialog] = useState(false); @@ -34,7 +41,7 @@ export function SeasonPage() { if (!entry?.entryIds?.tmdb_id) return; initialize(); play({ - type: 'tv', + type: "tv", tmdbId: entry.entryIds.tmdb_id, imdbId: entry.entryIds?.imdb_id || undefined, season, @@ -60,8 +67,7 @@ export function SeasonPage() { const watchedCount = episodes.filter( (ep: Episode) => - ep.date_first_seen || - (ep.episodeSeens && ep.episodeSeens.length > 0) + ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0), ).length; const totalEpisodes = episodes.length; const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0; @@ -74,16 +80,18 @@ export function SeasonPage() { to={`/entry/${entryId}`} className="hover:text-foreground transition-colors truncate max-w-50" > - {entryTitle || 'Entry'} + {entryTitle || "Entry"} / - Season {season.season_number} + + Season {season.season_number} +
{/* Header */}
{season.name} @@ -137,7 +145,9 @@ export function SeasonPage() { const isWatched = !!episode.date_first_seen || (episode.episodeSeens && episode.episodeSeens.length > 0); - const seenDates = (episode.episodeSeens ?? []).map((s: EpisodeSeen) => s.date_seen); + const seenDates = (episode.episodeSeens ?? []).map( + (s: EpisodeSeen) => s.date_seen, + ); return ( {episode.still_path ? ( {episode.name} { ev.preventDefault(); @@ -249,7 +262,9 @@ export function SeasonPage() { {dialogEpisode && ( { if (!open) setDialogEpisode(null); }} + onOpenChange={(open) => { + if (!open) setDialogEpisode(null); + }} mode="create" episodeId={dialogEpisode.id} entryId={parseInt(entryId!, 10)} diff --git a/react_frontend/src/stores/useCommandPaletteStore.ts b/react_frontend/src/stores/useCommandPaletteStore.ts index 617e6da..0f2a334 100644 --- a/react_frontend/src/stores/useCommandPaletteStore.ts +++ b/react_frontend/src/stores/useCommandPaletteStore.ts @@ -1,9 +1,9 @@ -import { create } from 'zustand'; +import { create } from "zustand"; interface RecentItem { id: string; // unique key: "lib-{id}" or "tmdb-{tmdbId}" title: string; - type: 'movie' | 'tv'; + type: "movie" | "tv"; poster_path: string | null; libraryId?: number; tmdbId?: number; @@ -21,7 +21,9 @@ interface CommandPaletteState { export const useCommandPaletteStore = create((set) => ({ isOpen: false, - recentlyViewed: JSON.parse(localStorage.getItem('showy-recent-viewed') || '[]'), + recentlyViewed: JSON.parse( + localStorage.getItem("showy-recent-viewed") || "[]", + ), open: () => set({ isOpen: true }), close: () => set({ isOpen: false }), @@ -31,10 +33,9 @@ export const useCommandPaletteStore = create((set) => ({ set((state) => { const filtered = state.recentlyViewed.filter((r) => r.id !== item.id); const updated = [item, ...filtered].slice(0, 10); - localStorage.setItem('showy-recent-viewed', JSON.stringify(updated)); + localStorage.setItem("showy-recent-viewed", JSON.stringify(updated)); return { recentlyViewed: updated }; }), })); export type { RecentItem }; - diff --git a/react_frontend/src/stores/useLibraryFiltersStore.ts b/react_frontend/src/stores/useLibraryFiltersStore.ts index fa993b9..3af5516 100644 --- a/react_frontend/src/stores/useLibraryFiltersStore.ts +++ b/react_frontend/src/stores/useLibraryFiltersStore.ts @@ -1,8 +1,13 @@ -import { create } from 'zustand'; +import { create } from "zustand"; -type FilterTab = 'all' | 'movies' | 'tv' | 'favorites' | 'hidden'; -type SortField = 'date_last_seen' | 'createdAt' | 'title' | 'release_date' | 'rating'; -type SortDir = 'asc' | 'desc'; +type FilterTab = "all" | "movies" | "tv" | "favorites" | "hidden"; +type SortField = + | "date_last_seen" + | "createdAt" + | "title" + | "release_date" + | "rating"; +type SortDir = "asc" | "desc"; interface Filters { genre: string; @@ -31,20 +36,20 @@ interface LibraryFiltersState { } const defaultFilters: Filters = { - genre: '', - tmdbRatingMin: '', - tmdbRatingMax: '', - userRatingMin: '', - userRatingMax: '', - yearMin: '', - yearMax: '', + genre: "", + tmdbRatingMin: "", + tmdbRatingMax: "", + userRatingMin: "", + userRatingMax: "", + yearMin: "", + yearMax: "", }; export const useLibraryFiltersStore = create((set) => ({ - activeTab: 'all', - search: '', - sortField: 'date_last_seen', - sortDir: 'desc', + activeTab: "all", + search: "", + sortField: "date_last_seen", + sortDir: "desc", filters: defaultFilters, setActiveTab: (tab) => set({ activeTab: tab }), @@ -53,15 +58,15 @@ export const useLibraryFiltersStore = create((set) => ({ setSortDir: (dir) => set({ sortDir: dir }), setFilters: (updater) => set((state) => ({ - filters: typeof updater === 'function' ? updater(state.filters) : updater, + filters: typeof updater === "function" ? updater(state.filters) : updater, })), clearFilters: () => set({ filters: defaultFilters }), resetAll: () => set({ - activeTab: 'all', - search: '', - sortField: 'date_last_seen', - sortDir: 'desc', + activeTab: "all", + search: "", + sortField: "date_last_seen", + sortDir: "desc", filters: defaultFilters, }), })); diff --git a/react_frontend/src/stores/useLibraryStore.ts b/react_frontend/src/stores/useLibraryStore.ts index 5dad9bd..487d004 100644 --- a/react_frontend/src/stores/useLibraryStore.ts +++ b/react_frontend/src/stores/useLibraryStore.ts @@ -1,5 +1,5 @@ -import { create } from 'zustand'; -import type { Entry } from '@/types'; +import { create } from "zustand"; +import type { Entry } from "@/types"; interface LibraryState { entries: Map; diff --git a/react_frontend/src/stores/useStreamingStore.ts b/react_frontend/src/stores/useStreamingStore.ts index 4376005..39a3f97 100644 --- a/react_frontend/src/stores/useStreamingStore.ts +++ b/react_frontend/src/stores/useStreamingStore.ts @@ -1,5 +1,10 @@ -import { create } from 'zustand'; -import type { StreamingServer, StreamRequest, StreamError, AutoMarkWatchedConfig } from '@/lib/streaming/types'; +import { create } from "zustand"; +import type { + StreamingServer, + StreamRequest, + StreamError, + AutoMarkWatchedConfig, +} from "@/lib/streaming/types"; import { getAllServers, getPreferredServer, @@ -10,7 +15,7 @@ import { setAutoMarkWatchedConfig, hasAutoMarkPromptBeenShown, markAutoMarkPromptShown, -} from '@/lib/streaming/streaming-manager'; +} from "@/lib/streaming/streaming-manager"; interface StreamingStore { // State @@ -77,15 +82,20 @@ export const useStreamingStore = create((set, get) => ({ set({ error: { server: getAllServers()[0], - message: 'No server selected', - code: 'UNAVAILABLE', + message: "No server selected", + code: "UNAVAILABLE", }, isLoading: false, }); return; } - set({ isLoading: true, error: null, currentRequest: request, isPlayerOpen: true }); + set({ + isLoading: true, + error: null, + currentRequest: request, + isPlayerOpen: true, + }); const result = getStreamUrl(request, activeServer); if (isStreamError(result)) { @@ -164,8 +174,8 @@ export const useStreamingStore = create((set, get) => ({ set({ error: { server: activeServer, - message: 'All servers are unavailable. Please try again later.', - code: 'UNAVAILABLE', + message: "All servers are unavailable. Please try again later.", + code: "UNAVAILABLE", }, }); return; diff --git a/react_frontend/src/stores/useThemeStore.ts b/react_frontend/src/stores/useThemeStore.ts index 732c69b..d1c0d24 100644 --- a/react_frontend/src/stores/useThemeStore.ts +++ b/react_frontend/src/stores/useThemeStore.ts @@ -1,7 +1,7 @@ -import { create } from 'zustand'; -import { persist } from 'zustand/middleware'; +import { create } from "zustand"; +import { persist } from "zustand/middleware"; -type Theme = 'dark' | 'light'; +type Theme = "dark" | "light"; interface ThemeState { theme: Theme; @@ -12,26 +12,26 @@ interface ThemeState { export const useThemeStore = create()( persist( (set, get) => ({ - theme: 'dark', + theme: "dark", setTheme: (theme) => { - document.documentElement.classList.remove('dark', 'light'); + document.documentElement.classList.remove("dark", "light"); document.documentElement.classList.add(theme); set({ theme }); }, toggleTheme: () => { - const newTheme = get().theme === 'dark' ? 'light' : 'dark'; - document.documentElement.classList.remove('dark', 'light'); + const newTheme = get().theme === "dark" ? "light" : "dark"; + document.documentElement.classList.remove("dark", "light"); document.documentElement.classList.add(newTheme); set({ theme: newTheme }); }, }), { - name: 'showy-theme', + name: "showy-theme", onRehydrateStorage: () => (state) => { if (state) { document.documentElement.classList.add(state.theme); } }, - } - ) + }, + ), );