implemented images maintenance, services + component

This commit is contained in:
X4Lo committed 2024-06-06 03:41:55 +01:00
1 parent ba96f540ca
commit 34766ba8e9
13 files changed
+448 -4

No files matched your search

+2 -1
View File
@@ -15,6 +15,7 @@ const Media = require('../models/Media');
const Episode = require('../models/Episode');
// ! /entries
// * GET - ALL ENTRIES
entryRouter.get('/', async (req, res) => {
const { page, pageSize } = req.body;
@@ -129,7 +130,6 @@ entryRouter.get('/:id/seasons', async (req, res) => {
}
});
// ! POST
// * POST - CREATE ENTRY
entryRouter.post('/', async (req, res) => {
const { tmdb_id, is_tvserie } = req.body;
@@ -181,6 +181,7 @@ entryRouter.post('/bulk-import-episodes-seen', async (req, res) => {
res.status(201).json(createdRows);
});
// + import routes end
// * PUT - ENTRY UPDATE
entryRouter.put('/:id', async (req, res) => {
const { id } = req.params;
+34
View File
@@ -0,0 +1,34 @@
const express = require('express');
const { deleteMissingFilesEntries, deleteOrphanFiles } = require('../services/maintenanceService');
const maintenanceRouter = express.Router();
// ! /maintenance
// * GET - Orphan files
maintenanceRouter.get('/orphan-files', async (req, res) => {
const deleted = await deleteOrphanFiles(true);
return res.status(200).json(deleted);
});
// * GET - Missing files
maintenanceRouter.get('/missing-files', async (req, res) => {
const deleted = await deleteMissingFilesEntries(true);
return res.status(200).json(deleted);
});
// * DELETE - Orphan files
maintenanceRouter.delete('/orphan-files', async (req, res) => {
const deleted = await deleteOrphanFiles();
return res.status(200).json(deleted);
});
// * DELETE - Missing files
maintenanceRouter.delete('/missing-files', async (req, res) => {
const deleted = await deleteMissingFilesEntries();
return res.status(200).json(deleted);
});
module.exports = maintenanceRouter;
+2
View File
@@ -7,6 +7,7 @@ const entryRatingsRouter = require('./entry-ratings.routes');
const seasonRouter = require('./season.routes');
const episodeSeenRouter = require('./episode-seen.routes');
const settingsRouter = require('./settings.routes');
const maintenanceRouter = require('./maintenance.routes');
const router = express.Router();
@@ -20,5 +21,6 @@ router.use('/seasons', seasonRouter);
router.use('/episode-seen', episodeSeenRouter);
router.use('/settings', settingsRouter);
router.use('/maintenance', maintenanceRouter)
module.exports = router;
+41 -2
View File
@@ -125,6 +125,8 @@ async function saveEntry(data) {
// + end of: seasons & episodes for tv series
// ? cast
// ? images
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
console.log(`entry service, downloaded images: `, downloadedImages)
@@ -490,9 +492,46 @@ async function refrechEntry(entryId) {
// if (!oldEntry.casts || oldEntry.casts.length == 0 || oldEntry.casts.length < oldEntry.max_cast) {
// }
// * Media
// * Only fetch if a Poster, Backdrop or a Logo is missing
// * Updating Media : Only fetch if a Poster, Backdrop or a Logo is missing
let downloadedImages;
if (oldEntry.medias.length == 0) {
// ? if no media is available, directly get all
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries);
} else {
// ? only get missing media types
let availableMedia = {
'posters': 0,
'logos': 0,
'backdrops': 0
};
// ? count media by type
for (let i = 0; i < oldEntry.medias.length; i++) {
availableMedia[oldEntry.medias[i].type] += 1;
}
// ? if the count of a media type == 0, the add the type to mediaToGet
let mediaToGet = [];
availableMedia.forEach(({ type, count }) => {
if (count == 0) mediaToGet.push(type);
});
if (mediaToGet.length != 0) {
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries, mediaToGet);
}
}
if (downloadedImages) {
for (const image of downloadedImages) {
await Media.create({
entry_id: oldEntry.id,
type: image.type,
path: image.path,
is_local: true,
is_selected: true
})
}
}
// + end of: refrech logic
+106
View File
@@ -0,0 +1,106 @@
const path = require('path');
const fsPromises = require('fs').promises;
const fs = require('fs');
const Media = require("../models/Media");
const { getSettings } = require("./settingsService");
const { logToFile } = require('./logService');
async function deleteMissingFilesEntries(dry = false) {
const allMedia = await Media.findAll();
// Getting the userDataPath to store the images
const dataPath = getSettings().userDataPath;
// Handling different media types
const mediaTypes = {
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
};
let missingFiles = [];
for (let i = 0; i < allMedia.length; i++) {
let type = `${allMedia[i].type}`;
const filePath = path.join(mediaTypes[type], allMedia[i].path)
if (!fs.existsSync(filePath)) {
missingFiles.push(allMedia[i]);
}
}
let removed = {
'posters': 0,
'logos': 0,
'backdrops': 0
};
if (missingFiles.length == 0)
return removed;
for (let i = 0; i < missingFiles.length; i++) {
removed[missingFiles[i].type] += 1;
if (!dry) missingFiles[i].destroy();
}
if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
return removed;
}
async function deleteOrphanFiles(dry = false) {
// Getting the userDataPath to store the images
const dataPath = getSettings().userDataPath;
// ? Getting the path of all media files and putting them in an array
const allMedia = (await Media.findAll()).map(m =>
path.join(dataPath, 'images', 'entries', m.type + 's', m.path)
);
// ? Loop trough the files of the images folder and check
// ? if a file doesnt exist in the allMedia array and mark it to delete
let orphanFiles = [];
const mediaTypes = {
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
};
let removed = {
'posters': 0,
'logos': 0,
'backdrops': 0
};
// Iterate over each media type directory and check for orphan files
for (let type in mediaTypes) {
const directory = mediaTypes[type];
try {
const files = await fsPromises.readdir(directory).then();
// Check each file in the directory
for (let file of files) {
const filePath = path.join(directory, file);
// Check if the constructed file path exists in the allMedia array
if (!allMedia.includes(filePath.replace("_preview", ""))) {
// If not, delete the file
if (!dry) await fsPromises.unlink(filePath);
removed[type + 's']++; // Increment the count of removed files
}
}
} catch (err) {
console.error(`Error handling files in ${directory}:`, err);
}
}
if (dry) logToFile(`Run a dry orphan files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
else logToFile(`Run an orphan files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
return removed;
}
module.exports = {
deleteMissingFilesEntries,
deleteOrphanFiles
};
@@ -0,0 +1,38 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment.prod';
import { MaintenanceResult } from '../../shared/models/maintenanceResult.model';
@Injectable({
providedIn: 'root',
})
export class MaintenanceService {
private backend_apiUrl = environment.API_URL;
private apiAction = 'maintenance';
constructor(private http: HttpClient) {}
getOrphanFiles() {
return this.http.get<MaintenanceResult>(
`${this.backend_apiUrl}/${this.apiAction}/orphan-files`
);
}
getMissingFiles() {
return this.http.get<MaintenanceResult>(
`${this.backend_apiUrl}/${this.apiAction}/missing-files`
);
}
deleteOrphanFiles() {
return this.http.delete<MaintenanceResult>(
`${this.backend_apiUrl}/${this.apiAction}/orphan-files`
);
}
deleteMissingFiles() {
return this.http.delete<MaintenanceResult>(
`${this.backend_apiUrl}/${this.apiAction}/missing-files`
);
}
}
@@ -0,0 +1,3 @@
.material-symbols-outlined {
vertical-align: middle; /* Aligns the icon vertically with the text */
}
@@ -0,0 +1,98 @@
<div class="container mt-5">
<div class="row">
<!-- Orphan Files Section -->
<div class="col-md-6">
<h3 class="mb-3">
<span class="material-symbols-outlined">variable_remove</span>
Orphan Images
</h3>
<div class="card">
<div class="card-body">
<h5 class="card-title">
<span class="material-symbols-outlined">image</span>
Posters
</h5>
<p class="card-text">{{ orphanFiles.posters }} items</p>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<h5 class="card-title">
<span class="material-symbols-outlined">abc</span>
Logos
</h5>
<p class="card-text">{{ orphanFiles.logos }} items</p>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<h5 class="card-title">
<span class="material-symbols-outlined">wallpaper</span>
Backdrops
</h5>
<p class="card-text">{{ orphanFiles.backdrops }} items</p>
</div>
</div>
<div class="card mt-3">
<button class="btn btn-danger" type="button" [disabled]="isLocked1" (click)="removeOrphanFiles()">
<ng-container *ngIf="isLocked1; else elseTemplate">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<span class=""> Removing Orphan Files...</span>
</ng-container>
<ng-template #elseTemplate>
Remove Orphan Images
</ng-template>
</button>
</div>
</div>
<!-- Missing Files Section -->
<div class="col-md-6">
<h3 class="mb-3">
<span class="material-symbols-outlined">scan_delete</span>
Missing Images
</h3>
<div class="card">
<div class="card-body">
<h5 class="card-title">
<span class="material-symbols-outlined">image</span>
Posters
</h5>
<p class="card-text">{{ missingFiles.posters }} items</p>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<h5 class="card-title">
<span class="material-symbols-outlined">abc</span>
Logos
</h5>
<p class="card-text">{{ missingFiles.logos }} items</p>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<h5 class="card-title">
<span class="material-symbols-outlined">wallpaper</span>
Backdrops
</h5>
<p class="card-text">{{ missingFiles.backdrops }} items</p>
</div>
</div>
<div class="card mt-3">
<button class="btn btn-danger" type="button" [disabled]="isLocked2" (click)="removeMissingFiles()">
<ng-container *ngIf="isLocked2; else elseTemplate">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<span class=""> Removing Missing Files...</span>
</ng-container>
<ng-template #elseTemplate>
Remove Missing Images
</ng-template>
</button>
</div>
</div>
<div class="alert alert-warning mt-3" role="alert">
<strong>Warning:</strong> Only use the "Remove Orphan/Missing Images" feature if some images are not showing up. If none of the images are appearing, it might be due to an incorrect "User Data Path". Please verify that it is correct in <strong>Settings > Application Settings</strong>.
</div>
</div>
</div>
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SettingsMaintenanceComponent } from './settings-maintenance.component';
describe('SettingsMaintenanceComponent', () => {
let component: SettingsMaintenanceComponent;
let fixture: ComponentFixture<SettingsMaintenanceComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [SettingsMaintenanceComponent]
})
.compileComponents();
fixture = TestBed.createComponent(SettingsMaintenanceComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,74 @@
import { Component, OnInit } from '@angular/core';
import { MaintenanceService } from '../../../core/services/maintenance.service';
import { MaintenanceResult } from '../../../shared/models/maintenanceResult.model';
@Component({
selector: 'app-settings-maintenance',
templateUrl: './settings-maintenance.component.html',
styleUrl: './settings-maintenance.component.css',
})
export class SettingsMaintenanceComponent implements OnInit {
orphanFiles: MaintenanceResult = {} as MaintenanceResult;
missingFiles: MaintenanceResult = {} as MaintenanceResult;
isLocked1: boolean = false;
isLocked2: boolean = false;
constructor(private maintenanceService: MaintenanceService) {}
ngOnInit(): void {
this.getMaintenanceStats();
}
getMaintenanceStats(): void {
this.maintenanceService.getOrphanFiles().subscribe({
next: (result) => {
this.orphanFiles = result;
},
error: (error) => {
console.log(`Error getting orphan files stats: `, error);
},
});
this.maintenanceService.getMissingFiles().subscribe({
next: (result) => {
this.missingFiles = result;
},
error: (error) => {
console.log(`Error getting missing files stats: `, error);
},
});
}
removeOrphanFiles(): void {
if (this.isLocked1) return;
this.isLocked1 = true;
this.maintenanceService.deleteOrphanFiles().subscribe({
next: (removed) => {
console.log(`Removed orphan files: `, removed);
this.getMaintenanceStats();
},
error: (error) => {
console.log(`Error deleting orphan files stats: `, error);
},
});
this.isLocked1 = false;
}
removeMissingFiles(): void {
if (this.isLocked2) return;
this.isLocked2 = true;
this.maintenanceService.deleteMissingFiles().subscribe({
next: (removed) => {
console.log(`Removed missing files: `, removed);
this.getMaintenanceStats();
},
error: (error) => {
console.log(`Error deleting missing files stats: `, error);
},
});
this.isLocked2 = false;
}
}
@@ -14,7 +14,7 @@
</div>
</div>
<!-- ? step 1 -->
<!-- ? step 2 -->
<div class="step" data-target="#test-vl-1" (click)="setStep(2)" [ngClass]="{ 'active': step == 2 }">
<div class="step-trigger" role="tab" aria-controls="test-vl-3" aria-selected="true">
<div class="bs-stepper-circle"><i class="material-icons-outlined">key</i></div>
@@ -25,6 +25,17 @@
</div>
</div>
<!-- ? step 3 -->
<div class="step" data-target="#test-vl-1" (click)="setStep(3)" [ngClass]="{ 'active': step == 3 }">
<div class="step-trigger" role="tab" aria-controls="test-vl-3" aria-selected="true">
<div class="bs-stepper-circle"><i class="material-icons-outlined">handyman</i></div>
<div class="">
<h5 class="mb-0 steper-title">Maintenance</h5>
<p class="mb-0 steper-sub-title">Clean up you database</p>
</div>
</div>
</div>
</div>
<!-- ! STEPPER CONTENT -->
@@ -45,6 +56,14 @@
<app-settings-api-keys></app-settings-api-keys>
</div>
<!-- ? step 3 -->
<div id="test-vl-3" class="bs-stepper-pane content fade dstepper-block" [ngClass]="{ 'active': step == 3 }"
*ngIf="step == 3">
<h5 class="mb-1">Maintenance</h5>
<p class="mb-4">Clean up you database</p>
<app-settings-maintenance></app-settings-maintenance>
</div>
</div>
</div>
</div>
@@ -9,6 +9,7 @@ import { SettingsRoutingModule } from './settings-routing.module';
import { SettingsPageComponent } from './settings-page/settings-page.component';
import { SettingsGeneralComponent } from './settings-general/settings-general.component';
import { SettingsApiKeysComponent } from './settings-api-keys/settings-api-keys.component';
import { SettingsMaintenanceComponent } from './settings-maintenance/settings-maintenance.component';
@NgModule({
imports: [
@@ -27,6 +28,7 @@ import { SettingsApiKeysComponent } from './settings-api-keys/settings-api-keys.
SettingsGeneralComponent,
SettingsApiKeysComponent,
SettingsMaintenanceComponent,
],
exports: [],
})
@@ -0,0 +1,5 @@
export interface MaintenanceResult {
posters: string;
backdrops: string;
logos: string;
}