Add multi-language support and new repository methods for book synchronization

- Extend repository methods to handle API requests for fetching books, chapters, characters, and other entities with multilingual support (`lang: 'fr' | 'en'`).
- Add `uploadBookForSync` logic to consolidate and decrypt book data for synchronization.
- Refactor schema migration logic to remove console logs and streamline table recreation.
- Enhance error handling across database repositories and IPC methods.
This commit is contained in:
natreex
2025-12-22 16:44:12 -05:00
parent ff530f3442
commit 515d469ba7
17 changed files with 666 additions and 113 deletions

View File

@@ -34,14 +34,10 @@ export class DatabaseService {
this.db = new sqlite3.Database(dbPath);
this.userEncryptionKey = encryptionKey;
this.userId = userId;
// Initialize schema (creates tables if they don't exist)
initializeSchema(this.db);
// Run migrations (updates existing tables if needed)
runMigrations(this.db);
console.log(`Database initialized for user ${userId} at ${dbPath}`);
}
/**

View File

@@ -432,7 +432,7 @@ export default class Book {
return BookRepo.insertBook(id,userId,encryptedTitle,hashedTitle,encryptedSubTitle,hashedSubTitle,encryptedSummary,type,serie,publicationDate,desiredWordCount,lang);
}
public static async getBook(userId:string,bookId: string): Promise<BookProps> {
public static async getBook(userId:string,bookId: string, lang: 'fr' | 'en'): Promise<BookProps> {
const book:Book = new Book(bookId);
await book.getBookInfos(userId);
return {
@@ -1334,6 +1334,217 @@ export default class Book {
});
}
static async uploadBookForSync(userId:string,bookId: string,lang: "fr" | "en"): Promise<CompleteBook> {
const userKey: string = getUserEncryptionKey(userId);
const [
eritBooksRaw,
actSummariesRaw,
aiGuideLineRaw,
chaptersRaw,
charactersRaw,
guideLineRaw,
incidentsRaw,
issuesRaw,
locationsRaw,
plotPointsRaw,
worldsRaw
]: [
EritBooksTable[],
BookActSummariesTable[],
BookAIGuideLineTable[],
BookChaptersTable[],
BookCharactersTable[],
BookGuideLineTable[],
BookIncidentsTable[],
BookIssuesTable[],
BookLocationTable[],
BookPlotPointsTable[],
BookWorldTable[]
] = await Promise.all([
BookRepo.fetchEritBooksTable(userId, bookId,lang),
BookRepo.fetchBookActSummaries(userId, bookId,lang),
BookRepo.fetchBookAIGuideLine(userId, bookId,lang),
BookRepo.fetchBookChapters(userId, bookId,lang),
BookRepo.fetchBookCharacters(userId, bookId,lang),
BookRepo.fetchBookGuideLineTable(userId, bookId,lang),
BookRepo.fetchBookIncidents(userId, bookId,lang),
BookRepo.fetchBookIssues(userId, bookId,lang),
BookRepo.fetchBookLocations(userId, bookId,lang),
BookRepo.fetchBookPlotPoints(userId, bookId,lang),
BookRepo.fetchBookWorlds(userId, bookId,lang)
]);
const [
chapterContentsNested,
chapterInfosNested,
characterAttributesNested,
worldElementsNested,
locationElementsNested
]: [
BookChapterContentTable[][],
BookChapterInfosTable[][],
BookCharactersAttributesTable[][],
BookWorldElementsTable[][],
LocationElementTable[][]
] = await Promise.all([
Promise.all(chaptersRaw.map((chapter: BookChaptersTable): Promise<BookChapterContentTable[]> => BookRepo.fetchBookChapterContents(userId, chapter.chapter_id,lang))),
Promise.all(chaptersRaw.map((chapter: BookChaptersTable): Promise<BookChapterInfosTable[]> => BookRepo.fetchBookChapterInfos(userId, chapter.chapter_id,lang))),
Promise.all(charactersRaw.map((character: BookCharactersTable): Promise<BookCharactersAttributesTable[]> => BookRepo.fetchBookCharactersAttributes(userId, character.character_id,lang))),
Promise.all(worldsRaw.map((world: BookWorldTable): Promise<BookWorldElementsTable[]> => BookRepo.fetchBookWorldElements(userId, world.world_id,lang))),
Promise.all(locationsRaw.map((location: BookLocationTable): Promise<LocationElementTable[]> => BookRepo.fetchLocationElements(userId, location.loc_id,lang)))
]);
const chapterContentsRaw: BookChapterContentTable[] = chapterContentsNested.flat();
const chapterInfosRaw: BookChapterInfosTable[] = chapterInfosNested.flat();
const characterAttributesRaw: BookCharactersAttributesTable[] = characterAttributesNested.flat();
const worldElementsRaw: BookWorldElementsTable[] = worldElementsNested.flat();
const locationElementsRaw: LocationElementTable[] = locationElementsNested.flat();
const locationSubElementsNested: LocationSubElementTable[][] = await Promise.all(
locationElementsRaw.map((element: LocationElementTable): Promise<LocationSubElementTable[]> => BookRepo.fetchLocationSubElements(userId, element.element_id,lang))
);
const locationSubElementsRaw: LocationSubElementTable[] = locationSubElementsNested.flat();
const eritBooks: EritBooksTable[] = eritBooksRaw.map((book: EritBooksTable): EritBooksTable => ({
...book,
title: System.decryptDataWithUserKey(book.title, userKey),
sub_title: book.sub_title ? System.decryptDataWithUserKey(book.sub_title, userKey) : null,
summary: book.summary ? System.decryptDataWithUserKey(book.summary, userKey) : null,
cover_image: book.cover_image ? System.decryptDataWithUserKey(book.cover_image, userKey) : null
}));
const actSummaries: BookActSummariesTable[] = actSummariesRaw.map((actSummary: BookActSummariesTable): BookActSummariesTable => ({
...actSummary,
summary: actSummary.summary ? System.decryptDataWithUserKey(actSummary.summary, userKey) : null
}));
const aiGuideLine: BookAIGuideLineTable[] = aiGuideLineRaw.map((guideLine: BookAIGuideLineTable): BookAIGuideLineTable => ({
...guideLine,
global_resume: guideLine.global_resume ? System.decryptDataWithUserKey(guideLine.global_resume, userKey) : null,
themes: guideLine.themes ? System.decryptDataWithUserKey(guideLine.themes, userKey) : null,
tone: guideLine.tone ? System.decryptDataWithUserKey(guideLine.tone, userKey) : null,
atmosphere: guideLine.atmosphere ? System.decryptDataWithUserKey(guideLine.atmosphere, userKey) : null,
current_resume: guideLine.current_resume ? System.decryptDataWithUserKey(guideLine.current_resume, userKey) : null
}));
const chapters: BookChaptersTable[] = chaptersRaw.map((chapter: BookChaptersTable): BookChaptersTable => ({
...chapter,
title: System.decryptDataWithUserKey(chapter.title, userKey)
}));
const chapterContents: BookChapterContentTable[] = chapterContentsRaw.map((chapterContent: BookChapterContentTable): BookChapterContentTable => ({
...chapterContent,
content: chapterContent.content ? JSON.parse(System.decryptDataWithUserKey(chapterContent.content, userKey)) : null
}));
const chapterInfos: BookChapterInfosTable[] = chapterInfosRaw.map((chapterInfo: BookChapterInfosTable): BookChapterInfosTable => ({
...chapterInfo,
summary: chapterInfo.summary ? System.decryptDataWithUserKey(chapterInfo.summary, userKey) : null,
goal: chapterInfo.goal ? System.decryptDataWithUserKey(chapterInfo.goal, userKey) : null
}));
const characters: BookCharactersTable[] = charactersRaw.map((character: BookCharactersTable): BookCharactersTable => ({
...character,
first_name: System.decryptDataWithUserKey(character.first_name, userKey),
last_name: character.last_name ? System.decryptDataWithUserKey(character.last_name, userKey) : null,
category: System.decryptDataWithUserKey(character.category, userKey),
title: character.title ? System.decryptDataWithUserKey(character.title, userKey) : null,
role: character.role ? System.decryptDataWithUserKey(character.role, userKey) : null,
biography: character.biography ? System.decryptDataWithUserKey(character.biography, userKey) : null,
history: character.history ? System.decryptDataWithUserKey(character.history, userKey) : null
}));
const characterAttributes: BookCharactersAttributesTable[] = characterAttributesRaw.map((attribute: BookCharactersAttributesTable): BookCharactersAttributesTable => ({
...attribute,
attribute_name: System.decryptDataWithUserKey(attribute.attribute_name, userKey),
attribute_value: System.decryptDataWithUserKey(attribute.attribute_value, userKey)
}));
const guideLine: BookGuideLineTable[] = guideLineRaw.map((guide: BookGuideLineTable): BookGuideLineTable => ({
...guide,
tone: guide.tone ? System.decryptDataWithUserKey(guide.tone, userKey) : null,
atmosphere: guide.atmosphere ? System.decryptDataWithUserKey(guide.atmosphere, userKey) : null,
writing_style: guide.writing_style ? System.decryptDataWithUserKey(guide.writing_style, userKey) : null,
themes: guide.themes ? System.decryptDataWithUserKey(guide.themes, userKey) : null,
symbolism: guide.symbolism ? System.decryptDataWithUserKey(guide.symbolism, userKey) : null,
motifs: guide.motifs ? System.decryptDataWithUserKey(guide.motifs, userKey) : null,
narrative_voice: guide.narrative_voice ? System.decryptDataWithUserKey(guide.narrative_voice, userKey) : null,
pacing: guide.pacing ? System.decryptDataWithUserKey(guide.pacing, userKey) : null,
intended_audience: guide.intended_audience ? System.decryptDataWithUserKey(guide.intended_audience, userKey) : null,
key_messages: guide.key_messages ? System.decryptDataWithUserKey(guide.key_messages, userKey) : null
}));
const incidents: BookIncidentsTable[] = incidentsRaw.map((incident: BookIncidentsTable): BookIncidentsTable => ({
...incident,
title: System.decryptDataWithUserKey(incident.title, userKey),
summary: incident.summary ? System.decryptDataWithUserKey(incident.summary, userKey) : null
}));
const issues: BookIssuesTable[] = issuesRaw.map((issue: BookIssuesTable): BookIssuesTable => ({
...issue,
name: System.decryptDataWithUserKey(issue.name, userKey)
}));
const locations: BookLocationTable[] = locationsRaw.map((location: BookLocationTable): BookLocationTable => ({
...location,
loc_name: System.decryptDataWithUserKey(location.loc_name, userKey)
}));
const plotPoints: BookPlotPointsTable[] = plotPointsRaw.map((plotPoint: BookPlotPointsTable): BookPlotPointsTable => ({
...plotPoint,
title: System.decryptDataWithUserKey(plotPoint.title, userKey),
summary: plotPoint.summary ? System.decryptDataWithUserKey(plotPoint.summary, userKey) : null
}));
const worlds: BookWorldTable[] = worldsRaw.map((world: BookWorldTable): BookWorldTable => ({
...world,
name: System.decryptDataWithUserKey(world.name, userKey),
history: world.history ? System.decryptDataWithUserKey(world.history, userKey) : null,
politics: world.politics ? System.decryptDataWithUserKey(world.politics, userKey) : null,
economy: world.economy ? System.decryptDataWithUserKey(world.economy, userKey) : null,
religion: world.religion ? System.decryptDataWithUserKey(world.religion, userKey) : null,
languages: world.languages ? System.decryptDataWithUserKey(world.languages, userKey) : null
}));
const worldElements: BookWorldElementsTable[] = worldElementsRaw.map((worldElement: BookWorldElementsTable): BookWorldElementsTable => ({
...worldElement,
name: System.decryptDataWithUserKey(worldElement.name, userKey),
description: worldElement.description ? System.decryptDataWithUserKey(worldElement.description, userKey) : null
}));
const locationElements: LocationElementTable[] = locationElementsRaw.map((locationElement: LocationElementTable): LocationElementTable => ({
...locationElement,
element_name: System.decryptDataWithUserKey(locationElement.element_name, userKey),
element_description: locationElement.element_description ? System.decryptDataWithUserKey(locationElement.element_description, userKey) : null
}));
const locationSubElements: LocationSubElementTable[] = locationSubElementsRaw.map((locationSubElement: LocationSubElementTable): LocationSubElementTable => ({
...locationSubElement,
sub_elem_name: System.decryptDataWithUserKey(locationSubElement.sub_elem_name, userKey),
sub_elem_description: locationSubElement.sub_elem_description ? System.decryptDataWithUserKey(locationSubElement.sub_elem_description, userKey) : null
}));
return {
eritBooks,
actSummaries,
aiGuideLine,
chapters,
chapterContents,
chapterInfos,
characters,
characterAttributes,
guideLine,
incidents,
issues,
locations,
plotPoints,
worlds,
worldElements,
locationElements,
locationSubElements
};
}
static async saveCompleteBook(userId: string, data: CompleteBook, lang: "fr" | "en"):Promise<boolean> {
const userKey: string = getUserEncryptionKey(userId);
@@ -1723,7 +1934,6 @@ export default class Book {
}
}
}
console.log(data.id)
const book: EritBooksTable[] = await BookRepo.fetchCompleteBookById(data.id, lang);
if (book.length>0) {
const bookDataItem: EritBooksTable = book[0];

View File

@@ -1048,6 +1048,244 @@ export default class BookRepo {
}
return result;
}
static async fetchEritBooksTable(userId:string,bookId:string, lang: 'fr' | 'en'):Promise<EritBooksTable[]>{
try {
const db: Database = System.getDb();
return db.all('SELECT book_id, type, author_id, title, hashed_title, sub_title, hashed_sub_title, summary, serie_id, desired_release_date, desired_word_count, words_count, cover_image, last_update FROM erit_books WHERE book_id=? AND author_id=?', [bookId, userId]) as EritBooksTable[];
} catch (e:unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les informations du livre.` : `Unable to retrieve book information.`);
} else {
console.error("An unknown error occurred.");
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookActSummaries(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookActSummariesTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT act_sum_id, book_id, user_id, act_index, summary, last_update FROM book_act_summaries WHERE user_id=? AND book_id=?', [userId, bookId]) as BookActSummariesTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les résumés des actes.` : `Unable to retrieve act summaries.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookAIGuideLine(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookAIGuideLineTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT user_id, book_id, global_resume, themes, verbe_tense, narrative_type, langue, dialogue_type, tone, atmosphere, current_resume, last_update FROM book_ai_guide_line WHERE user_id=? AND book_id=?', [userId, bookId]) as BookAIGuideLineTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer la ligne directrice IA.` : `Unable to retrieve AI guideline.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookChapters(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookChaptersTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT chapter_id, book_id, author_id, title, hashed_title, words_count, chapter_order, last_update FROM book_chapters WHERE author_id=? AND book_id=?', [userId, bookId]) as BookChaptersTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les chapitres.` : `Unable to retrieve chapters.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookChapterContents(userId: string,chapterId:string, lang: 'fr' | 'en'): Promise<BookChapterContentTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT content_id, chapter_id, author_id, version, content, words_count, time_on_it, last_update FROM book_chapter_content WHERE author_id=? AND chapter_id=?', [userId, chapterId]) as BookChapterContentTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer le contenu des chapitres.` : `Unable to retrieve chapter contents.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookChapterInfos(userId: string, chapterId: string, lang: 'fr' | 'en'): Promise<BookChapterInfosTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT chapter_info_id, chapter_id, act_id, incident_id, plot_point_id, book_id, author_id, summary, goal, last_update FROM book_chapter_infos WHERE author_id=? AND chapter_id=?', [userId, chapterId]) as BookChapterInfosTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les infos des chapitres.` : `Unable to retrieve chapter infos.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookCharacters(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookCharactersTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT character_id, book_id, user_id, first_name, last_name, category, title, image, role, biography, history, last_update FROM book_characters WHERE user_id=? AND book_id=?', [userId, bookId]) as BookCharactersTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les personnages.` : `Unable to retrieve characters.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookCharactersAttributes(userId: string, characterId:string, lang: 'fr' | 'en'): Promise<BookCharactersAttributesTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT attr_id, character_id, user_id, attribute_name, attribute_value, last_update FROM book_characters_attributes WHERE user_id=? AND character_id=?', [userId, characterId]) as BookCharactersAttributesTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les attributs des personnages.` : `Unable to retrieve character attributes.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookGuideLineTable(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookGuideLineTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT user_id, book_id, tone, atmosphere, writing_style, themes, symbolism, motifs, narrative_voice, pacing, intended_audience, key_messages, last_update FROM book_guide_line WHERE user_id=? AND book_id=?', [userId, bookId]) as BookGuideLineTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer la ligne directrice.` : `Unable to retrieve guideline.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookIncidents(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookIncidentsTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT incident_id, author_id, book_id, title, hashed_title, summary, last_update FROM book_incidents WHERE author_id=? AND book_id=?', [userId, bookId]) as BookIncidentsTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les incidents.` : `Unable to retrieve incidents.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookIssues(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookIssuesTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT issue_id, author_id, book_id, name, hashed_issue_name, last_update FROM book_issues WHERE author_id=? AND book_id=?', [userId, bookId]) as BookIssuesTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les problématiques.` : `Unable to retrieve issues.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookLocations(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookLocationTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT loc_id, book_id, user_id, loc_name, loc_original_name, last_update FROM book_location WHERE user_id=? AND book_id=?', [userId, bookId]) as BookLocationTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les lieux.` : `Unable to retrieve locations.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookPlotPoints(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookPlotPointsTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT plot_point_id, title, hashed_title, summary, linked_incident_id, author_id, book_id, last_update FROM book_plot_points WHERE author_id=? AND book_id=?', [userId, bookId]) as BookPlotPointsTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les points d'intrigue.` : `Unable to retrieve plot points.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookWorlds(userId: string, bookId: string, lang: 'fr' | 'en'): Promise<BookWorldTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT world_id, name, hashed_name, author_id, book_id, history, politics, economy, religion, languages, last_update FROM book_world WHERE author_id=? AND book_id=?', [userId, bookId]) as BookWorldTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les mondes.` : `Unable to retrieve worlds.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchBookWorldElements(userId: string,worldId:string, lang: 'fr' | 'en'): Promise<BookWorldElementsTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT element_id, world_id, user_id, element_type, name, original_name, description, last_update FROM book_world_elements WHERE user_id=? AND world_id=?', [userId, worldId]) as BookWorldElementsTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les éléments du monde.` : `Unable to retrieve world elements.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchLocationElements(userId: string,locationId:string, lang: 'fr' | 'en'): Promise<LocationElementTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT element_id, location, user_id, element_name, original_name, element_description, last_update FROM location_element WHERE user_id=? AND location=?', [userId, locationId]) as LocationElementTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les éléments de lieu.` : `Unable to retrieve location elements.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static async fetchLocationSubElements(userId: string,elementId:string, lang: 'fr' | 'en'): Promise<LocationSubElementTable[]> {
try {
const db: Database = System.getDb();
return db.all('SELECT sub_element_id, element_id, user_id, sub_elem_name, original_name, sub_elem_description, last_update FROM location_sub_element WHERE user_id=? AND element_id=?', [userId, elementId]) as LocationSubElementTable[];
} catch (e: unknown) {
if (e instanceof Error) {
console.error(`DB Error: ${e.message}`);
throw new Error(lang === 'fr' ? `Impossible de récupérer les sous-éléments de lieu.` : `Unable to retrieve location sub-elements.`);
} else {
throw new Error(lang === 'fr' ? "Une erreur inconnue s'est produite." : "An unknown error occurred.");
}
}
}
static fetchSyncedBooks(userId: string, lang: 'fr' | 'en'): SyncedBookResult[] {
try {
const db: Database = System.getDb();

View File

@@ -483,7 +483,6 @@ function dropColumnIfExists(db: Database, tableName: string, columnName: string)
if (columnExists(db, tableName, columnName)) {
try {
db.exec(`ALTER TABLE ${tableName} DROP COLUMN ${columnName}`);
console.log(`[Migration] Dropped column ${columnName} from ${tableName}`);
} catch (e) {
console.error(`[Migration] Failed to drop column ${columnName} from ${tableName}:`, e);
}
@@ -502,7 +501,6 @@ function recreateTable(db: Database, tableName: string, newSchema: string, colum
db.exec(`INSERT INTO ${tableName} (${columnsToKeep}) SELECT ${columnsToKeep} FROM ${tableName}_backup`);
db.exec(`DROP TABLE ${tableName}_backup`);
db.exec('PRAGMA foreign_keys = ON');
console.log(`[Migration] Recreated table ${tableName}`);
} catch (e) {
console.error(`[Migration] Failed to recreate table ${tableName}:`, e);
db.exec('PRAGMA foreign_keys = ON');
@@ -519,12 +517,8 @@ export function runMigrations(db: Database): void {
return;
}
console.log(`[Migration] Upgrading schema from version ${currentVersion} to ${SCHEMA_VERSION}`);
// Migration v2: Remove NOT NULL constraints to allow null values from server sync
if (currentVersion < 2) {
console.log('[Migration] Running migration v2: Allowing NULL in certain columns...');
// Recreate erit_books with nullable hashed_sub_title and summary
recreateTable(db, 'erit_books', `
CREATE TABLE erit_books (
@@ -578,11 +572,8 @@ export function runMigrations(db: Database): void {
FOREIGN KEY (plot_point_id) REFERENCES book_plot_points(plot_point_id) ON DELETE CASCADE
)
`, 'chapter_info_id, chapter_id, act_id, incident_id, plot_point_id, book_id, author_id, summary, goal, last_update');
console.log('[Migration] Migration v2 completed');
}
// Update schema version
setDbSchemaVersion(db, SCHEMA_VERSION);
console.log(`[Migration] Schema updated to version ${SCHEMA_VERSION}`);
}

View File

@@ -117,7 +117,15 @@ ipcMain.handle('db:book:syncSave', createHandler<CompleteBook, boolean>(
// GET /book/:id - Get single book
ipcMain.handle('db:book:bookBasicInformation', createHandler<string, BookProps>(
async function(userId: string, bookId: string, lang: 'fr' | 'en'):Promise<BookProps> {
return await Book.getBook(userId, bookId);
return await Book.getBook(userId, bookId, lang);
}
)
);
// GET
ipcMain.handle('db:book:uploadToServer', createHandler<string, CompleteBook>(
async function(userId: string, bookId: string, lang: 'fr' | 'en'):Promise<CompleteBook> {
return await Book.uploadBookForSync(userId, bookId, lang);
}
)
);

View File

@@ -160,5 +160,3 @@ ipcMain.handle('db:chapter:information:remove', createHandler<RemoveChapterInfoD
}
)
);
console.log('[IPC] Chapter handlers registered');

View File

@@ -102,5 +102,3 @@ ipcMain.handle('db:location:subelement:delete', createHandler<DeleteLocationSubE
}
)
);
console.log('[IPC] Location handlers registered');

View File

@@ -1,7 +1,7 @@
import { ipcMain } from 'electron';
import { createHandler } from '../database/LocalSystem.js';
import * as bcrypt from 'bcrypt';
import { getSecureStorage } from '../storage/SecureStorage.js';
import SecureStorage, { getSecureStorage } from '../storage/SecureStorage.js';
import { getDatabaseService } from '../database/database.service.js';
interface SetPinData {
@@ -19,21 +19,18 @@ interface OfflineModeData {
ipcMain.handle('offline:pin:set', async (_event, data: SetPinData) => {
try {
const storage = getSecureStorage();
const userId = storage.get<string>('userId');
const storage: SecureStorage = getSecureStorage();
const userId: string | null = storage.get<string>('userId');
if (!userId) {
return { success: false, error: 'No user logged in' };
}
// Hash the PIN
const hashedPin = await bcrypt.hash(data.pin, 10);
const hashedPin: string = await bcrypt.hash(data.pin, 10);
// Store hashed PIN
storage.set(`pin-${userId}`, hashedPin);
storage.save();
console.log('[Offline] PIN set for user');
return { success: true };
} catch (error) {
console.error('[Offline] Error setting PIN:', error);
@@ -73,8 +70,7 @@ ipcMain.handle('offline:pin:verify', async (_event, data: VerifyPinData) => {
console.error('[Offline] No encryption key found for user');
return { success: false, error: 'No encryption key found' };
}
console.log('[Offline] PIN verified, user authenticated locally');
return {
success: true,
userId: lastUserId
@@ -99,7 +95,6 @@ ipcMain.handle('offline:mode:set', (_event, data: OfflineModeData) => {
}
storage.save();
console.log('[Offline] Mode set to:', data.enabled);
return { success: true };
} catch (error) {
@@ -157,6 +152,4 @@ ipcMain.handle('offline:sync:check', () => {
console.error('[Offline] Error checking sync:', error);
return { shouldSync: false };
}
});
console.log('[IPC] Offline handlers registered');
});

View File

@@ -1,4 +1,4 @@
import {app, BrowserWindow, ipcMain, nativeImage, protocol, safeStorage, shell} from 'electron';
import {app, BrowserWindow, ipcMain, IpcMainInvokeEvent, nativeImage, protocol, safeStorage, shell} from 'electron';
import * as path from 'path';
import {fileURLToPath} from 'url';
import * as fs from 'fs';
@@ -152,13 +152,13 @@ ipcMain.handle('set-lang', (_event, lang: 'fr' | 'en') => {
});
// IPC Handler pour initialiser l'utilisateur après récupération depuis le serveur
ipcMain.handle('init-user', async (_event, userId: string) => {
ipcMain.handle('init-user', async (_event:IpcMainInvokeEvent, userId: string) => {
const storage:SecureStorage = getSecureStorage();
storage.set('userId', userId);
storage.set('lastUserId', userId);
try {
let encryptionKey: string | null = null;
let encryptionKey: string | null;
if (!hasUserEncryptionKey(userId)) {
encryptionKey = generateUserEncryptionKey(userId);
@@ -170,14 +170,12 @@ ipcMain.handle('init-user', async (_event, userId: string) => {
setUserEncryptionKey(userId, encryptionKey);
const savedKey:string = getUserEncryptionKey(userId);
console.log('[InitUser] Key verification after save:', savedKey ? `${savedKey.substring(0, 10)}...` : 'UNDEFINED');
if (!savedKey) {
throw new Error('Failed to save encryption key');
}
} else {
encryptionKey = getUserEncryptionKey(userId);
console.log('[InitUser] Using existing encryption key:', encryptionKey ? `${encryptionKey.substring(0, 10)}...` : 'UNDEFINED');
if (!encryptionKey) {
console.error('[InitUser] CRITICAL: Existing key is undefined, regenerating');
@@ -189,14 +187,15 @@ ipcMain.handle('init-user', async (_event, userId: string) => {
if (safeStorage.isEncryptionAvailable()) {
storage.save();
console.log('[InitUser] User ID and lastUserId saved to disk (encrypted)');
} else {
console.error('[InitUser] WARNING: Cannot save user ID - encryption not available');
return {
success: false,
error: 'Encryption is not available on this system'
};
}
return { success: true, keyCreated: !hasUserEncryptionKey(userId) };
} catch (error) {
console.error('[InitUser] Error managing encryption key:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
@@ -205,7 +204,6 @@ ipcMain.handle('init-user', async (_event, userId: string) => {
});
ipcMain.on('login-success', async (_event, token: string) => {
console.log('[Login] Received token, setting in storage');
const storage = getSecureStorage();
storage.set('authToken', token);
@@ -215,7 +213,7 @@ ipcMain.on('login-success', async (_event, token: string) => {
createMainWindow();
setTimeout(async () => {
setTimeout(async ():Promise<void> => {
try {
if (safeStorage.isEncryptionAvailable()) {
storage.save();
@@ -294,7 +292,6 @@ ipcMain.handle('db:user:sync', async (_event, data: SyncUserData): Promise<boole
return true;
}
} catch (error) {
console.error('[DB] Failed to sync user:', error);
throw error;
}
});
@@ -307,7 +304,6 @@ ipcMain.handle('generate-encryption-key', async (_event, userId: string) => {
const key:string = generateUserEncryptionKey(userId);
return { success: true, key };
} catch (error) {
console.error('Failed to generate encryption key:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
@@ -341,7 +337,6 @@ ipcMain.handle('db-initialize', (_event, userId: string, encryptionKey: string)
db.initialize(userId, encryptionKey);
return { success: true };
} catch (error) {
console.error('Failed to initialize database:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
@@ -349,9 +344,9 @@ ipcMain.handle('db-initialize', (_event, userId: string, encryptionKey: string)
}
});
app.whenReady().then(() => {
app.whenReady().then(():void => {
if (!isDev) {
const outPath = path.join(process.resourcesPath, 'app.asar.unpacked/out');
const outPath:string = path.join(process.resourcesPath, 'app.asar.unpacked/out');
protocol.handle('app', async (request) => {
let filePath:string = request.url.replace('app://', '').replace(/^\.\//, '');
@@ -394,17 +389,8 @@ app.whenReady().then(() => {
}
// Vérifier si un token existe (OS-encrypted storage)
const storage = getSecureStorage();
const token = storage.get('authToken');
const userId = storage.get('userId');
const offlineMode = storage.get<boolean>('offlineMode', false);
const lastUserId = storage.get<string>('lastUserId');
const hasPin = !!storage.get<string>(`pin-${lastUserId}`);
console.log('[Startup] Token exists:', !!token);
console.log('[Startup] UserId exists:', !!userId);
console.log('[Startup] Offline mode:', offlineMode);
console.log('[Startup] Has PIN:', hasPin);
const storage: SecureStorage = getSecureStorage();
const token: string | null = storage.get('authToken');
if (token) {
createMainWindow();
@@ -412,10 +398,10 @@ app.whenReady().then(() => {
createLoginWindow();
}
app.on('activate', () => {
app.on('activate', ():void => {
if (BrowserWindow.getAllWindows().length === 0) {
const storage = getSecureStorage();
const token = storage.get('authToken');
const storage: SecureStorage = getSecureStorage();
const token: string | null = storage.get('authToken');
if (token) {
createMainWindow();
} else {
@@ -425,7 +411,6 @@ app.whenReady().then(() => {
});
});
app.on('window-all-closed', () => {
// Quitter l'application quand toutes les fenêtres sont fermées
app.on('window-all-closed', ():void => {
app.quit();
});