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:
91
app/login/offline/page.tsx
Normal file
91
app/login/offline/page.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import OfflinePinVerify from '@/components/offline/OfflinePinVerify';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faWifi, faArrowLeft } from '@fortawesome/free-solid-svg-icons';
|
||||
|
||||
export default function OfflineLoginPage() {
|
||||
const t = useTranslations();
|
||||
|
||||
async function handlePinSuccess(userId: string):Promise<void> {
|
||||
|
||||
// Initialize database with user's encryption key
|
||||
if (window.electron) {
|
||||
try {
|
||||
// Get encryption key
|
||||
const encryptionKey = await window.electron.getUserEncryptionKey(userId);
|
||||
if (encryptionKey) {
|
||||
// Initialize database
|
||||
await window.electron.dbInitialize(userId, encryptionKey);
|
||||
|
||||
// Navigate to main page
|
||||
window.location.href = '/';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[OfflineLogin] Error initializing database:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleBackToOnline():void {
|
||||
if (window.electron) {
|
||||
window.electron.logout();
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(():void => {
|
||||
// Check if we have offline capability
|
||||
async function checkOfflineCapability() {
|
||||
if (window.electron) {
|
||||
const offlineStatus = await window.electron.offlineModeGet();
|
||||
if (!offlineStatus.hasPin) {
|
||||
window.location.href = '/login/login';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
checkOfflineCapability().then();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col items-center justify-center bg-background text-textPrimary">
|
||||
<div className="w-full max-w-md px-4">
|
||||
{/* Offline indicator */}
|
||||
<div className="mb-6 flex items-center justify-center">
|
||||
<div className="px-4 py-2 bg-warning/10 border border-warning/30 rounded-full flex items-center gap-2">
|
||||
<FontAwesomeIcon icon={faWifi} className="w-4 h-4 text-warning" />
|
||||
<span className="text-sm text-warning font-medium">{t('offline.mode.title')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Logo */}
|
||||
<div className="flex justify-center mb-8">
|
||||
<img
|
||||
src="/logo.png"
|
||||
alt="ERitors"
|
||||
className="object-contain w-full max-w-[240px] h-[80px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* PIN Verify Component */}
|
||||
<OfflinePinVerify
|
||||
onSuccess={handlePinSuccess}
|
||||
onCancel={handleBackToOnline}
|
||||
/>
|
||||
|
||||
{/* Back to online link */}
|
||||
<div className="mt-6 text-center">
|
||||
<button
|
||||
onClick={handleBackToOnline}
|
||||
className="text-sm text-muted hover:text-textPrimary transition-colors inline-flex items-center gap-2"
|
||||
>
|
||||
<FontAwesomeIcon icon={faArrowLeft} className="w-3 h-3" />
|
||||
{t('offline.mode.backToOnline')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
19
app/page.tsx
19
app/page.tsx
@@ -30,7 +30,7 @@ import {NextIntlClientProvider, useTranslations} from "next-intl";
|
||||
import {LangContext} from "@/context/LangContext";
|
||||
import {AIUsageContext} from "@/context/AIUsageContext";
|
||||
import OfflineProvider from "@/context/OfflineProvider";
|
||||
import OfflineContext from "@/context/OfflineContext";
|
||||
import OfflineContext, {OfflineMode} from "@/context/OfflineContext";
|
||||
import OfflinePinSetup from "@/components/offline/OfflinePinSetup";
|
||||
import OfflinePinVerify from "@/components/offline/OfflinePinVerify";
|
||||
import {SyncedBook, BookSyncCompare, compareBookSyncs} from "@/lib/models/SyncedBook";
|
||||
@@ -234,7 +234,6 @@ function ScribeContent() {
|
||||
|
||||
if (!offlineStatus.hasPin) {
|
||||
setTimeout(():void => {
|
||||
console.log('[Page] Showing PIN setup dialog');
|
||||
setShowPinSetup(true);
|
||||
}, 2000);
|
||||
}
|
||||
@@ -374,13 +373,12 @@ function ScribeContent() {
|
||||
username: user.username,
|
||||
email: user.email
|
||||
});
|
||||
console.log('User synced to local DB');
|
||||
} catch (syncError) {
|
||||
console.error('Failed to sync user to local DB:', syncError);
|
||||
errorMessage(t("homePage.errors.syncError"));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize database:', error);
|
||||
errorMessage(t("homePage.errors.syncError"));
|
||||
}
|
||||
}
|
||||
setSession({
|
||||
@@ -396,7 +394,7 @@ function ScribeContent() {
|
||||
const offlineStatus = await window.electron.offlineModeGet();
|
||||
|
||||
if (offlineStatus.hasPin && offlineStatus.lastUserId) {
|
||||
setOfflineMode(prev => ({...prev, isOffline: true, isNetworkOnline: false}));
|
||||
setOfflineMode((prev:OfflineMode):OfflineMode => ({...prev, isOffline: true, isNetworkOnline: false}));
|
||||
setShowPinVerify(true);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
@@ -407,7 +405,7 @@ function ScribeContent() {
|
||||
}
|
||||
}
|
||||
} catch (offlineError) {
|
||||
console.error('[Auth] Error checking offline mode:', offlineError);
|
||||
errorMessage(t("homePage.errors.offlineError"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -429,7 +427,7 @@ function ScribeContent() {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Auth] Error checking offline mode:', error);
|
||||
errorMessage(t("homePage.errors.authenticationError"));
|
||||
}
|
||||
window.electron.logout();
|
||||
}
|
||||
@@ -557,10 +555,9 @@ function ScribeContent() {
|
||||
showPinSetup && window.electron && (
|
||||
<OfflinePinSetup
|
||||
showOnFirstLogin={true}
|
||||
onClose={() => setShowPinSetup(false)}
|
||||
onSuccess={() => {
|
||||
onClose={():void => setShowPinSetup(false)}
|
||||
onSuccess={():void => {
|
||||
setShowPinSetup(false);
|
||||
console.log('[Page] PIN configured successfully');
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -9,7 +9,7 @@ import {LangContext} from "@/context/LangContext";
|
||||
import {CompleteBook} from "@/lib/models/Book";
|
||||
import {BooksSyncContext, BooksSyncContextProps, SyncType} from "@/context/BooksSyncContext";
|
||||
import {AlertContext, AlertContextProps} from "@/context/AlertContext";
|
||||
import {BookSyncCompare} from "@/lib/models/SyncedBook";
|
||||
import {BookSyncCompare, SyncedBook} from "@/lib/models/SyncedBook";
|
||||
|
||||
interface SyncBookProps {
|
||||
bookId: string;
|
||||
@@ -24,15 +24,48 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
const {isCurrentlyOffline} = useContext<OfflineContextType>(OfflineContext);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [currentStatus, setCurrentStatus] = useState<SyncType>(status);
|
||||
const {booksToSyncToServer, booksToSyncFromServer} = useContext<BooksSyncContextProps>(BooksSyncContext)
|
||||
const {booksToSyncToServer, booksToSyncFromServer,serverSyncedBooks,localSyncedBooks,setLocalOnlyBooks, setServerOnlyBooks} = useContext<BooksSyncContextProps>(BooksSyncContext)
|
||||
|
||||
const isOffline: boolean = isCurrentlyOffline();
|
||||
|
||||
async function upload(): Promise<void> {
|
||||
// TODO: Implement upload local-only book to server
|
||||
if (isOffline) {
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const bookToSync: CompleteBook = await window.electron.invoke<CompleteBook>('db:book:uploadToServer', bookId);
|
||||
if (!bookToSync) {
|
||||
errorMessage(t("bookCard.uploadError"));
|
||||
return;
|
||||
}
|
||||
const response: boolean = await System.authPostToServer('book/sync/upload', {
|
||||
book: bookToSync
|
||||
}, session.accessToken, lang);
|
||||
if (!response) {
|
||||
errorMessage(t("bookCard.uploadError"));
|
||||
return;
|
||||
}
|
||||
setCurrentStatus('synced');
|
||||
setLocalOnlyBooks((prevBooks: SyncedBook[]): SyncedBook[] => {
|
||||
return prevBooks.filter((book: SyncedBook): boolean => book.id !== bookId)
|
||||
});
|
||||
} catch (e:unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("bookCard.uploadError"));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function download(): Promise<void> {
|
||||
if (isOffline) {
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response: CompleteBook = await System.authGetQueryToServer('book/sync/download', session.accessToken, lang, {bookId});
|
||||
if (!response) {
|
||||
@@ -45,12 +78,17 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
return;
|
||||
}
|
||||
setCurrentStatus('synced');
|
||||
setServerOnlyBooks((prevBooks: SyncedBook[]): SyncedBook[] => {
|
||||
return prevBooks.filter((book: SyncedBook): boolean => book.id !== bookId)
|
||||
});
|
||||
} catch (e:unknown) {
|
||||
if (e instanceof Error) {
|
||||
errorMessage(e.message);
|
||||
} else {
|
||||
errorMessage(t("bookCard.downloadError"));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +96,7 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
if (isOffline) {
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const bookToFetch:BookSyncCompare|undefined = booksToSyncFromServer.find((book:BookSyncCompare):boolean => book.id === bookId);
|
||||
if (!bookToFetch) {
|
||||
@@ -83,6 +122,8 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
} else {
|
||||
errorMessage(t("bookCard.syncFromServerError"));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +131,7 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
if (isOffline) {
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const bookToFetch:BookSyncCompare|undefined = booksToSyncToServer.find((book:BookSyncCompare):boolean => book.id === bookId);
|
||||
if (!bookToFetch) {
|
||||
@@ -101,7 +143,7 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
errorMessage(t("bookCard.syncToServerError"));
|
||||
return;
|
||||
}
|
||||
const response: boolean = await System.authPutToServer('book/sync/client-to-server', {
|
||||
const response: boolean = await System.authPatchToServer('book/sync/client-to-server', {
|
||||
book: bookToSync
|
||||
}, session.accessToken, lang);
|
||||
if (!response) {
|
||||
@@ -115,6 +157,8 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
} else {
|
||||
errorMessage(t("bookCard.syncToServerError"));
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +174,6 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Fully synced - no action needed */}
|
||||
{currentStatus === 'synced' && (
|
||||
<span
|
||||
className="text-gray-light"
|
||||
@@ -139,8 +182,7 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
<FontAwesomeIcon icon={faCloud} className="w-4 h-4"/>
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Local only - can upload to server */}
|
||||
|
||||
{currentStatus === 'local-only' && (
|
||||
<button
|
||||
onClick={upload}
|
||||
@@ -152,8 +194,6 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
<FontAwesomeIcon icon={faCloudArrowUp} className="w-4 h-4"/>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Server only - can download to local */}
|
||||
{currentStatus === 'server-only' && (
|
||||
<button
|
||||
onClick={download}
|
||||
@@ -165,8 +205,6 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
<FontAwesomeIcon icon={faCloudArrowDown} className="w-4 h-4"/>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Needs to sync from server (server has newer version) */}
|
||||
{currentStatus === 'to-sync-from-server' && (
|
||||
<button
|
||||
onClick={syncFromServer}
|
||||
@@ -178,8 +216,6 @@ export default function SyncBook({bookId, status}: SyncBookProps) {
|
||||
<FontAwesomeIcon icon={faCloudArrowDown} className="w-4 h-4"/>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Needs to sync to server (local has newer version) */}
|
||||
{currentStatus === 'to-sync-to-server' && (
|
||||
<button
|
||||
onClick={syncToServer}
|
||||
|
||||
@@ -16,9 +16,6 @@ interface BookCardProps {
|
||||
|
||||
export default function BookCard({book, onClickCallback, index, syncStatus}: BookCardProps) {
|
||||
const t = useTranslations();
|
||||
useEffect(() => {
|
||||
console.log(syncStatus)
|
||||
}, [syncStatus]);
|
||||
return (
|
||||
<div
|
||||
className="group bg-tertiary/90 backdrop-blur-sm rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 h-full border border-secondary/50 hover:border-primary/50 flex flex-col hover:scale-105">
|
||||
|
||||
@@ -265,10 +265,8 @@ export default function DraftCompanion() {
|
||||
useYourKey?: boolean;
|
||||
aborted?: boolean;
|
||||
} = JSON.parse(dataStr);
|
||||
|
||||
// Si c'est le message final avec les totaux
|
||||
|
||||
if ('totalCost' in data && 'useYourKey' in data && 'totalPrice' in data) {
|
||||
console.log(data);
|
||||
if (data.useYourKey) {
|
||||
setTotalPrice((prev: number): number => prev + data.totalPrice!);
|
||||
} else {
|
||||
|
||||
@@ -189,10 +189,8 @@ export default function GhostWriter() {
|
||||
useYourKey?: boolean;
|
||||
aborted?: boolean;
|
||||
} = JSON.parse(dataStr);
|
||||
|
||||
// Si c'est le message final avec les totaux
|
||||
|
||||
if ('totalCost' in data && 'useYourKey' in data && 'totalPrice' in data) {
|
||||
console.log(data)
|
||||
if (data.useYourKey) {
|
||||
setTotalPrice((prev: number): number => prev + data.totalPrice!);
|
||||
} else {
|
||||
|
||||
@@ -42,8 +42,7 @@ export default function OfflineProvider({ children }: OfflineProviderProps) {
|
||||
isDatabaseInitialized: true,
|
||||
error: null
|
||||
}));
|
||||
|
||||
console.log('Database initialized successfully for user:', userId);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize database:', error);
|
||||
@@ -57,17 +56,9 @@ export default function OfflineProvider({ children }: OfflineProviderProps) {
|
||||
}, []);
|
||||
|
||||
const toggleOfflineMode = useCallback(() => {
|
||||
setOfflineMode(prev => {
|
||||
const newManuallyOffline = !prev.isManuallyOffline;
|
||||
const newIsOffline = newManuallyOffline || !prev.isNetworkOnline;
|
||||
|
||||
console.log('Toggle offline mode:', {
|
||||
wasManuallyOffline: prev.isManuallyOffline,
|
||||
nowManuallyOffline: newManuallyOffline,
|
||||
wasOffline: prev.isOffline,
|
||||
nowOffline: newIsOffline,
|
||||
networkOnline: prev.isNetworkOnline
|
||||
});
|
||||
setOfflineMode((prev:OfflineMode):OfflineMode => {
|
||||
const newManuallyOffline:boolean = !prev.isManuallyOffline;
|
||||
const newIsOffline:boolean = newManuallyOffline || !prev.isNetworkOnline;
|
||||
|
||||
return {
|
||||
...prev,
|
||||
|
||||
@@ -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}`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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}`);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
@@ -160,5 +160,3 @@ ipcMain.handle('db:chapter:information:remove', createHandler<RemoveChapterInfoD
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
console.log('[IPC] Chapter handlers registered');
|
||||
|
||||
@@ -102,5 +102,3 @@ ipcMain.handle('db:location:subelement:delete', createHandler<DeleteLocationSubE
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
console.log('[IPC] Location handlers registered');
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -93,6 +93,34 @@ export default class System{
|
||||
}
|
||||
}
|
||||
|
||||
public static async authPatchToServer<T>(url: string, data: {}, auth: string, lang: string = "fr"): Promise<T> {
|
||||
try {
|
||||
const response: AxiosResponse<T> = await axios({
|
||||
method: 'patch',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${auth}`
|
||||
},
|
||||
params: {
|
||||
lang: lang,
|
||||
plateforme: 'web',
|
||||
},
|
||||
url: configs.apiUrl + url,
|
||||
data: data
|
||||
})
|
||||
return response.data;
|
||||
} catch (e: unknown) {
|
||||
if (axios.isAxiosError(e)) {
|
||||
const serverMessage: string = e.response?.data?.message || e.response?.data || e.message;
|
||||
throw new Error(serverMessage as string);
|
||||
} else if (e instanceof Error) {
|
||||
throw new Error(e.message);
|
||||
} else {
|
||||
throw new Error('An unexpected error occurred');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static async postToServer<T>(url: string, data: {}, lang: string = "fr"): Promise<T> {
|
||||
try {
|
||||
const response: AxiosResponse<T> = await axios({
|
||||
|
||||
Reference in New Issue
Block a user