diff --git a/.gitignore b/.gitignore index c1f23f0..af97261 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,14 @@ # See http://help.github.com/ignore-files/ for more about ignoring files. +# ! me +settings.json +sequelize.log +showy.log + # Compiled output /dist /dist_exe +/dist_electron /uploads /tmp /out-tsc diff --git a/angular.json b/angular.json index deaaa2e..da8f68f 100644 --- a/angular.json +++ b/angular.json @@ -13,7 +13,7 @@ "build": { "builder": "@angular-devkit/build-angular:application", "options": { - "outputPath": "dist/show-z", + "outputPath": "dist/showy", "index": "frontend/src/index.html", "browser": "frontend/src/main.ts", "polyfills": ["zone.js"], @@ -21,13 +21,14 @@ "assets": ["frontend/src/favicon.ico", "frontend/src/assets"], "styles": [ "frontend/src/styles.css", - + "frontend/src/assets/plugins/select2/css/select2.min.css", "frontend/src/assets/plugins/select2/css/select2-bootstrap4.css", "frontend/src/assets/css/bootstrap.min.css", "frontend/src/assets/css/bootstrap-extended.css", + "frontend/src/assets/plugins/bs-stepper/css/bs-stepper.css", "frontend/src/assets/plugins/metismenu/metisMenu.min.css", "frontend/src/assets/plugins/metismenu/mm-vertical.css", "frontend/src/assets/plugins/simplebar/css/simplebar.css", @@ -37,7 +38,6 @@ "frontend/src/assets/sass/semi-dark.css", "frontend/src/assets/sass/dark-theme.css", - "frontend/src/assets/sass/bordered-theme.css", "node_modules/ngx-toastr/toastr.css", @@ -58,7 +58,7 @@ "frontend/src/assets/plugins/select2/js/select2.min.js", "frontend/src/assets/plugins/select2/js/select2-custom.js", - + "node_modules/flatpickr/dist/flatpickr.min.js", "frontend/src/assets/js/index.js", @@ -67,6 +67,12 @@ }, "configurations": { "production": { + "fileReplacements": [ + { + "replace": "frontend/src/environments/environment.ts", + "with": "frontend/src/environments/environment.prod.ts" + } + ], "budgets": [ { "type": "initial", diff --git a/backend/middleware/errorHandler.js b/backend/middleware/errorHandler.js index 9494b4e..9d4b78e 100644 --- a/backend/middleware/errorHandler.js +++ b/backend/middleware/errorHandler.js @@ -1,11 +1,14 @@ const CustomError = require('../errors/CustomError'); +const { logToFile } = require('../services/logService'); module.exports = (err, req, res, next) => { if (err instanceof CustomError) { res.status(err.statusCode()).json({ message: err.message }); + logToFile(`Error (${err.statusCode()}) ${err.message}`) } else { console.log(`📌 Error: `, err) + logToFile(`Error (500) ${err}`) res.status(500).json({ message: 'Internal server error' }); } }; \ No newline at end of file diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index a477b75..6be0be5 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -1,15 +1,18 @@ const express = require('express'); +const entryRouter = express.Router(); + const { fetchEntryData } = require('../services/tmdbService'); +const { saveEntry, refrechEntry } = require('../services/entryService'); +const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService'); + const Entry = require('../models/Entry'); const EntryId = require('../models/EntryId'); const EntryRating = require('../models/EntryRating'); const Genre = require('../models/Genre'); const EntrySeen = require('../models/EntrySeen'); -const { saveEntry, refrechEntry } = require('../services/entryService'); const Season = require('../models/Season'); -const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService'); const Media = require('../models/Media'); -const entryRouter = express.Router(); +const Episode = require('../models/Episode'); // ! /entries // * GET - ALL ENTRIES @@ -65,13 +68,15 @@ entryRouter.get('/:id', async (req, res) => { attributes: [] // Do not fetch any attributes from the join table } } + ], + order: [ + [{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list ] }); if (!entry) { // ! entry not found res.status(404).json({ message: 'Entry not found' }); } - const entryData = entry.get({ plain: true }); const genres = entryData.genres.map(genre => genre.name); @@ -83,6 +88,47 @@ entryRouter.get('/:id', async (req, res) => { console.log(error); } }); + +// * GET - Get seasons of an entry +entryRouter.get('/:id/seasons', async (req, res) => { + try { + const { id } = req.params; + + if (id == null) { // ! entry id not provided + res.status(404).json({ message: 'Entry id not provided' }); + } + + const entry = await Entry.findByPk(id); + + if (!entry) { + res.status(404).json({ message: 'Entry not found' }); + } + + const seasons = await Season.findAll({ + where: { + entry_id: id + }, + attributes: ['id', 'season_number'], + include: [ + { model: Episode, as: 'episodes', attributes: ['id', 'episode_number'], } + ], + order: [ + ['season_number', 'ASC'], + [{ model: Episode, as: 'episodes' }, 'episode_number', 'ASC'], + ] + }) + + if (seasons.length == 0) { // ! no content + res.status(404).json({ message: 'No seasons' }); + } + + res.status(200).json(seasons); + } catch (error) { + res.status(500).json({ error: error.message }); + console.log(error); + } +}); + // ! POST // * POST - CREATE ENTRY entryRouter.post('/', async (req, res) => { @@ -172,7 +218,10 @@ entryRouter.put('/:id', async (req, res) => { if (oldEntry.is_tvseries) includes.push({ model: Season, as: 'seasons' }); const updatedEntry = await Entry.findByPk(id, { - include: includes + include: includes, + order: [ + [{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list + ] }); const entryData = updatedEntry.get({ plain: true }); diff --git a/backend/routes/routes.js b/backend/routes/routes.js index 70f6fcf..14eced0 100644 --- a/backend/routes/routes.js +++ b/backend/routes/routes.js @@ -6,6 +6,7 @@ const entryRouter = require('./entry.routes'); const entryRatingsRouter = require('./entry-ratings.routes'); const seasonRouter = require('./season.routes'); const episodeSeenRouter = require('./episode-seen.routes'); +const settingsRouter = require('./settings.routes'); const router = express.Router(); @@ -18,4 +19,6 @@ router.use('/entry-ratings', entryRatingsRouter); router.use('/seasons', seasonRouter); router.use('/episode-seen', episodeSeenRouter); +router.use('/settings', settingsRouter); + module.exports = router; \ No newline at end of file diff --git a/backend/routes/season.routes.js b/backend/routes/season.routes.js index f52fd77..2a1e8fd 100644 --- a/backend/routes/season.routes.js +++ b/backend/routes/season.routes.js @@ -4,7 +4,7 @@ const Episode = require('../models/Episode'); const seasonRouter = express.Router(); // ! /seasons -// POST /seasons - Create a new season +// * POST - Create a new season seasonRouter.post('/', async (req, res) => { try { const season = await Season.create(req.body); @@ -14,7 +14,7 @@ seasonRouter.post('/', async (req, res) => { } }); -// GET /seasons - Retrieve all seasons +// * GET - Retrieve all seasons seasonRouter.get('/', async (req, res) => { try { const seasons = await Season.findAll(); @@ -24,7 +24,7 @@ seasonRouter.get('/', async (req, res) => { } }); -// GET /seasons/:id - Retrieve a specific season by id +// * GET - Retrieve a specific season by id seasonRouter.get('/:id', async (req, res) => { try { const season = await Season.findByPk(req.params.id, { @@ -44,6 +44,7 @@ seasonRouter.get('/:id', async (req, res) => { } }); +// * GET - Retrieve episodes of a season seasonRouter.get('/:id/episodes', async (req, res) => { try { const episodes = await Episode.findAll({ @@ -62,7 +63,7 @@ seasonRouter.get('/:id/episodes', async (req, res) => { } }); -// PUT /seasons/:id - Update a season +// * PUT - Update a season seasonRouter.put('/:id', async (req, res) => { try { const [updated] = await Season.update(req.body, { @@ -79,7 +80,7 @@ seasonRouter.put('/:id', async (req, res) => { } }); -// DELETE /seasons/:id - Delete a season +// * DELETE - Delete a season seasonRouter.delete('/:id', async (req, res) => { try { const deleted = await Season.destroy({ diff --git a/backend/routes/settings.routes.js b/backend/routes/settings.routes.js new file mode 100644 index 0000000..2e6ed11 --- /dev/null +++ b/backend/routes/settings.routes.js @@ -0,0 +1,33 @@ +const express = require('express'); +const { updateSettings, getSettings } = require('../services/settingsService'); +const settingsRouter = express.Router(); + +const settingsFileFormat = { + "dataFolderPath": "", + "tmdbApiUrl": "", + "tmdbApiKey": "", + "frontPort": "", + "backPort": "", + "portableMode": "", +}; + +// ! /settings +settingsRouter.put('/', async (req, res) => { + const settings = req.body; + + updateSettings(settings); + + res.status(200).send(getSettings()); +}); + +settingsRouter.get('/', (req, res) => { + try { + const settings = getSettings(); + + res.status(200).json(settings); + } catch (err) { + res.status(500).send('Error retrieving settings'); + } +}); + +module.exports = settingsRouter; diff --git a/backend/server.js b/backend/server.js index 47a6df5..391d333 100644 --- a/backend/server.js +++ b/backend/server.js @@ -1,22 +1,30 @@ -// server.js const express = require('express'); const bodyParser = require('body-parser'); const routes = require('./routes/routes.js'); const sequelize = require('./db/database.js'); const path = require('path'); +const fs = require('fs'); const app = express(); -const PORT = process.env.PORT || 4000; + const relations = require('./db/relations.js'); const sequelizeHooks = require('./db/sequelizeHooks.js'); -const { initializeGenres, initializeData } = require('./db/dataInitializer.js'); +const { initializeData } = require('./db/dataInitializer.js'); const killerRouter = require('./routes/killer.routes.js'); +const errorHandler = require('./middleware/errorHandler'); +const { getSettings } = require('./services/settingsService.js'); +const { logToFile } = require('./services/logService.js'); -// Middleware +// ? variables +let settings = getSettings() +const PORT = settings["backPort"] || 4000; +const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}'); + +// ? Middleware app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded -// CORS Middleware to allow requests from any origin +// * CORS Middleware to allow requests from any origin app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header( @@ -30,52 +38,65 @@ app.use((req, res, next) => { next(); }); -// ? Routes -// * media access route -app.use('/api/v1/media/:category/:type', (req, res, next) => { +// ? Routes : media access routes +app.use('/api/v1/media/:category/:type/:file', (req, res, next) => { const category = req.params.category; const type = req.params.type; + const file = req.params.file; if (!['entries', 'collections', 'franchises'].includes(category)) { return res.status(404).send('Not Found'); } - if (!['backdrops', 'posters', 'others'].includes(type)) { + if (!['backdrops', 'posters', 'logos', 'others'].includes(type)) { return res.status(404).send('Not Found'); } - const options = { - fallthrough: false, // ! Important: don't call next middleware if file isn't found - }; + const settings = getSettings(); + const dataPath = settings.userDataPath; - express.static(path.join(__dirname, '..', `uploads/${category}/${type}`), options)(req, res, next); + const mediaPath = path.join(dataPath, 'images', category, type); + // const mediaPath = path.join(__dirname, '..', `data/images/${category}/${type}`); + const filePath = path.join(mediaPath, file); + logToFile(filePath) + fs.access(filePath, fs.constants.F_OK, (err) => { + if (err) { + return res.status(404).send('Not Found'); + } + + const options = { + fallthrough: false, // ! Important: don't call next middleware if file isn't found + }; + + // express.static(filePath, options)(req, res, next); + // Serve the file using fs.createReadStream + const stream = fs.createReadStream(filePath); + stream.pipe(res); + }); }); -// * other api routes +// ? other api routes app.use('/api/v1', routes); - -// ! Error handling middleware -const errorHandler = require('./middleware/errorHandler'); +// ? Error handling middleware app.use(errorHandler); -// ! KILLER ROUTE: used to crash the backend +// ? KILLER ROUTE: used to crash the backend app.use('/killer', killerRouter); -// Start the server - +// * Start the server +const doUpdate = false; +const doForce = false; console.log(`Syncing database schema...`); sequelize // .sync({force: true}) // will drop all tables and recreate them. - // .sync({ alter: true }) // will attempt to automatically alter tables to fit the model definitions. - .sync() + .sync({ alter: doUpdate }) // will attempt to automatically alter tables to fit the model definitions. .then((result) => { - console.log(`Database schema synced...`); + console.log(`Database schema synced.`); initializeData(); app.listen(PORT, () => { - //const Entry = require("./models/Entry.js") - console.log(`Backend server running on http://localhost:${PORT}`); + console.log(`Backend server running on http://localhost:${PORT}/`); }); }) .catch(err => { diff --git a/backend/services/entryService.js b/backend/services/entryService.js index 309106c..1d7e362 100644 --- a/backend/services/entryService.js +++ b/backend/services/entryService.js @@ -515,7 +515,10 @@ async function refrechEntry(entryId) { if (oldEntry.is_tvseries) includes.push({ model: Season, as: 'seasons' }); const updatedEntry = await Entry.findByPk(entryId, { - include: includes + include: includes, + order: [ + [{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list + ] }); const entryData = updatedEntry.get({ plain: true }); diff --git a/backend/services/logService.js b/backend/services/logService.js new file mode 100644 index 0000000..5290a57 --- /dev/null +++ b/backend/services/logService.js @@ -0,0 +1,31 @@ +// logService.js +const fs = require('fs'); +const util = require('util'); + +// 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) => { + if (err) { + console.error("Failed to open log file:", err); + } else { + fs.close(fd, (err) => { + if (err) console.error("Failed to close log file:", err); + }); + } +}); + +// Asynchronous function to append a message to the log file +async function logToFile(message) { + try { + await writeFile(logFilePath, `${message}\n`, { flag: 'a' }); + } catch (err) { + console.error("Failed to write to log file:", err); + } +} + +module.exports = { + logToFile, +}; \ No newline at end of file diff --git a/backend/services/settingsService.js b/backend/services/settingsService.js new file mode 100644 index 0000000..e14ff20 --- /dev/null +++ b/backend/services/settingsService.js @@ -0,0 +1,61 @@ +const fs = require('fs'); +const path = require('path'); +const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}'); + +let userDataPath = ''; +const defaultSettings = { + userDataPath: '', + tmdbApiUrl: '', + tmdbApiKey: '', + frontPort: '', + backPort: '', + portableMode: '', +}; + +function getUserDataPath() { + // return parrentProcess.electron_path || path.join(__dirname, '..', '..', 'data'); + return path.join(__dirname, '..', '..'); +} + +function getSettingsFilePath() { + return path.join(getUserDataPath(), 'settings.json'); +} + +function getSettings() { + const settingsFilePath = getSettingsFilePath(); + + try { + const settingsData = fs.readFileSync(settingsFilePath); + // console.log(`Loaded settings file.`); + return JSON.parse(settingsData); + } catch (err) { + console.error('Error reading settings file:', err); + console.log('Creating default settings file...'); + + let newSettingsFile = { ...defaultSettings }; + + let defaultDataPath = path.join(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.'); + + return defaultSettings; + } +} + +function updateSettings(newSettings) { + const settingsFilePath = getSettingsFilePath(); + + let updatedSettings = { ...userDataPath, ...newSettings }; + fs.mkdirSync(newSettings.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)); +} + +module.exports = { + getSettings, + updateSettings +}; \ No newline at end of file diff --git a/frontend/src/app/app-routing.module.ts b/frontend/src/app/app-routing.module.ts index 4a068b9..f8b6c53 100644 --- a/frontend/src/app/app-routing.module.ts +++ b/frontend/src/app/app-routing.module.ts @@ -1,26 +1,30 @@ import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './features/home/home.component'; -import { SearchComponent } from './features/discover/search/search.component'; +import { SearchPageComponent } from './features/discover/search-page/search-page.component'; import { TrendingComponent } from './features/discover/trending/trending.component'; import { PopularComponent } from './features/discover/popular/popular.component'; import { LibraryComponent } from './features/library/library.component'; import { FavoritComponent } from './features/favorit/favorit.component'; import { WatchlistComponent } from './features/watchlist/watchlist.component'; -import { SettingsComponent } from './features/settings/settings.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, - { path: 'search', component: SearchComponent }, + { path: 'search', component: SearchPageComponent }, { path: 'popular', component: PopularComponent }, { path: 'trending', component: TrendingComponent }, { path: 'library', component: LibraryComponent }, { path: 'favorit', component: FavoritComponent }, { path: 'watchlist', component: WatchlistComponent }, - { path: 'settings', component: SettingsComponent }, - // { path: 'entry', component: LibraryComponent }, + { + path: 'settings', + loadChildren: () => + import('./features/settings/settings.module').then( + (m) => m.SettingsModule + ), + }, { path: 'entries', loadChildren: () => diff --git a/frontend/src/app/app.component.ts b/frontend/src/app/app.component.ts index 8f665bb..d5e84d5 100644 --- a/frontend/src/app/app.component.ts +++ b/frontend/src/app/app.component.ts @@ -1,4 +1,7 @@ import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core'; +import { NavigationEnd, Router } from '@angular/router'; +import { filter } from 'rxjs'; + import PerfectScrollbar from 'perfect-scrollbar'; @Component({ @@ -7,12 +10,25 @@ import PerfectScrollbar from 'perfect-scrollbar'; styleUrl: './app.component.css', }) export class AppComponent implements AfterViewInit { + title = 'Showy'; + @ViewChild('scrollContainer', { static: true }) scrollContainer!: ElementRef; private ps!: PerfectScrollbar; - title = 'ShowZ'; + constructor(private router: Router) {} ngAfterViewInit() { this.ps = new PerfectScrollbar(this.scrollContainer.nativeElement); + + this.router.events + .pipe(filter(event => event instanceof NavigationEnd)) + .subscribe(() => { + this.scrollToTop(); + }); + } + + scrollToTop() { + this.scrollContainer.nativeElement.scrollTop = 0; + this.ps.update(); } } diff --git a/frontend/src/app/app.module.ts b/frontend/src/app/app.module.ts index f7c9833..2efae5e 100644 --- a/frontend/src/app/app.module.ts +++ b/frontend/src/app/app.module.ts @@ -14,7 +14,7 @@ import { CommonModule, DatePipe } from '@angular/common'; import { HomeComponent } from './features/home/home.component'; import { PopularComponent } from './features/discover/popular/popular.component'; import { TrendingComponent } from './features/discover/trending/trending.component'; -import { SearchComponent } from './features/discover/search/search.component'; +import { SearchPageComponent } from './features/discover/search-page/search-page.component'; import { LibraryComponent } from './features/library/library.component'; import { DynamicEntryListComponent } from './shared/components/lists/dynamic-entry-list/dynamic-entry-list.component'; @@ -23,7 +23,6 @@ import { MainCardComponent } from './shared/components/cards/main-card/main-card import { FavoritComponent } from './features/favorit/favorit.component'; import { WatchlistComponent } from './features/watchlist/watchlist.component'; import { SharedModule } from './shared/shared.module'; -import { SettingsComponent } from './features/settings/settings.component'; import { ToastrModule } from 'ngx-toastr'; @NgModule({ @@ -53,11 +52,10 @@ import { ToastrModule } from 'ngx-toastr'; HomeComponent, PopularComponent, TrendingComponent, - SearchComponent, + SearchPageComponent, LibraryComponent, FavoritComponent, WatchlistComponent, - SettingsComponent, // ? temp shared components MainCardComponent, diff --git a/frontend/src/app/core/components/navbar/navbar.component.html b/frontend/src/app/core/components/navbar/navbar.component.html index 7a709fb..0d81417 100644 --- a/frontend/src/app/core/components/navbar/navbar.component.html +++ b/frontend/src/app/core/components/navbar/navbar.component.html @@ -580,19 +580,19 @@
{{this.entry.release_date | dateFormat:'yyyy'}} • {{genres}}
- -{{this.entry.original_title}}
-{{this.entry.tagline}}
-{{this.entry.storyline}}
++ {{this.entry.original_title}} • + {{this.entry.release_date | dateFormat:'yyyy'}} • {{genres}} +
+ +{{this.entry.tagline}}
+{{this.entry.storyline}}
+| Season | -Episode | -Date Seen | -Seen With | -Action | -
|---|---|---|---|---|
| {{ item.season_number == 0 ? 'Special' : 'Season '+ item.season_number }} | -{{ item.episode_number }} | -{{ item.date_seen | dateFormat:'MMM dd, yyyy' }} | -{{ item.seen_with }} | -
-
-
-
-
- |
+
| Season | +Episode | +Date Seen | +Seen With | +Action | +
|---|---|---|---|---|
| {{ item.season_number == 0 ? 'Special' : 'Season '+ item.season_number }} | +{{ item.episode_number }} | +{{ item.date_seen | dateFormat:'MMM dd, yyyy' }} | +{{ item.seen_with }} | +
+
+
+
+
+ |
-
Movies
16.5%55.21 USD
+Tv-Series
24.9%267.35 USD
+settings-api-keys works!
diff --git a/frontend/src/app/features/settings/settings-api-keys/settings-api-keys.component.spec.ts b/frontend/src/app/features/settings/settings-api-keys/settings-api-keys.component.spec.ts new file mode 100644 index 0000000..9531a51 --- /dev/null +++ b/frontend/src/app/features/settings/settings-api-keys/settings-api-keys.component.spec.ts @@ -0,0 +1,23 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { SettingsApiKeysComponent } from './settings-api-keys.component'; + +describe('SettingsApiKeysComponent', () => { + let component: SettingsApiKeysComponent; + let fixture: ComponentFixtureGeneral application settings
+Setup your API keys
+General application settings
+Setup your API keys
+