Compare commits

..

15 Commits

62 changed files with 18466 additions and 2769 deletions

16
.editorconfig Normal file
View File

@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

2
.env Normal file
View File

@@ -0,0 +1,2 @@
DB_FILE_NAME=file:local.db
PORT=3000

7
.gitignore vendored
View File

@@ -40,3 +40,10 @@ testem.log
# System files
.DS_Store
Thumbs.db
*.db
.nx/cache
.nx/workspace-data
.aider*
.env

5
.prettierignore Normal file
View File

@@ -0,0 +1,5 @@
# Add files here to ignore them from prettier formatting
/dist
/coverage
/.nx/cache
/.nx/workspace-data

18
.prettierrc Normal file
View File

@@ -0,0 +1,18 @@
{
"arrowParens": "avoid",
"embeddedLanguageFormatting": "auto",
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"jsxBracketSameLine": false,
"jsxSingleQuote": false,
"printWidth": 220,
"proseWrap": "always",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"useTabs": false,
"vueIndentScriptAndStyle": false
}

View File

@@ -1,4 +1,7 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
"recommendations": [
"angular.ng-template",
"nrwl.angular-console",
"esbenp.prettier-vscode"
]
}

13
.vscode/launch.json vendored
View File

@@ -1,13 +1,14 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
"type": "node",
"request": "attach",
"name": "Attach to Nx Serve",
"port": 9229,
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/dist/api/**/*.js"],
"skipFiles": ["<node_internals>/**"]
}
]
}

29
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,29 @@
{
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"explorer.confirmDelete": false,
"typescript.updateImportsOnFileMove.enabled": "always",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"prettier.printWidth": 240,
"git.autofetch": false,
"git.autorefresh": true
}

View File

@@ -1,111 +0,0 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"vokabeltraining": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"inlineTemplate": true,
"inlineStyle": true,
"style": "scss",
"skipTests": true
},
"@schematics/angular:class": {
"skipTests": true
},
"@schematics/angular:directive": {
"skipTests": true
},
"@schematics/angular:guard": {
"skipTests": true
},
"@schematics/angular:interceptor": {
"skipTests": true
},
"@schematics/angular:pipe": {
"skipTests": true
},
"@schematics/angular:resolver": {
"skipTests": true
},
"@schematics/angular:service": {
"skipTests": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/vokabeltraining",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kB",
"maximumError": "4kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"proxyConfig": "src/proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "vokabeltraining:build:production"
},
"development": {
"buildTarget": "vokabeltraining:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
}
}
}
},
"cli": {
"analytics": false
}
}

5
api/.env Normal file
View File

@@ -0,0 +1,5 @@
DB_FILE_NAME=file:local.db
PORT=3000
FIREBASE_PROJECT_ID=haiki-452bd
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-fbsvc@haiki-452bd.iam.gserviceaccount.com
FIREBASE_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDyCsRhtPYwozBy\n60A4LguqsFzJG0WwCMhvi7PIxoh1kVenwxXBBQHvgssF/jPTkqbK6orL9r15gdRc\nZK2S73OdESYlO9xCE+gq/pop1F432DrHBA6ftQIl2NHSQfkKgTKFM6Pt85e6s5mb\neIxxHr7AzGMlqu7UJbnw8Vk2+8LP3NZXwsyCEi5vg4+8UgPFVxhLnB4HYZIM8JOj\nM3q1N/KqKgl2qGl5ekZLN7QLPs6+znlVZVIeHo1vuX9xTUaa6XUA0xeZfFO3pNUd\nKLlQNAy7OFQ6GlTFTWWHnShecLPHLQdWP15rkwBPv1q7qDmtLMy4E2XLvsoErhJM\niFsbEczxAgMBAAECggEAJqGJTn7vfDvPk8fwbAcNXaTgakisCricJRGLFFR7mygj\ncWc1paUC9hNODBrScsZJUMG2fW9YNnh+SHDZM0Z8kWkXSYIQWYuL1rDkMiDvGMKu\nPu1q2BqvyRKeCoz1DrQoOBJR67yhTu8zaRkIcVWS5Hq6qFxr2fhbgRVEQ/5SzZIG\nPh+Npxdp62Xe66MB0OzmF/A5qSrXTpOOk4/Lmpoqf6PtmrOD+SetE+Aa6ELYX3pK\n30XPLiUyDS+EFPjHLA1U7frOawLRpMP6Iobu7hUzu9ASzgLKxpzbcGRsPtbVRuAQ\nzP+iV+Nyn/wMFbnnjrjlwk/jqE+NLGJnf7Jrc9vwQQKBgQD5lfRWR6MKDezty5Qu\nPGrSlKXOM+aOoTmZiaPTutYzwWHeqzfUfYsghbgR3jl7I0BTqMaGrOnYU60IDWZi\nJeK6iu68pUe8Mme3vXm15Go55UhZD9U5/4W+x0/+AVivBPUBwKUXFdgmPFkb2jBY\np1LJmXaelx2jvPM3yMXQN+5flQKBgQD4Qy6aF3V7DIVxo/F88KCGNUpEobyXsxv6\nakSV+7WEtuSf6amXHxZyiJPtjCIwzCUL458gUd6mwiQgWRy7awdKreU6BCHgqNVf\nAE5ahjeeiLOc1uu0ocNLL+g35DbBXSgSlB+hUE0+bxAxU9xjNc9UZKqIi/kGRP/G\nlxi2ZUIQ7QKBgQDUH5Ku0evL29IGuQOT2F2h5ByXiJznlDd0Ovs2NJFhI3ae3T5y\nJtFcLsomxYxtD6TYdZVlWQjWhyeEtH7T5AczLGmDg6XYWa61ByCuaxetZSV8LGy5\nAmcVoihmZZaOCdSCTM0DNdmjhZ7mgSad8nf2R6v9VconI6xDOSyGr0K1kQKBgQCp\nuhxxIpqhzlSo9aFSfpvwRRyKQVzTBZOaJu7O7zARFIzHOxNDivBoyzD/FXAGlnq5\nXxvaF761mULjjqjTBQAOMUbm3A5hLmv5sBbhUqNR0jmhf1nTu0ft7km/dFlu5wZP\ndU8OlPzKM1oJr0Cb3xzooI3qHm/YtnF7Tq+Jez6onQKBgQCfbqG5dyTAduhPZzmp\n6m4ndzzdYVoh8KiM3fUApo/u9zF3GixUFgcKKFzP1/zmD6A6UfbVT+JVmUfIVtor\nAA42lqJyOaNH9ttQjZeDXfPpbAyAoZzH0l7/U9KSOkh+2I8tMscjWFqyQ1/DGNcY\nptIRECjQrk5jL0yea0+tbpMmJQ==\n-----END PRIVATE KEY-----\n

38
api/project.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "api",
"$schema": "../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "api/src",
"projectType": "application",
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"command": "webpack-cli build",
"args": ["node-env=production"]
},
"configurations": {
"development": {
"args": ["node-env=development"]
}
}
},
"serve": {
"executor": "@nx/js:node",
"defaultConfiguration": "development",
"dependsOn": ["build"],
"options": {
"buildTarget": "api:build",
"runBuildTargetDependencies": false
},
"configurations": {
"development": {
"buildTarget": "api:build:development"
},
"production": {
"buildTarget": "api:build:production"
}
}
}
},
"tags": []
}

12
api/src/app/app.module.ts Normal file
View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { DecksController } from './decks.controller';
import { DrizzleService } from './drizzle.service';
import { ProxyController } from './proxy.controller';
import { SqlLoggerService } from './sql-logger.service';
@Module({
imports: [],
controllers: [DecksController, ProxyController],
providers: [DrizzleService, SqlLoggerService],
})
export class AppModule {}

View File

@@ -0,0 +1,159 @@
// decks.controller.ts
import { Body, Controller, Delete, Get, HttpException, HttpStatus, Param, Post, Put, Request, UseGuards } from '@nestjs/common';
import { User } from '../db/schema';
import { AuthGuard } from '../service/auth.guard';
import { DrizzleService } from './drizzle.service';
@Controller('decks')
@UseGuards(AuthGuard)
export class DecksController {
constructor(private readonly drizzleService: DrizzleService) {}
@Get()
async getDecks(@Request() req) {
const user: User = req['user'];
const entries = await this.drizzleService.getDecks(user);
const decks = {};
for (const entry of entries) {
const deckname = entry.deckname!!;
if (!decks[deckname]) {
decks[deckname] = {
name: deckname,
images: [],
};
}
if (entry.bildname && entry.bildid) {
decks[deckname].images.push({
name: entry.bildname,
bildid: entry.bildid,
id: entry.id,
x1: entry.x1,
x2: entry.x2,
y1: entry.y1,
y2: entry.y2,
due: entry.due,
ivl: entry.ivl,
factor: entry.factor,
reps: entry.reps,
lapses: entry.lapses,
isGraduated: Boolean(entry.isGraduated),
inserted: new Date(entry.inserted!!),
updated: new Date(entry.updated!!),
});
}
}
return Object.values(decks);
}
@Post()
async createDeck(@Request() req, @Body() data: { deckname: string }) {
if (!data.deckname) {
throw new HttpException('No deckname provided', HttpStatus.BAD_REQUEST);
}
const user: User = req['user'];
return this.drizzleService.createDeck(data.deckname, user);
}
@Get(':deckname')
async getDeck(@Request() req, @Param('deckname') deckname: string) {
const user: User = req['user'];
const entries = await this.drizzleService.getDeckByName(deckname, user);
if (entries.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
const deck = {
name: deckname,
images: [] as any,
};
for (const entry of entries) {
if (entry.bildname && entry.bildid) {
deck.images.push({
name: entry.bildname,
bildid: entry.bildid,
id: entry.id,
x1: entry.x1,
x2: entry.x2,
y1: entry.y1,
y2: entry.y2,
due: entry.due,
ivl: entry.ivl,
factor: entry.factor,
reps: entry.reps,
lapses: entry.lapses,
isGraduated: Boolean(entry.isGraduated),
inserted: new Date(entry.inserted!!),
updated: new Date(entry.updated!!),
});
}
}
return deck;
}
@Delete(':deckname')
async deleteDeck(@Request() req, @Param('deckname') deckname: string) {
const user: User = req['user'];
return this.drizzleService.deleteDeck(deckname, user);
}
@Put(':oldDeckname/rename')
async renameDeck(@Request() req, @Param('oldDeckname') oldDeckname: string, @Body() data: { newDeckName: string }) {
if (!data.newDeckName) {
throw new HttpException('New deck name is required', HttpStatus.BAD_REQUEST);
}
const user: User = req['user'];
return this.drizzleService.renameDeck(oldDeckname, data.newDeckName, user);
}
@Post('image')
async updateImage(@Request() req, @Body() data: any) {
if (!data) {
throw new HttpException('No data provided', HttpStatus.BAD_REQUEST);
}
const user: User = req['user'];
const requiredFields = ['deckname', 'bildname', 'bildid', 'boxes'];
if (!requiredFields.every(field => field in data)) {
throw new HttpException('Missing fields in data', HttpStatus.BAD_REQUEST);
}
if (!Array.isArray(data.boxes) || data.boxes.length === 0) {
throw new HttpException("'boxes' must be a non-empty list", HttpStatus.BAD_REQUEST);
}
return this.drizzleService.updateImage(data, user);
}
@Delete('image/:bildid')
async deleteImagesByBildId(@Request() req, @Param('bildid') bildid: string) {
const user: User = req['user'];
return this.drizzleService.deleteImagesByBildId(bildid, user);
}
@Post('images/:bildid/move')
async moveImage(@Request() req, @Param('bildid') bildid: string, @Body() data: { targetDeckId: string }) {
if (!data.targetDeckId) {
throw new HttpException('No targetDeckId provided', HttpStatus.BAD_REQUEST);
}
const user: User = req['user'];
return this.drizzleService.moveImage(bildid, data.targetDeckId, user);
}
@Put('boxes/:id')
async updateBox(
@Request() req,
@Param('id') id: number,
@Body()
data: {
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?: boolean;
},
) {
const user: User = req['user'];
return this.drizzleService.updateBox(id, data, user);
}
}

View File

@@ -0,0 +1,252 @@
// drizzle.service.ts
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { and, eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/libsql';
import { Deck, SelectDeck, User } from '../db/schema';
import { SqlLoggerService } from './sql-logger.service';
@Injectable()
export class DrizzleService {
// private readonly logger = new Logger(DrizzleService.name);
private db: any;
constructor(private sqlLogger: SqlLoggerService) {
this.db = drizzle('file:local.db', {
logger: {
logQuery: (query: string, params: any[]) => {
this.sqlLogger.logQuery(query, params);
},
},
});
}
/**
* Methode zum Abrufen aller Decks eines Benutzers
*/
async getDecks(user: User) {
return this.db.select().from(Deck).where(eq(Deck.user, user.email));
}
/**
* Methode zum Erstellen eines neuen Decks
*/
async createDeck(deckname: string, user: User) {
// 'inserted' und 'updated' werden automatisch von der Datenbank gesetzt
const result = await this.db
.insert(Deck)
.values({
deckname,
user: user.email,
// 'inserted' und 'updated' werden von der DB automatisch gesetzt
})
.returning();
return { status: 'success', deck: result };
}
/**
* Methode zum Abrufen eines Decks nach Name
*/
async getDeckByName(deckname: string, user: User) {
return this.db
.select()
.from(Deck)
.where(and(eq(Deck.deckname, deckname), eq(Deck.user, user.email)));
}
/**
* Methode zum Löschen eines Decks
*/
async deleteDeck(deckname: string, user: User) {
const existingDeck = await this.getDeckByName(deckname, user);
if (existingDeck.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
await this.db.delete(Deck).where(and(eq(Deck.deckname, deckname), eq(Deck.user, user.email)));
return { status: 'success' };
}
/**
* Methode zum Umbenennen eines Decks
*/
async renameDeck(oldDeckname: string, newDeckname: string, user: User) {
const existingDeck = await this.getDeckByName(oldDeckname, user);
if (existingDeck.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
const existingNewDeck = await this.getDeckByName(newDeckname, user);
if (existingNewDeck.length > 0) {
throw new HttpException('Deck with the new name already exists', HttpStatus.CONFLICT);
}
await this.db
.update(Deck)
.set({
deckname: newDeckname,
updated: sql`CURRENT_TIMESTAMP`, // Setze 'updated' auf CURRENT_TIMESTAMP
})
.where(and(eq(Deck.deckname, oldDeckname), eq(Deck.user, user.email)));
return { status: 'success', message: 'Deck renamed successfully' };
}
/**
* Methode zum Aktualisieren eines Bildes innerhalb eines Decks
*/
async updateImage(
data: {
deckname: string;
bildname: string;
bildid: string;
boxes: Array<{ x1: number; x2: number; y1: number; y2: number; id?: number }>;
},
user: User,
) {
// Schritt 1: Überprüfen, ob das Deck existiert
const existingDecks: SelectDeck[] = await this.getDeckByName(data.deckname, user);
if (existingDecks.length === 0) {
throw new HttpException('Deck not found', HttpStatus.NOT_FOUND);
}
// Schritt 2: Trennen der neuen und bestehenden Einträge
const newEntries = data.boxes.filter(b => !b.id);
const existingEntries = data.boxes.filter(b => b.id);
// Schritt 3: Einfügen neuer Einträge
const insertedImages: any = [];
for (let index = 0; index < newEntries.length; index++) {
const box = newEntries[index];
const result = await this.db
.insert(Deck)
.values({
deckname: data.deckname,
bildname: data.bildname,
bildid: data.bildid,
x1: box.x1,
x2: box.x2,
y1: box.y1,
y2: box.y2,
user: user.email,
// 'inserted' und 'updated' werden automatisch von der DB gesetzt
})
.returning();
insertedImages.push(result);
}
// Schritt 4: Aktualisieren bestehender Einträge
for (let index = 0; index < existingEntries.length; index++) {
const box = existingEntries[index];
const existingDeck = existingDecks.find(d => d.id === box.id);
if (existingDeck && (existingDeck.x1 !== box.x1 || existingDeck.x2 !== box.x2 || existingDeck.y1 !== box.y1 || existingDeck.y2 !== box.y2)) {
const result = await this.db
.update(Deck)
.set({
x1: box.x1,
x2: box.x2,
y1: box.y1,
y2: box.y2,
updated: sql`CURRENT_TIMESTAMP`, // Setze 'updated' auf CURRENT_TIMESTAMP
})
.where(and(eq(Deck.user, user.email), eq(Deck.bildid, data.bildid), eq(Deck.deckname, data.deckname), eq(Deck.id, box.id!!)));
if (result.rowsAffected === 0) {
throw new HttpException(`Box with id ${box.id} not found`, HttpStatus.NOT_FOUND);
}
}
}
// Schritt 5: Löschen von nicht mehr vorhandenen Einträgen
// Sammle alle bestehenden IDs aus der Datenbank für das gegebene deckname und bildid
const existingIdsInDb = existingDecks.filter(entry => entry.bildid === data.bildid && entry.deckname === data.deckname).map(entry => entry.id);
// Sammle alle eingehenden IDs aus den vorhandenen Einträgen
const incomingIds = existingEntries.map(entry => entry.id);
// Bestimme die IDs, die in der Datenbank existieren, aber nicht mehr in den eingehenden Daten vorhanden sind
const idsToDelete = existingIdsInDb.filter(id => !incomingIds.includes(id));
if (idsToDelete.length > 0) {
await this.db.delete(Deck).where(and(eq(Deck.deckname, data.deckname), eq(Deck.bildid, data.bildid), eq(Deck.user, user.email), sql`id in ${idsToDelete}`));
}
return { status: 'success', inserted_images: insertedImages };
}
/**
* Methode zum Löschen von Bildern anhand der bildid
*/
async deleteImagesByBildId(bildid: string, user: User) {
const affectedDecks = await this.db
.select({ deckname: Deck.deckname })
.from(Deck)
.where(and(eq(Deck.bildid, bildid), eq(Deck.user, user.email)))
.all();
if (affectedDecks.length === 0) {
throw new HttpException('No entries found for the given image ID', HttpStatus.NOT_FOUND);
}
await this.db.delete(Deck).where(and(eq(Deck.bildid, bildid), eq(Deck.user, user.email)));
return {
status: 'success',
message: `All entries for image ID "${bildid}" have been deleted.`,
};
}
/**
* Methode zum Verschieben eines Bildes in ein anderes Deck
*/
async moveImage(bildid: string, targetDeckId: string, user: User) {
const existingImages = await this.db
.select()
.from(Deck)
.where(and(eq(Deck.bildid, bildid), eq(Deck.user, user.email)))
.all();
if (existingImages.length === 0) {
throw new HttpException('No entries found for the given image ID', HttpStatus.NOT_FOUND);
}
await this.db
.update(Deck)
.set({
deckname: targetDeckId,
updated: sql`CURRENT_TIMESTAMP`, // Setze 'updated' auf CURRENT_TIMESTAMP
})
.where(and(eq(Deck.bildid, bildid), eq(Deck.user, user.email)));
return { status: 'success', moved_entries: existingImages.length };
}
/**
* Methode zum Aktualisieren einer Box
*/
async updateBox(
id: number,
data: {
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?: boolean;
},
user: User,
) {
const updateData: any = { ...data };
if (typeof data.isGraduated === 'boolean') {
updateData.isGraduated = Number(data.isGraduated);
}
updateData.updated = sql`CURRENT_TIMESTAMP`; // Setze 'updated' auf CURRENT_TIMESTAMP
const result = await this.db
.update(Deck)
.set(updateData)
.where(and(eq(Deck.id, id), eq(Deck.user, user.email)));
if (result.rowsAffected === 0) {
throw new HttpException('Box not found', HttpStatus.NOT_FOUND);
}
return { status: 'success' };
}
}

View File

@@ -0,0 +1,57 @@
// decks.controller.ts
import { Body, Controller, HttpException, HttpStatus, Post, Res, UseGuards } from '@nestjs/common';
import express from 'express';
import { AuthGuard } from '../service/auth.guard';
@Controller('')
@UseGuards(AuthGuard)
export class ProxyController {
constructor() {}
// --------------------
// Proxy Endpoints
// --------------------
@Post('ocr')
async ocrEndpoint(@Body() data: { image: string }, @Res() res: express.Response) {
try {
if (!data || !data.image) {
throw new HttpException('No image provided', HttpStatus.BAD_REQUEST);
}
const response = await fetch('http://localhost:5000/api/ocr', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ image: data.image }),
});
const result = await response.json();
if (!response.ok) {
if (response.status === 400) {
throw new HttpException(result.error, HttpStatus.BAD_REQUEST);
}
throw new HttpException(result.error || 'OCR processing failed', HttpStatus.INTERNAL_SERVER_ERROR);
}
// Bei erfolgreicher Verarbeitung mit Warnung
if (result.warning) {
return res.status(HttpStatus.OK).json({
warning: result.warning,
debug_dir: result.debug_dir,
});
}
// Bei vollständig erfolgreicher Verarbeitung
return res.status(HttpStatus.OK).json({
status: result.status,
results: result.results,
});
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException('Internal server error', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@@ -0,0 +1,36 @@
// sql-logger.service.ts
import { Injectable, Logger } from '@nestjs/common';
import type { ChalkInstance } from 'chalk';
import chalk from 'chalk';
@Injectable()
export class SqlLoggerService {
private readonly logger = new Logger(SqlLoggerService.name);
private chalkInstance: ChalkInstance;
constructor() {
this.chalkInstance = chalk;
}
logQuery(query: string, params: any[], sourceIp?: string) {
const timestamp = new Date().toISOString().replace('T', ' ').replace('Z', '');
let logMessage = `[DrizzleORM] Info\t${timestamp}`;
// Optional source IP
if (sourceIp) {
logMessage += ` IP: ${sourceIp}`;
}
// Colored query and params using chalk directly
const coloredQuery = chalk.blueBright(`Query: ${query}`);
const coloredParams = chalk.yellow(`Params: ${JSON.stringify(params)}`);
logMessage += ` - ${coloredQuery} - ${coloredParams}`;
// Add timing indicator
logMessage += chalk.gray(' +2ms');
console.log(logMessage);
}
}

0
api/src/assets/.gitkeep Normal file
View File

52
api/src/db/schema.ts Normal file
View File

@@ -0,0 +1,52 @@
import { sql } from 'drizzle-orm';
import * as t from 'drizzle-orm/sqlite-core';
import { integer, real, sqliteTable as table, text } from 'drizzle-orm/sqlite-core';
export const Deck = table(
'Deck',
{
id: integer('id').primaryKey({ autoIncrement: true }),
deckname: text('deckname').notNull(),
bildname: text('bildname'),
bildid: text('bildid'),
x1: real('x1'),
x2: real('x2'),
y1: real('y1'),
y2: real('y2'),
due: integer('due'),
ivl: real('ivl'),
factor: real('factor'),
reps: integer('reps'),
lapses: integer('lapses'),
isGraduated: integer('isGraduated'),
user: text('user').notNull(),
inserted: text().default(sql`(CURRENT_TIMESTAMP)`), // Neue Spalte
updated: text().default(sql`(CURRENT_TIMESTAMP)`), // Neue Spalte
},
table => {
return {
index: t.uniqueIndex('email_idx').on(table.id),
};
},
);
export type InsertDeck = typeof Deck.$inferInsert;
export type SelectDeck = typeof Deck.$inferSelect;
export interface User {
name: string;
picture: string;
iss: string;
aud: string;
auth_time: number;
user_id: string;
sub: string;
iat: number;
exp: number;
email: string;
email_verified: boolean;
firebase: {
identities: any;
sign_in_provider: string;
};
uid: string;
}

24
api/src/main.ts Normal file
View File

@@ -0,0 +1,24 @@
/**
* This is not a production server yet!
* This is only a minimal backend to get started.
*/
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { json, urlencoded } from 'express';
import { AppModule } from './app/app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: ['log', 'error', 'warn', 'debug', 'verbose'], // Aktiviere alle Log-Level
});
app.use(json({ limit: '50mb' }));
app.use(urlencoded({ limit: '50mb', extended: true }));
const globalPrefix = 'api';
app.setGlobalPrefix(globalPrefix);
const port = process.env['PORT'] || 3000;
await app.listen(port);
Logger.log(`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`);
}
bootstrap();

View File

@@ -0,0 +1,27 @@
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import admin from './firebase-admin';
@Injectable()
export class AuthGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException('No token provided');
}
try {
const decodedToken = await admin.auth().verifyIdToken(token);
request['user'] = decodedToken; // Fügen Sie die Benutzerdaten dem Request-Objekt hinzu
return true;
} catch (error) {
throw new UnauthorizedException('Invalid token');
}
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers['authorization']?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}

View File

@@ -0,0 +1,16 @@
import * as admin from 'firebase-admin';
import { ServiceAccount } from 'firebase-admin';
const serviceAccount: ServiceAccount = {
projectId: process.env['FIREBASE_PROJECT_ID'],
clientEmail: process.env['FIREBASE_CLIENT_EMAIL'],
privateKey: process.env['FIREBASE_PRIVATE_KEY']?.replace(/\\n/g, '\n'), // Ersetzen Sie escaped newlines
};
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
export default admin;

12
api/tsconfig.app.json Normal file
View File

@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"module": "ES2020",
"types": ["node"],
"emitDecoratorMetadata": true,
"target": "es2021",
"strictNullChecks": true
},
"include": ["src/**/*.ts"]
}

13
api/tsconfig.json Normal file
View File

@@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
}
],
"compilerOptions": {
"esModuleInterop": true
}
}

20
api/webpack.config.js Normal file
View File

@@ -0,0 +1,20 @@
const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin');
const { join } = require('path');
module.exports = {
output: {
path: join(__dirname, '../dist/api'),
},
plugins: [
new NxAppWebpackPlugin({
target: 'node',
compiler: 'tsc',
main: './src/main.ts',
tsConfig: './tsconfig.app.json',
assets: ['./src/assets'],
optimization: false,
outputHashing: 'none',
generatePackageJson: true,
}),
],
};

10
drizzle.config.ts Normal file
View File

@@ -0,0 +1,10 @@
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './api/src/db/schema.ts',
dialect: 'sqlite',
dbCredentials: {
url: 'file:local1.db',
},
});

View File

@@ -0,0 +1,19 @@
CREATE TABLE `Deck` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`deckname` text NOT NULL,
`bildname` text,
`bildid` text,
`iconindex` integer,
`x1` real,
`x2` real,
`y1` real,
`y2` real,
`due` integer,
`ivl` real,
`factor` real,
`reps` integer,
`lapses` integer,
`isGraduated` integer
);
--> statement-breakpoint
CREATE UNIQUE INDEX `email_idx` ON `Deck` (`id`);

View File

@@ -0,0 +1 @@
ALTER TABLE `Deck` ADD `user` text NOT NULL;

View File

@@ -0,0 +1,2 @@
ALTER TABLE `Deck` ADD `inserted` text DEFAULT (CURRENT_TIMESTAMP);--> statement-breakpoint
ALTER TABLE `Deck` ADD `updated` text DEFAULT (CURRENT_TIMESTAMP);

View File

@@ -0,0 +1 @@
ALTER TABLE `Deck` DROP COLUMN `iconindex`;

View File

@@ -0,0 +1,141 @@
{
"version": "6",
"dialect": "sqlite",
"id": "3996df1c-a197-4842-869e-2e3b4f10064a",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"Deck": {
"name": "Deck",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"deckname": {
"name": "deckname",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"bildname": {
"name": "bildname",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"bildid": {
"name": "bildid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"iconindex": {
"name": "iconindex",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x1": {
"name": "x1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x2": {
"name": "x2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y1": {
"name": "y1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y2": {
"name": "y2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"due": {
"name": "due",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"ivl": {
"name": "ivl",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"factor": {
"name": "factor",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"reps": {
"name": "reps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lapses": {
"name": "lapses",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"isGraduated": {
"name": "isGraduated",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"email_idx": {
"name": "email_idx",
"columns": [
"id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View File

@@ -0,0 +1,148 @@
{
"version": "6",
"dialect": "sqlite",
"id": "a3cf5e86-4f1b-4cdc-9688-cf9063ba6936",
"prevId": "3996df1c-a197-4842-869e-2e3b4f10064a",
"tables": {
"Deck": {
"name": "Deck",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"deckname": {
"name": "deckname",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"bildname": {
"name": "bildname",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"bildid": {
"name": "bildid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"iconindex": {
"name": "iconindex",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x1": {
"name": "x1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x2": {
"name": "x2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y1": {
"name": "y1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y2": {
"name": "y2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"due": {
"name": "due",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"ivl": {
"name": "ivl",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"factor": {
"name": "factor",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"reps": {
"name": "reps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lapses": {
"name": "lapses",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"isGraduated": {
"name": "isGraduated",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"user": {
"name": "user",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"email_idx": {
"name": "email_idx",
"columns": [
"id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View File

@@ -0,0 +1,164 @@
{
"version": "6",
"dialect": "sqlite",
"id": "1e5421d8-df58-434e-93c8-85dcbe6ec9ee",
"prevId": "a3cf5e86-4f1b-4cdc-9688-cf9063ba6936",
"tables": {
"Deck": {
"name": "Deck",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"deckname": {
"name": "deckname",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"bildname": {
"name": "bildname",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"bildid": {
"name": "bildid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"iconindex": {
"name": "iconindex",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x1": {
"name": "x1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x2": {
"name": "x2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y1": {
"name": "y1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y2": {
"name": "y2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"due": {
"name": "due",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"ivl": {
"name": "ivl",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"factor": {
"name": "factor",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"reps": {
"name": "reps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lapses": {
"name": "lapses",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"isGraduated": {
"name": "isGraduated",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"user": {
"name": "user",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"inserted": {
"name": "inserted",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "(CURRENT_TIMESTAMP)"
},
"updated": {
"name": "updated",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "(CURRENT_TIMESTAMP)"
}
},
"indexes": {
"email_idx": {
"name": "email_idx",
"columns": [
"id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View File

@@ -0,0 +1,157 @@
{
"version": "6",
"dialect": "sqlite",
"id": "a0b561cf-8404-43ea-bc72-8b32671580bd",
"prevId": "1e5421d8-df58-434e-93c8-85dcbe6ec9ee",
"tables": {
"Deck": {
"name": "Deck",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"deckname": {
"name": "deckname",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"bildname": {
"name": "bildname",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"bildid": {
"name": "bildid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x1": {
"name": "x1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"x2": {
"name": "x2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y1": {
"name": "y1",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"y2": {
"name": "y2",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"due": {
"name": "due",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"ivl": {
"name": "ivl",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"factor": {
"name": "factor",
"type": "real",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"reps": {
"name": "reps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lapses": {
"name": "lapses",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"isGraduated": {
"name": "isGraduated",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"user": {
"name": "user",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"inserted": {
"name": "inserted",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "(CURRENT_TIMESTAMP)"
},
"updated": {
"name": "updated",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "(CURRENT_TIMESTAMP)"
}
},
"indexes": {
"email_idx": {
"name": "email_idx",
"columns": [
"id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View File

@@ -0,0 +1,34 @@
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1737229773082,
"tag": "0000_ambitious_hercules",
"breakpoints": true
},
{
"idx": 1,
"version": "6",
"when": 1737229845910,
"tag": "0001_smooth_iron_lad",
"breakpoints": true
},
{
"idx": 2,
"version": "6",
"when": 1738103858394,
"tag": "0002_aromatic_zodiak",
"breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1738235979220,
"tag": "0003_hard_cable",
"breakpoints": true
}
]
}

28
migrations.json Normal file
View File

@@ -0,0 +1,28 @@
{
"migrations": [
{
"version": "19.0.0",
"factory": "./use-application-builder/migration",
"description": "Migrate application projects to the new build system. Application projects that are using the '@angular-devkit/build-angular' package's 'browser' and/or 'browser-esbuild' builders will be migrated to use the new 'application' builder. You can read more about this, including known issues and limitations, here: https://angular.dev/tools/cli/build-system-migration",
"optional": true,
"recommended": true,
"documentation": "tools/cli/build-system-migration",
"package": "@angular/cli",
"name": "use-application-builder"
},
{
"version": "19.0.0",
"factory": "./update-workspace-config/migration",
"description": "Update the workspace configuration by replacing deprecated options in 'angular.json' for compatibility with the latest Angular CLI changes.",
"package": "@angular/cli",
"name": "update-workspace-config"
},
{
"version": "19.0.0",
"factory": "./update-ssr-imports/migration",
"description": "Update '@angular/ssr' import paths to use the new '/node' entry point when 'CommonEngine' is detected.",
"package": "@angular/cli",
"name": "update-ssr-imports"
}
]
}

26
nx.json Normal file
View File

@@ -0,0 +1,26 @@
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
}
},
"defaultBase": "master",
"namedInputs": {
"sharedGlobals": [],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": ["default"]
},
"plugins": [
{
"plugin": "@nx/webpack/plugin",
"options": {
"buildTargetName": "build",
"serveTargetName": "serve",
"previewTargetName": "preview"
}
}
]
}

17638
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,32 +3,68 @@
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development"
"start": "nx serve",
"start:all": "concurrently 'nx serve' 'http-server ../vocab-backend'",
"build": "nx build",
"watch": "nx build --watch --configuration development"
},
"private": true,
"dependencies": {
"@angular/animations": "^18.2.0",
"@angular/common": "^18.2.0",
"@angular/compiler": "^18.2.0",
"@angular/core": "^18.2.0",
"@angular/forms": "^18.2.0",
"@angular/platform-browser": "^18.2.0",
"@angular/platform-browser-dynamic": "^18.2.0",
"@angular/router": "^18.2.0",
"@angular/animations": "19.1.1",
"@angular/common": "19.1.1",
"@angular/compiler": "19.1.1",
"@angular/core": "19.1.1",
"@angular/fire": "^19.0.0",
"@angular/forms": "19.1.1",
"@angular/platform-browser": "19.1.1",
"@angular/platform-browser-dynamic": "19.1.1",
"@angular/router": "19.1.1",
"@libsql/client": "^0.14.0",
"@nestjs/common": "^10.0.2",
"@nestjs/core": "^10.0.2",
"@nestjs/platform-express": "^10.0.2",
"axios": "^1.6.0",
"dotenv": "^16.4.7",
"fabric": "^5.4.1",
"firebase": "^11.2.0",
"firebase-admin": "^13.0.2",
"flowbite": "^2.5.2",
"http-server": "^14.1.1",
"reflect-metadata": "^0.1.13",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
"zone.js": "~0.15.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.2.12",
"@angular/cli": "^18.2.12",
"@angular/compiler-cli": "^18.2.0",
"@angular-devkit/core": "19.1.2",
"@angular-devkit/schematics": "19.1.2",
"@angular/build": "^19.1.2",
"@angular/cli": "19.1.2",
"@angular/compiler-cli": "19.1.1",
"@nestjs/schematics": "^10.0.1",
"@nestjs/testing": "^10.0.2",
"@nx/angular": "20.3.2",
"@nx/js": "20.3.2",
"@nx/nest": "20.3.2",
"@nx/node": "20.3.2",
"@nx/web": "20.3.2",
"@nx/webpack": "20.3.2",
"@nx/workspace": "20.3.2",
"@schematics/angular": "^19.1.2",
"@swc-node/register": "~1.9.1",
"@swc/core": "~1.5.7",
"@swc/helpers": "~0.5.11",
"@types/fabric": "^5.3.9",
"@types/node": "~18.16.9",
"chalk": "^5.4.1",
"concurrently": "^9.1.2",
"drizzle-kit": "^0.30.2",
"drizzle-orm": "^0.38.4",
"nx": "20.3.2",
"prettier": "^2.6.2",
"tailwindcss": "^3.4.15",
"typescript": "~5.5.2"
"tsx": "^4.19.2",
"typescript": "~5.5.2",
"webpack-cli": "^5.1.4"
}
}

108
project.json Normal file
View File

@@ -0,0 +1,108 @@
{
"$schema": "node_modules/nx/schemas/project-schema.json",
"name": "vokabeltraining",
"projectType": "application",
"generators": {
"@schematics/angular:component": {
"inlineTemplate": true,
"inlineStyle": true,
"style": "scss",
"skipTests": true
},
"@schematics/angular:class": {
"skipTests": true
},
"@schematics/angular:directive": {
"skipTests": true
},
"@schematics/angular:guard": {
"skipTests": true
},
"@schematics/angular:interceptor": {
"skipTests": true
},
"@schematics/angular:pipe": {
"skipTests": true
},
"@schematics/angular:resolver": {
"skipTests": true
},
"@schematics/angular:service": {
"skipTests": true
}
},
"sourceRoot": "src",
"prefix": "app",
"targets": {
"build": {
"executor": "@angular/build:application",
"options": {
"outputPath": "dist/vokabeltraining",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.scss"
],
"scripts": [],
"fileReplacements": [
{
"replace": "src/app/environments/environment.ts",
"with": "src/app/environments/environment.prod.ts"
}
]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kB",
"maximumError": "4kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "vokabeltraining:build:production"
},
"development": {
"buildTarget": "vokabeltraining:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular/build:extract-i18n"
}
}
}

12
proxy.conf.json Normal file
View File

@@ -0,0 +1,12 @@
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
},
"/debug_images": {
"target": "http://localhost:8080",
"secure": false,
"changeOrigin": true
}
}

View File

@@ -1,23 +1,183 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { initFlowbite } from 'flowbite';
import { Component, inject } from '@angular/core';
import { Auth } from '@angular/fire/auth';
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
import { PopoverComponent } from './components/popover.component';
import { DeckListComponent } from './deck-list.component';
import { ClickOutsideDirective } from './service/click-outside.directive';
import { PopoverService } from './services/popover.service';
@Component({
selector: 'app-root',
template: `
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold text-center mb-8">Vokabeltraining</h1>
<div *ngIf="!isLoggedIn" class="min-h-screen flex flex-col items-center justify-center bg-gradient-to-r from-blue-500 to-purple-600 text-white">
<div class="text-center">
<h1 class="text-5xl font-bold mb-4">Master Your Vocabulary</h1>
<p class="text-xl mb-8">Learn smarter, not harder. Start your journey today.</p>
<button (click)="loginWithGoogle()" class="bg-white text-blue-600 px-6 py-3 rounded-lg shadow-lg hover:bg-gray-100 transition duration-300 flex items-center justify-center">
<svg class="w-6 h-6 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">
<path
fill="#FFC107"
d="M43.611 20.083H42V20H24v8h11.303c-1.649 4.657-6.08 8-11.303 8-6.627 0-12-5.373-12-12s5.373-12 12-12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 12.955 4 4 12.955 4 24s8.955 20 20 20 20-8.955 20-20c0-1.341-.138-2.65-.389-3.917z"
/>
<path fill="#FF3D00" d="M6.306 14.691l6.571 4.819C14.655 15.108 18.961 12 24 12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 16.318 4 9.656 8.337 6.306 14.691z" />
<path fill="#4CAF50" d="M24 44c5.166 0 9.86-1.977 13.409-5.192l-6.19-5.238A11.91 11.91 0 0124 36c-5.202 0-9.619-3.317-11.283-7.946l-6.522 5.025C9.505 39.556 16.227 44 24 44z" />
<path fill="#1976D2" d="M43.611 20.083H42V20H24v8h11.303a12.04 12.04 0 01-4.087 5.571l.003-.002 6.19 5.238C36.971 39.205 44 34 44 24c0-1.341-.138-2.65-.389-3.917z" />
</svg>
Login with Google
</button>
</div>
</div>
<div *ngIf="isLoggedIn" class="container mx-auto p-4">
<div class="flex justify-center items-center mb-8">
<h1 class="text-3xl font-bold mx-auto">Vocabulary Training</h1>
<div class="relative" appClickOutside (clickOutside)="showDropdown = false">
@if(photoURL){
<img [src]="photoURL" alt="User Photo" class="w-10 h-10 rounded-full cursor-pointer" (click)="toggleDropdown()" referrerpolicy="no-referrer" crossorigin="anonymous" />
} @else {
<div class="image-placeholder w-10 h-10 rounded-full cursor-pointer">Image</div>
} @if(showDropdown){
<div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg">
<button (click)="logout()" class="block w-full text-left px-4 py-2 text-gray-700 hover:bg-gray-100">Abmelden</button>
</div>
}
</div>
</div>
<app-deck-list></app-deck-list>
</div>
<app-popover
[visible]="popoverVisible"
[title]="popoverTitle"
[message]="popoverMessage"
[showInput]="popoverShowInput"
[showCancel]="popoverShowCancel"
[inputValue]="popoverInputValue"
[confirmText]="popoverConfirmText"
(confirmed)="handleConfirm($event)"
(canceled)="handleCancel()"
></app-popover>
`,
standalone: true,
imports: [ CommonModule, DeckListComponent]
styles: `
img {
border: 2px solid #fff;
transition: transform 0.2s;
}
img:hover {
transform: scale(1.1);
}
/* Stile für das Dropdown-Menü */
.dropdown {
display: none;
position: absolute;
right: 0;
margin-top: 0.5rem;
background-color: white;
border: 1px solid #e2e8f0;
border-radius: 0.375rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
.dropdown button {
width: 100%;
text-align: left;
padding: 0.5rem 1rem;
color: #4a5568;
}
.dropdown button:hover {
background-color: #f7fafc;
}
`,
imports: [CommonModule, DeckListComponent, ClickOutsideDirective, PopoverComponent],
})
export class AppComponent {
title = 'vokabeltraining';
ngOnInit(): void {
initFlowbite();
isLoggedIn = false;
private auth: Auth = inject(Auth);
showDropdown = false;
photoURL: string = 'https://placehold.co/40';
// user: User | null = null;
popoverVisible = false;
popoverTitle = '';
popoverMessage = '';
popoverShowInput = false;
popoverShowCancel = true;
popoverInputValue = '';
popoverConfirmText = 'Confirm';
private confirmCallback?: (inputValue?: string) => void;
private cancelCallback?: () => void;
constructor(public popoverService: PopoverService) {
this.popoverService.popoverState$.subscribe(options => {
this.popoverVisible = true;
this.popoverTitle = options.title;
this.popoverMessage = options.message;
this.popoverShowInput = options.showInput;
this.popoverShowCancel = options.showCancel;
this.popoverInputValue = options.inputValue;
this.popoverConfirmText = options.confirmText;
this.confirmCallback = options.onConfirm;
this.cancelCallback = options.onCancel;
});
}
ngOnInit() {
// Überprüfen des Login-Status beim Start der Anwendung
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
const accessToken = localStorage.getItem('accessToken');
const refreshToken = localStorage.getItem('refreshToken');
this.photoURL = localStorage.getItem('photoURL');
if (isLoggedIn && accessToken && refreshToken) {
this.isLoggedIn = true;
}
}
async loginWithGoogle() {
const provider = new GoogleAuthProvider();
try {
const result = await signInWithPopup(this.auth, provider);
this.isLoggedIn = true;
this.photoURL = result.user.photoURL;
// Speichern des Login-Status und Tokens im Local Storage
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('accessToken', await result.user.getIdToken());
localStorage.setItem('refreshToken', result.user.refreshToken);
localStorage.setItem('photoURL', result.user.photoURL);
this.showDropdown = false;
console.log('Logged in with Google', result.user);
} catch (error) {
console.error('Google Login failed', error);
}
}
logout() {
this.isLoggedIn = false;
localStorage.removeItem('isLoggedIn');
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
// Optional: Firebase-Logout durchführen
this.auth.signOut();
}
toggleDropdown() {
this.showDropdown = !this.showDropdown;
}
handleConfirm(inputValue?: string) {
this.popoverVisible = false;
if (this.confirmCallback) {
this.confirmCallback(inputValue);
}
}
handleCancel() {
this.popoverVisible = false;
if (this.cancelCallback) {
this.cancelCallback();
}
}
}

View File

@@ -1,9 +1,25 @@
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
import { getAuth, provideAuth } from '@angular/fire/auth';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';
import { environment } from './environments/environment';
import { authInterceptor } from './service/auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes),provideHttpClient()]
providers: [
// {
// provide: HTTP_INTERCEPTORS,
// useClass: AuthInterceptor,
// multi: true,
// },
provideFirebaseApp(() => initializeApp(environment.firebase)),
provideAuth(() => getAuth()),
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient(
withInterceptors([authInterceptor]), // Hier wird der Interceptor registriert
),
],
};

View File

@@ -0,0 +1,56 @@
// popover.component.ts
import { CommonModule } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-popover',
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<div class="fixed inset-0 bg-gray-500 bg-opacity-50 flex items-center justify-center z-50" *ngIf="visible">
<div class="bg-white rounded-lg p-6 max-w-xs w-full shadow-lg border border-gray-200">
<h3 class="text-lg font-semibold mb-4">{{ title }}</h3>
<p *ngIf="message" class="mb-4">{{ message }}</p>
<input *ngIf="showInput" type="text" class="w-full p-2 border rounded mb-4 focus:ring-2 focus:ring-blue-500 focus:border-transparent" [(ngModel)]="inputValue" (keyup.enter)="onConfirm()" autofocus />
<div class="flex justify-end space-x-2">
@if(showCancel){
<button (click)="onCancel()" class="px-4 py-2 rounded bg-gray-100 text-gray-700 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400">Cancel</button>
}
<button (click)="onConfirm()" class="px-4 py-2 rounded bg-blue-500 text-white hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
{{ confirmText }}
</button>
</div>
</div>
</div>
`,
})
export class PopoverComponent {
@Input() title: string = '';
@Input() message: string = '';
@Input() showInput: boolean = false;
@Input() showCancel: boolean = false;
@Input() confirmText: string = 'Confirm';
@Input() inputValue: string = '';
@Input() visible: boolean = false;
@Output() confirmed = new EventEmitter<string>();
@Output() canceled = new EventEmitter<void>();
onConfirm() {
this.confirmed.emit(this.inputValue);
//this.reset();
}
onCancel() {
this.canceled.emit();
//this.reset();
}
private reset() {
this.visible = false;
this.inputValue = '';
}
}

View File

@@ -1,4 +1,3 @@
<!-- src/app/create-deck-modal.component.html -->
<div #createDeckModal id="createDeckModal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full">
<div class="relative w-full h-full max-w-md md:h-auto">
<div class="relative bg-white rounded-lg shadow">
@@ -6,17 +5,17 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
<span class="sr-only">Schließen</span>
<span class="sr-only">Close</span>
</button>
<div class="p-6">
<h3 class="mb-4 text-xl font-medium text-gray-900">Neues Deck erstellen</h3>
<h3 class="mb-4 text-xl font-medium text-gray-900">Create New Deck</h3>
<form (submit)="createDeck($event)">
<div class="mb-4">
<label for="deckName" class="block text-sm font-medium text-gray-700">Deck-Name</label>
<label for="deckName" class="block text-sm font-medium text-gray-700">Deck Name</label>
<input type="text" id="deckName" [(ngModel)]="deckName" name="deckName" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" />
</div>
<button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Erstellen
Create
</button>
</form>
</div>

View File

@@ -1,15 +1,15 @@
// src/app/create-deck-modal.component.ts
import { Component, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { DeckService } from '../deck.service';
import { CommonModule } from '@angular/common';
import { Modal } from 'flowbite';
import { AfterViewInit, Component, ElementRef, EventEmitter, Output, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Modal } from 'flowbite';
import { DeckService } from '../deck.service';
import { PopoverService } from '../services/popover.service';
@Component({
selector: 'app-create-deck-modal',
templateUrl: './create-deck-modal.component.html',
standalone: true,
imports: [CommonModule, FormsModule]
imports: [CommonModule, FormsModule],
})
export class CreateDeckModalComponent implements AfterViewInit {
@Output() deckCreated = new EventEmitter<void>();
@@ -17,7 +17,7 @@ export class CreateDeckModalComponent implements AfterViewInit {
deckName: string = '';
modal!: Modal;
constructor(private deckService: DeckService) { }
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
ngAfterViewInit(): void {
this.modal = new Modal(this.modalElement.nativeElement);
@@ -30,7 +30,10 @@ export class CreateDeckModalComponent implements AfterViewInit {
createDeck(event: Event): void {
event.preventDefault();
if (this.deckName.trim() === '') {
alert('Bitte einen Deck-Namen eingeben.');
this.popoverService.show({
title: 'Information',
message: 'Please enter a deck name !',
});
return;
}
@@ -40,10 +43,13 @@ export class CreateDeckModalComponent implements AfterViewInit {
this.deckCreated.emit();
this.modal.hide();
},
error: (err) => {
console.error('Fehler beim Erstellen des Decks', err);
alert('Fehler beim Erstellen des Decks.');
}
error: err => {
console.error('Error creating deck', err);
this.popoverService.show({
title: 'Error',
message: 'Error creating deck.',
});
},
});
}
@@ -51,4 +57,3 @@ export class CreateDeckModalComponent implements AfterViewInit {
this.modal.hide();
}
}

View File

@@ -1,101 +1,162 @@
<!-- src/app/deck-list.component.html -->
<div>
<!-- Button zum Erstellen eines neuen Decks -->
<div class="flex justify-end mb-4">
<button (click)="openCreateDeckModal()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Neues Deck erstellen
</button>
</div>
<!-- Decks anzeigen -->
<div class="flex flex-wrap">
<div *ngFor="let deck of decks" class="bg-white shadow rounded-lg p-6 w-full md:w-1/2 lg:w-1/3 flex flex-col border-dashed border-2 border-indigo-600">
<!-- Deck-Header mit Toggle-Button -->
<div class="flex justify-between items-center mb-4">
<div class="flex items-center space-x-2">
<h2 class="text-xl font-semibold">{{ deck.name }}</h2>
<span class="text-gray-600">({{ deck.images.length }} Bilder)</span>
<div class="flex flex-col">
<!-- Two-column layout -->
<div *ngIf="!trainingsDeck" class="flex flex-col md:flex-row gap-4 mx-auto max-w-5xl">
<!-- Left column: List of decks -->
<div class="w-auto">
<div class="bg-white shadow rounded-lg p-4">
<div class="flex">
<h2 class="text-xl font-semibold mb-4">Decks</h2>
<button (click)="openCreateDeckModal()" class="text-gray-500 hover:text-gray-700 focus:outline-none flex items-start ml-2.5 translate-y-0.5">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="#2563eb">
<circle cx="12" cy="12" r="9" stroke-width="2" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v8M8 12h8" />
</svg>
</button>
</div>
<div class="space-y-2">
<div *ngFor="let deck of decks" class="flex justify-between items-center p-2 rounded hover:bg-gray-300 cursor-pointer" [class.bg-blue-200]="isDeckActive(deck)" (click)="toggleDeckExpansion(deck)">
<div class="flex flex-col space-y-1">
<div class="flex items-center space-x-2 whitespace-nowrap">
<h3 class="font-medium">{{ deck.name }}</h3>
<span class="text-gray-600">({{ deck.images.length }} Pics)</span>
</div>
<div class="text-sm text-gray-600">
<div>Next training: {{ getNextTrainingString(deck) }}</div>
<div>Words to review: {{ getWordsToReview(deck) }}</div>
</div>
</div>
<button class="text-gray-500 hover:text-gray-700 focus:outline-none">
<svg *ngIf="!isDeckActive(deck)" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transform rotate-0 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
<svg *ngIf="isDeckActive(deck)" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transform rotate-180 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
</button>
</div>
</div>
<button (click)="toggleDeckExpansion(deck.name)" class="text-gray-500 hover:text-gray-700 focus:outline-none" title="Deck ein-/ausklappen">
<svg *ngIf="!isDeckExpanded(deck.name)" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transform rotate-0 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
<svg *ngIf="isDeckExpanded(deck.name)" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transform rotate-180 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
</div>
<!-- Bildliste und Action-Buttons nur anzeigen, wenn das Deck erweitert ist und kein Training aktiv ist -->
<ng-container *ngIf="isDeckExpanded(deck.name) && !selectedDeck">
<!-- Liste der Bilder mit Anzahl der Boxen und Icons -->
<!-- Right column: Active deck details -->
<div class="w-auto min-w-96" *ngIf="activeDeck">
<div class="bg-white shadow rounded-lg p-6 border-dashed border-2 border-gray-300">
<!-- Deck header -->
<div class="flex justify-between items-center mb-4">
<div class="flex items-center space-x-2">
<h2 class="text-xl font-semibold">{{ activeDeck.name }}</h2>
<span class="text-gray-600">({{ activeDeck.images.length }} images)</span>
</div>
<div class="flex space-x-2">
<button (click)="openDeletePopover(activeDeck.name)" class="text-red-500 hover:text-red-700" title="Delete Deck">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<button (click)="openRenamePopover(activeDeck)" class="text-yellow-500 hover:text-yellow-700" title="Rename Deck">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
</svg>
</button>
</div>
</div>
<!-- Image list -->
<ul class="mb-4">
<li *ngFor="let image of deck.images" class="flex justify-between items-center py-2 border-b last:border-b-0">
<li *ngFor="let image of activeDeck.images" class="flex justify-between items-center py-2 border-b last:border-b-0">
<div class="flex items-center space-x-2">
<div class="relative group">
<!-- Tooltip Inhalt (Bild) -->
<div class="absolute left-0 bottom-full mb-2 w-48 bg-white border border-gray-300 rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 z-10 pointer-events-none">
<img src="/api/debug_image/{{image.id}}/thumbnail.jpg" alt="{{ image.name }}" class="w-full h-auto object-cover">
<img src="/debug_images/{{ image.bildid }}/thumbnail.jpg" alt="{{ image.name }}" class="w-full h-auto object-cover" />
</div>
<!-- Bildname mit Tooltip -->
<span class="font-medium cursor-pointer">
{{ image.name }}
</span>
<span class="font-medium cursor-pointer">{{ image.name }}</span>
</div>
<span class="text-gray-600">({{ image.boxes.length }} Boxen)</span>
<span class="text-gray-600">({{ image.boxes.length }} boxes)</span>
</div>
<div class="flex space-x-2">
<!-- Edit Icon -->
<button (click)="editImage(deck, image)" class="text-blue-500 hover:text-blue-700" title="Bild bearbeiten">
<button (click)="editImage(activeDeck, image)" class="text-blue-500 hover:text-blue-700" title="Edit Image">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 4H4v7m0 0l9-9 9 9M20 13v7h-7m0 0l-9-9-9 9" />
</svg>
</button>
<!-- Delete Icon -->
<button (click)="deleteImage(deck, image)" class="text-red-500 hover:text-red-700" title="Bild löschen">
<button (click)="deleteImage(activeDeck, image)" class="text-red-500 hover:text-red-700" title="Delete Image">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- Move Icon -->
<button (click)="openMoveImageModal(deck, image)" class="text-yellow-500 hover:text-yellow-700" title="Bild verschieben">
<button (click)="openMoveImageModal(activeDeck, image)" class="text-yellow-500 hover:text-yellow-700" title="Move Image">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
</button>
</button>
</div>
</li>
</ul>
<!-- Action-Buttons -->
<div class="flex space-x-2">
<button (click)="openTraining(deck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Training starten
</button>
<button (click)="openUploadImageModal(deck.name)" class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Bild hinzufügen
</button>
<div class="flex flex-row space-x-2">
<button (click)="openTraining(activeDeck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">Start Training</button>
<div class="flex-1">
<div class="relative">
<label for="imageFile" class="flex justify-center items-center bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600 cursor-pointer"> Add Image </label>
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/jpeg,image/png,image/gif,image/webp" required class="hidden" />
</div>
</div>
</div>
</ng-container>
</div>
</div>
</div>
<!-- Loading overlay -->
<div *ngIf="loading" class="absolute inset-0 bg-gray-800 bg-opacity-50 flex items-center justify-center z-10">
<div class="bg-white p-4 rounded shadow">
<p class="text-sm text-gray-700">Processing in progress...</p>
</div>
</div>
<!-- CreateDeckModalComponent -->
<app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal>
<!-- UploadImageModalComponent -->
<!-- <app-upload-image-modal [deckName]="currentUploadDeckName" (imageUploaded)="loadDecks()"></app-upload-image-modal> -->
<app-upload-image-modal (imageUploaded)="onImageUploaded($event)"> </app-upload-image-modal>
<app-edit-image-modal *ngIf="imageData" [deckName]="currentUploadDeckName" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal>
<!-- <app-upload-image-modal (imageUploaded)="onImageUploaded($event)"></app-upload-image-modal> -->
<app-edit-image-modal *ngIf="imageData" [deckName]="activeDeck.name" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal>
<!-- TrainingComponent -->
<app-training *ngIf="selectedDeck" [deck]="selectedDeck" (close)="closeTraining()"></app-training>
<!-- MoveImageModalComponent -->
<app-move-image-modal
*ngIf="imageToMove"
[image]="imageToMove.image"
[sourceDeck]="imageToMove.sourceDeck"
[decks]="decks"
(moveCompleted)="onImageMoved()"
(closed)="imageToMove = null">
</app-move-image-modal>
<app-training *ngIf="trainingsDeck" [deck]="trainingsDeck" (close)="closeTraining()"></app-training>
<!-- MoveImageModalComponent -->
<app-move-image-modal *ngIf="imageToMove" [image]="imageToMove.image" [sourceDeck]="imageToMove.sourceDeck" [decks]="decks" (moveCompleted)="onImageMoved()" (closed)="imageToMove = null"> </app-move-image-modal>
</div>
<!-- Popover für die Löschbestätigung -->
<!-- <div id="deletePopover" popover="manual" class="popover">
<p>Are you sure you want to delete this deck?</p>
<div class="flex justify-end space-x-2">
<button (click)="confirmDelete()" class="bg-red-500 text-white px-4 py-2 rounded">Delete</button>
<button (click)="cancelDelete()" class="bg-gray-500 text-white px-4 py-2 rounded">Cancel</button>
</div>
</div> -->
<!-- Popover für die Eingabe des neuen Decknamens -->
<!-- <div id="renamePopover" popover="manual" class="popover">
<p>Enter the new name for the deck:</p>
<input type="text" id="newDeckNameInput" class="w-full p-2 border rounded mb-2" [value]="deckToRename?.name" />
<div class="flex justify-end space-x-2">
<button (click)="confirmRename()" class="bg-blue-500 text-white px-4 py-2 rounded">Rename</button>
<button (click)="cancelRename()" class="bg-gray-500 text-white px-4 py-2 rounded">Cancel</button>
</div>
</div> -->
<!-- Statt der alten Popover-Divs -->
<!-- <app-popover [visible]="showDeletePopover" title="Delete Deck" message="Are you sure you want to delete this deck?" confirmText="Delete" (confirmed)="confirmDelete()" (canceled)="cancelDelete()"></app-popover>
<app-popover
[visible]="showRenamePopover"
title="Rename Deck"
[showInput]="true"
[inputValue]="deckToRename?.name || ''"
confirmText="Rename"
(confirmed)="confirmRename($event)"
(canceled)="cancelRename()"
></app-popover>
<app-popover
[visible]="showDeleteImagePopover"
title="Delete Image"
message="Are you sure you want to delete this image?"
confirmText="Delete"
(confirmed)="confirmImageDelete()"
(canceled)="cancelImageDelete()"
></app-popover> -->

View File

@@ -1,48 +1,61 @@
// src/app/deck-list.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { DeckService, Deck, DeckImage } from './deck.service';
import { CommonModule } from '@angular/common';
import { CreateDeckModalComponent } from './create-deck-modal/create-deck-modal.component';
import { TrainingComponent } from './training/training.component';
import { UploadImageModalComponent } from './upload-image-modal/upload-image-modal.component';
import { EditImageModalComponent } from './edit-image-modal/edit-image-modal.component';
import { HttpClient } from '@angular/common/http';
import { ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { firstValueFrom } from 'rxjs';
import { CreateDeckModalComponent } from './create-deck-modal/create-deck-modal.component';
import { Box, Deck, DeckImage, DeckService, OcrResult } from './deck.service';
import { EditImageModalComponent } from './edit-image-modal/edit-image-modal.component';
import { MoveImageModalComponent } from './move-image-modal/move-image-modal.component';
import { PopoverService } from './services/popover.service';
import { TrainingComponent } from './training/training.component';
@Component({
selector: 'app-deck-list',
templateUrl: './deck-list.component.html',
standalone: true,
styles: `
.popover {
padding: 1rem;
border: 1px solid #ccc;
border-radius: 0.5rem;
background-color: white;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 300px;
}
`,
imports: [
CommonModule,
CreateDeckModalComponent,
UploadImageModalComponent,
TrainingComponent,
EditImageModalComponent,
MoveImageModalComponent, // Hinzufügen der neuen Komponente
UploadImageModalComponent
]
MoveImageModalComponent, // Adding the new component
FormsModule,
],
})
export class DeckListComponent implements OnInit {
decks: Deck[] = [];
selectedDeck: Deck | null = null;
trainingsDeck: Deck | null = null;
activeDeck: Deck | null = null;
loading: boolean = false;
@ViewChild(CreateDeckModalComponent) createDeckModal!: CreateDeckModalComponent;
@ViewChild(UploadImageModalComponent) uploadImageModal!: UploadImageModalComponent;
@ViewChild(CreateDeckModalComponent)
createDeckModal!: CreateDeckModalComponent;
@ViewChild(EditImageModalComponent) editModal!: EditImageModalComponent;
@ViewChild(UploadImageModalComponent) uploadModal!: UploadImageModalComponent;
@ViewChild('imageFile') imageFileElement!: ElementRef;
imageData: { imageSrc: string | ArrayBuffer | null, deckImage: DeckImage } | null = null;
imageData: {
imageSrc: string | ArrayBuffer | null;
deckImage: DeckImage;
} | null = null;
currentUploadDeckName: string = '';
// Set zur Verfolgung erweiterter Decks
// Set to track expanded decks
expandedDecks: Set<string> = new Set<string>();
// State für das Verschieben von Bildern
imageToMove: { image: DeckImage, sourceDeck: Deck } | null = null;
// State for moving images
imageToMove: { image: DeckImage; sourceDeck: Deck } | null = null;
constructor(private deckService: DeckService) { }
constructor(private deckService: DeckService, private cdr: ChangeDetectorRef, private http: HttpClient, private popoverService: PopoverService) {}
ngOnInit(): void {
this.loadExpandedDecks();
@@ -51,92 +64,151 @@ export class DeckListComponent implements OnInit {
loadDecks(): void {
this.deckService.getDecks().subscribe({
next: (data) => this.decks = data,
error: (err) => console.error('Fehler beim Laden der Decks', err)
next: data => {
this.decks = data;
// Set the first deck as active if none is selected
if (!this.activeDeck && this.decks.length > 0) {
this.activeDeck = this.decks[0];
}
if (this.decks.length === 0) {
this.activeDeck = null;
}
},
error: err => console.error('Error loading decks', err),
});
}
deleteDeck(deckName: string): void {
if (!confirm(`Bist du sicher, dass du das Deck "${deckName}" löschen möchtest?`)) {
return;
}
// Updated toggle method
toggleDeckExpansion(deck: Deck): void {
this.activeDeck = deck;
}
// Method to open the delete confirmation popover
openDeletePopover(deckName: string): void {
this.popoverService.show({
title: 'Delete Deck',
message: 'Are you sure you want to delete this deck?',
confirmText: 'Delete',
onConfirm: () => this.confirmDelete(deckName),
});
}
// Method to check if a deck is active
isDeckActive(deck: Deck): boolean {
return this.activeDeck?.name === deck.name;
}
// Method to confirm the deletion of a deck
confirmDelete(deckName: string): void {
this.deckService.deleteDeck(deckName).subscribe({
next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Decks', err)
next: () => {
this.loadDecks();
this.activeDeck = this.decks.length > 0 ? this.decks[0] : null;
},
error: err => console.error('Error deleting deck', err),
});
}
deleteImage(deck: Deck, image: DeckImage): void {
if (!confirm(`Bist du sicher, dass du das Bild "${image.name}" löschen möchtest?`)) {
return;
}
// Method to open the rename popover
openRenamePopover(deck: Deck): void {
this.popoverService.showWithInput({
title: 'Rename Deck',
message: 'Enter the new name for the deck:',
confirmText: 'Rename',
inputValue: deck.name,
onConfirm: (inputValue?: string) => this.confirmRename(deck, inputValue),
});
}
const imageId = image.id;
// Method to confirm the renaming of a deck
confirmRename(deck: Deck, newName?: string): void {
if (newName && newName.trim() !== '' && newName !== deck.name) {
this.deckService.renameDeck(deck.name, newName).subscribe({
next: () => {
if (this.activeDeck?.name === deck.name) {
this.activeDeck.name = newName;
}
this.loadDecks();
},
error: err => console.error('Error renaming deck', err),
});
} else {
// Optional: Handle ungültigen neuen Namen
console.warn('Invalid new deck name.');
}
}
// Delete-Image Methoden ersetzen
deleteImage(deck: Deck, image: DeckImage): void {
this.popoverService.show({
title: 'Delete Image',
message: `Are you sure you want to delete the image ${image.name}?`,
confirmText: 'Delete',
showCancel: true,
onConfirm: () => this.confirmImageDelete(deck, image),
});
}
confirmImageDelete(deck: Deck, image: DeckImage): void {
const imageId = image.bildid;
this.deckService.deleteImage(imageId).subscribe({
next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Bildes', err)
next: () => {
this.loadDecks();
if (this.activeDeck) {
this.activeDeck.images = this.activeDeck.images.filter(img => img.bildid !== imageId);
this.cdr.detectChanges();
}
},
error: err => console.error('Error deleting image', err),
});
}
// Method to edit an image in a deck
editImage(deck: Deck, image: DeckImage): void {
let imageSrc = null
this.currentUploadDeckName = deck.name;
fetch(`/api/debug_image/${image.id}/original_compressed.jpg`)
.then(response => {
if (!response.ok) {
throw new Error('Netzwerkantwort war nicht ok');
}
return response.blob();
})
.then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
imageSrc = reader.result; // Base64-String
this.imageData = { imageSrc, deckImage: image }
};
reader.readAsDataURL(blob);
})
.catch(error => {
console.error('Fehler beim Laden des Bildes:', error);
});
}
openTraining(deck: Deck): void {
this.selectedDeck = deck;
let imageSrc = null;
fetch(`/debug_images/${image.bildid}/original_compressed.jpg`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob();
})
.then(blob => {
const reader = new FileReader();
reader.onloadend = () => {
imageSrc = reader.result; // Base64 string
this.imageData = { imageSrc, deckImage: image };
};
reader.readAsDataURL(blob);
})
.catch(error => {
console.error('Error loading image:', error);
});
}
// Method to open the training component
openTraining(deck: Deck): void {
this.trainingsDeck = deck;
}
// Method to close the training component
closeTraining(): void {
this.selectedDeck = null;
this.trainingsDeck = null;
this.loadDecks();
}
// Method to open the create deck modal
openCreateDeckModal(): void {
this.createDeckModal.open();
}
openUploadImageModal(deckName: string): void {
this.currentUploadDeckName = deckName;
this.uploadImageModal.deckName = deckName;
this.uploadImageModal.open();
}
// Methode zum Umschalten der Deck-Erweiterung
toggleDeckExpansion(deckName: string): void {
if (this.expandedDecks.has(deckName)) {
this.expandedDecks.delete(deckName);
} else {
this.expandedDecks.add(deckName);
}
this.saveExpandedDecks();
}
// Methode zur Überprüfung, ob ein Deck erweitert ist
// Method to check if a deck is expanded
isDeckExpanded(deckName: string): boolean {
return this.expandedDecks.has(deckName);
}
// Laden der erweiterten Decks aus dem sessionStorage
// Method to load expanded decks from sessionStorage
loadExpandedDecks(): void {
const stored = sessionStorage.getItem('expandedDecks');
if (stored) {
@@ -144,48 +216,177 @@ export class DeckListComponent implements OnInit {
const parsed: string[] = JSON.parse(stored);
this.expandedDecks = new Set<string>(parsed);
} catch (e) {
console.error('Fehler beim Parsen der erweiterten Decks aus sessionStorage', e);
console.error('Error parsing expanded decks from sessionStorage', e);
}
} else {
// Wenn keine Daten gespeichert sind, alle Decks standardmäßig nicht erweitern
// If no data is stored, do not expand any decks by default
this.expandedDecks = new Set<string>();
}
}
// Speichern der erweiterten Decks in das sessionStorage
// Method to save expanded decks to sessionStorage
saveExpandedDecks(): void {
const expandedArray = Array.from(this.expandedDecks);
sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray));
}
// Funktion zum Öffnen des Upload Modals (kann durch einen Button ausgelöst werden)
openUploadModal(): void {
this.uploadImageModal.open();
}
// Handler für das imageUploaded Event
// Handler for the imageUploaded event
onImageUploaded(imageData: any): void {
this.imageData = imageData;
}
onClosed(){
onClosed() {
this.imageData = null;
}
async onImageSaved() {
// Handle das Speichern der Bilddaten, z.B. aktualisiere die Liste der Bilder
// Handle saving the image data, e.g., update the list of images
this.imageData = null;
this.decks = await firstValueFrom(this.deckService.getDecks())
// Lade die Decks neu
this.decks = await firstValueFrom(this.deckService.getDecks());
// Aktualisiere den activeDeck, falls dieser der aktuelle Deck ist
if (this.activeDeck) {
const updatedDeck = this.decks.find(deck => deck.name === this.activeDeck?.name);
if (updatedDeck) {
this.activeDeck = updatedDeck;
}
}
}
// Methode zum Öffnen des MoveImageModal
// Method to open the MoveImageModal
openMoveImageModal(deck: Deck, image: DeckImage): void {
this.imageToMove = { image, sourceDeck: deck };
}
// Handler für das moveCompleted Event
// Handler for the moveCompleted event
onImageMoved(): void {
this.imageToMove = null;
this.loadDecks();
// Speichere den Namen des aktiven Decks
const activeDeckName = this.activeDeck?.name;
this.deckService.getDecks().subscribe({
next: decks => {
this.decks = decks;
// Aktualisiere den activeDeck mit den neuen Daten
if (activeDeckName) {
this.activeDeck = this.decks.find(deck => deck.name === activeDeckName) || null;
}
// Force change detection
this.cdr.detectChanges();
},
error: err => console.error('Error loading decks', err),
});
}
onFileChange(event: any): void {
const file: File = event.target.files[0];
if (!file) return;
// Erlaubte Dateitypen
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
// Prüfe den Dateityp
if (!allowedTypes.includes(file.type)) {
this.popoverService.show({
title: 'Information',
message: 'Only JPG, PNG, GIF and WebP images are allowed',
});
this.resetFileInput();
return;
}
// Prüfe die Dateigröße (5MB = 5 * 1024 * 1024 Bytes)
const maxSize = 5 * 1024 * 1024; // 5MB in Bytes
if (file.size > maxSize) {
this.popoverService.show({
title: 'Information',
message: 'Image file size must not exceed 5MB',
});
this.resetFileInput();
return;
}
const fileNameElement = document.getElementById('fileName');
if (fileNameElement) {
fileNameElement.textContent = file.name;
}
this.loading = true;
const reader = new FileReader();
reader.onload = async e => {
const imageSrc = e.target?.result;
// Image as Base64 string without prefix (data:image/...)
const imageBase64 = (imageSrc as string).split(',')[1];
try {
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
if (!response || !response.results) {
this.loading = false;
return;
}
this.loading = false;
// Emit event with image data and OCR results
const imageName = file?.name ?? '';
const imageId = response.results.length > 0 ? response.results[0].name : null;
const boxes: Box[] = [];
response.results.forEach((result: OcrResult) => {
const box = result.box;
const xs = box.map((point: number[]) => point[0]);
const ys = box.map((point: number[]) => point[1]);
const xMin = Math.min(...xs);
const xMax = Math.max(...xs);
const yMin = Math.min(...ys);
const yMax = Math.max(...ys);
boxes.push({ x1: xMin, x2: xMax, y1: yMin, y2: yMax, inserted: null, updated: null });
});
const deckImage: DeckImage = { name: imageName, bildid: imageId, boxes };
this.imageData = { imageSrc, deckImage };
this.resetFileInput();
} catch (error) {
console.error('Error with OCR service:', error);
this.loading = false;
}
};
reader.readAsDataURL(file);
}
/**
* Resets the file input field so the same file can be selected again.
*/
resetFileInput(): void {
if (this.imageFileElement && this.imageFileElement.nativeElement) {
this.imageFileElement.nativeElement.value = '';
}
}
// Methode zur Berechnung des nächsten Trainingsdatums
getNextTrainingDate(deck: Deck): Date {
const now = new Date();
now.setHours(0, 0, 0, 0);
const dueDates = deck.images.flatMap(image => image.boxes.map(box => (box.due ? new Date(box.due * 86400000) : null)));
const futureDueDates = dueDates.filter(date => date && date >= now);
if (futureDueDates.length > 0) {
const nextDate = futureDueDates.reduce((a, b) => (a < b ? a : b));
return nextDate;
}
return now;
}
getNextTrainingString(deck: Deck): string {
return this.getNextTrainingDate(deck).toLocaleDateString();
}
// Methode zur Berechnung der Anzahl der zu bearbeitenden Wörter
getWordsToReview(deck: Deck): number {
const nextTraining = this.getNextTrainingDate(deck);
return deck.images.flatMap(image => image.boxes.filter(box => (box.due && new Date(box.due * 86400000) <= new Date(nextTraining)) || !box.due)).length;
}
}

View File

@@ -1,7 +1,6 @@
// src/app/deck.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, Observable, switchMap } from 'rxjs';
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
export interface Deck {
name: string;
@@ -11,27 +10,28 @@ export interface Deck {
export interface DeckImage {
boxes: Box[];
name: string;
id:string;
bildid: string;
}
export interface Box {
id?:number;
x1:number;
x2:number;
y1:number;
y2:number;
id?: number;
x1: number;
x2: number;
y1: number;
y2: number;
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?:boolean;
isGraduated?: boolean;
inserted: string;
updated: string;
}
export interface BackendBox {
bildname: string;
deckid: number;
iconindex: number;
id: number;
x1: number;
x2: number;
@@ -39,13 +39,13 @@ export interface BackendBox {
y2: number;
}
// Definiert ein einzelnes Punktpaar [x, y]
// Defines a single point pair [x, y]
type OcrPoint = [number, number];
// Definiert die Box als Array von vier Punkten
// Defines the box as an array of four points
type OcrBox = [OcrPoint, OcrPoint, OcrPoint, OcrPoint];
// Interface für jedes JSON-Objekt
// Interface for each JSON object
export interface OcrResult {
box: OcrBox;
confidence: number;
@@ -54,50 +54,56 @@ export interface OcrResult {
}
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class DeckService {
private apiUrl = '/api/decks';
constructor(private http: HttpClient) { }
constructor(private http: HttpClient) {}
getDecks(): Observable<Deck[]> {
return this.http.get<any[]>(this.apiUrl).pipe(
map(decks => decks.map(deck => ({
name: deck.name,
images: this.groupImagesByName(deck.images)
})))
map(decks =>
decks.map(deck => ({
name: deck.name,
images: this.groupImagesByName(deck.images),
})),
),
);
}
private groupImagesByName(images: any[]): DeckImage[] {
const imageMap: { [key: string]: DeckImage } = {};
images.forEach(image => {
if (!imageMap[image.id]) {
imageMap[image.id] = {
if (!imageMap[image.bildid]) {
imageMap[image.bildid] = {
name: image.name,
id:image.id,
boxes: []
bildid: image.bildid,
boxes: [],
};
}
imageMap[image.id].boxes.push({
id: image.boxid,
imageMap[image.bildid].boxes.push({
id: image.id,
x1: image.x1,
x2: image.x2,
y1: image.y1,
y2: image.y2,
due: image.due,
ivl:image.ivl,
factor:image.factor,
reps:image.reps,
lapses:image.lapses,
isGraduated:image.isGraduated?true:false
ivl: image.ivl,
factor: image.factor,
reps: image.reps,
lapses: image.lapses,
isGraduated: image.isGraduated ? true : false,
inserted: image.inserted,
updated: image.updated,
});
});
return Object.values(imageMap);
}
getDeck(deckname:string): Observable<Deck> {
getDeck(deckname: string): Observable<Deck> {
return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`);
}
@@ -108,17 +114,19 @@ export class DeckService {
deleteDeck(deckName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/${encodeURIComponent(deckName)}`);
}
saveImageData(data:any): Observable<any> {
renameDeck(oldDeckName: string, newDeckName: string): Observable<any> {
return this.http.put(`${this.apiUrl}/${encodeURIComponent(oldDeckName)}/rename`, { newDeckName });
}
saveImageData(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/image`, data);
}
// Neue Methode zum Löschen eines Bildes
// New method to delete an image
deleteImage(imageName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/image/${imageName}`);
}
// Neue Methode zum Verschieben eines Bildes
// New method to move an image
moveImage(imageId: string, targetDeckId: number): Observable<any> {
return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId });
}

View File

@@ -1,4 +1,3 @@
<!-- src/app/edit-image-modal.component.html -->
<div #editImageModal id="editImageModal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full">
<div class="relative h-full contents">
<div class="relative bg-white rounded-lg shadow">
@@ -6,12 +5,12 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
<span class="sr-only">Schließen</span>
<span class="sr-only">Close</span>
</button>
<div class="p-6 relative">
<!-- Überschrift mit Boxanzahl -->
<!-- Header with box count -->
<h3 class="mb-4 text-xl font-medium text-gray-900">
Bild bearbeiten <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'en' : '' }})</span>
Edit Image <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'es' : '' }})</span>
</h3>
<!-- Canvas -->
@@ -19,16 +18,16 @@
<canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas>
</div>
<!-- Buttons unter dem Canvas -->
<!-- Buttons below the canvas -->
<div class="mt-4 flex justify-between">
<button (click)="save()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Save
</button>
<button (click)="addNewBox()" class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Neue Box
New Box
</button>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@@ -1,29 +1,30 @@
// src/app/edit-image-modal.component.ts
import { Component, Input, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnDestroy, Output, ViewChild } from '@angular/core';
import { fabric } from 'fabric';
import { Modal } from 'flowbite';
import { DeckImage, DeckService, OcrResult } from '../deck.service';
import { DeckImage, DeckService } from '../deck.service';
import { PopoverService } from '../services/popover.service';
@Component({
selector: 'app-edit-image-modal',
templateUrl: './edit-image-modal.component.html',
standalone: true,
imports: [CommonModule]
imports: [CommonModule],
})
export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// Konstante für die Boxfarbe
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Rot mit Transparenz
// Constant for box color
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Red with transparency
@Input() deckName: string = '';
@Input() imageData : {imageSrc:string|ArrayBuffer|null, deckImage:DeckImage|null} = {imageSrc:null,deckImage:null};
@Input() imageData: { imageSrc: string | ArrayBuffer | null; deckImage: DeckImage | null } = { imageSrc: null, deckImage: null };
@Output() imageSaved = new EventEmitter<void>();
@Output() closed = new EventEmitter<void>();
@ViewChild('editImageModal') modalElement!: ElementRef;
@ViewChild('canvas') canvasElement!: ElementRef<HTMLCanvasElement>;
detectedText: string = '';
boxes: { x1: number; x2: number; y1: number; y2: number }[] = [];
boxes: { x1: number; x2: number; y1: number; y2: number; id: number; inserted: string; updated: string }[] = [];
canvas!: fabric.Canvas;
maxCanvasWidth: number = 0;
@@ -32,14 +33,14 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
private keyDownHandler!: (e: KeyboardEvent) => void;
modal: any;
constructor(private deckService: DeckService) { }
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
async ngAfterViewInit() {
this.modal = new Modal(this.modalElement.nativeElement,{
this.modal = new Modal(this.modalElement.nativeElement, {
onHide: () => {
this.closed.emit();
}},
);
},
});
this.maxCanvasWidth = window.innerWidth * 0.6;
this.maxCanvasHeight = window.innerHeight * 0.6;
@@ -75,27 +76,27 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
return new Promise((resolve, reject) => {
fabric.Image.fromURL(
url,
(img) => {
img => {
resolve(img);
},
{
crossOrigin: 'anonymous',
originX: 'left',
originY: 'top',
}
},
);
});
}
async processImage(): Promise<void> {
try {
if (!this.imageData){
if (!this.imageData) {
return;
}
this.canvas = new fabric.Canvas(this.canvasElement.nativeElement);
// Hintergrundbild setzen
// Set background image
const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string);
const originalWidth = backgroundImage.width!;
@@ -120,19 +121,19 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.boxes = [];
// Boxen hinzufügen
// Add boxes
this.imageData.deckImage?.boxes.forEach(box => {
const rect = new fabric.Rect({
left: box.x1 * scaleFactor,
top: box.y1 * scaleFactor,
width: (box.x2 - box.x1) * scaleFactor,
height: (box.y2 - box.y1) * scaleFactor,
fill: this.BOX_COLOR, // Verwendung der Konstante
fill: this.BOX_COLOR, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
objectCaching: false,
data: { id: box.id, inserted: box.inserted, updated: box.updated },
});
rect.on('modified', () => {
@@ -155,11 +156,9 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
});
this.updateBoxCoordinates();
// this.detectedText = ocrResults.map(result => result.text).join('\n');
} catch (error) {
console.error('Fehler bei der Bildverarbeitung:', error);
console.error('Error processing image:', error);
}
}
@@ -198,7 +197,10 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
x1: Math.round(x1),
x2: Math.round(x2),
y1: Math.round(y1),
y2: Math.round(y2)
y2: Math.round(y2),
id: rect.data?.id,
inserted: rect.data?.inserted,
updated: rect.data?.updated,
});
});
@@ -221,13 +223,12 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
top: (canvasHeight - boxHeight) / 2,
width: boxWidth,
height: boxHeight,
fill: this.BOX_COLOR, // Verwendung der Konstante
fill: this.BOX_COLOR, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
objectCaching: false,
});
rect.on('modified', () => {
this.updateBoxCoordinates();
});
@@ -252,12 +253,12 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
}
save(): void {
// Hier implementierst du die Logik zum Speichern der Bilddaten
// Zum Beispiel über einen Service oder direkt hier
// Implement the logic to save the image data here
// For example, via a service or directly here
const data = {
deckname: this.deckName,
bildname: this.imageData.deckImage?.name, // this.imageFile?.name,
bildid: this.imageData.deckImage?.id,
bildid: this.imageData.deckImage?.bildid,
boxes: this.boxes,
};
this.deckService.saveImageData(data).subscribe({
@@ -265,11 +266,14 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.imageSaved.emit();
this.closeModal();
},
error: (err) => {
console.error('Fehler beim Speichern des Bildes:', err);
alert('Fehler beim Speichern des Bildes.');
error: err => {
console.error('Error saving image:', err);
this.popoverService.show({
title: 'Error',
message: 'Error saving image.',
});
this.closeModal();
}
},
});
}
}

View File

@@ -0,0 +1,12 @@
export const environment = {
production: true,
firebase: {
apiKey: 'AIzaSyBBH7mGJtwY-6_x0kCmyWCGe6JCesRS49k',
authDomain: 'haiki-452bd.firebaseapp.com',
projectId: 'haiki-452bd',
storageBucket: 'haiki-452bd.firebasestorage.app',
messagingSenderId: '263288723576',
appId: '1:263288723576:web:2bc87146ef52d276f5358d',
measurementId: 'G-C1C3N16KB3',
},
};

View File

@@ -0,0 +1,12 @@
export const environment = {
production: false,
firebase: {
apiKey: 'AIzaSyBBH7mGJtwY-6_x0kCmyWCGe6JCesRS49k',
authDomain: 'haiki-452bd.firebaseapp.com',
projectId: 'haiki-452bd',
storageBucket: 'haiki-452bd.firebasestorage.app',
messagingSenderId: '263288723576',
appId: '1:263288723576:web:2bc87146ef52d276f5358d',
measurementId: 'G-C1C3N16KB3',
},
};

View File

@@ -1,24 +1,22 @@
<!-- src/app/move-image-modal.component.html -->
<div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
<div class="bg-white rounded-lg shadow-lg w-96 p-6">
<h2 class="text-xl font-semibold mb-4">Bild verschieben</h2>
<p class="mb-4">Wähle das Zieldeck für das Bild <strong>{{ image.name }}</strong> aus.</p>
<select [(ngModel)]="selectedDeckId" class="w-full p-2 border border-gray-300 rounded mb-4">
<option *ngFor="let deck of decks" [value]="deck.name" [disabled]="deck.name === sourceDeck.name">
{{ deck.name }}
</option>
</select>
<div class="flex justify-end space-x-2">
<button (click)="close()" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600">
Abbrechen
</button>
<button
(click)="moveImage()"
[disabled]="!selectedDeckId"
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
Verschieben
</button>
</div>
<div class="bg-white rounded-lg shadow-lg w-96 p-6">
<h2 class="text-xl font-semibold mb-4">Move Image</h2>
<p class="mb-4">Select the target deck for the image <strong>{{ image.name }}</strong>.</p>
<select [(ngModel)]="selectedDeckId" class="w-full p-2 border border-gray-300 rounded mb-4">
<option *ngFor="let deck of decks" [value]="deck.name" [disabled]="deck.name === sourceDeck.name">
{{ deck.name }}
</option>
</select>
<div class="flex justify-end space-x-2">
<button (click)="close()" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600">
Cancel
</button>
<button
(click)="moveImage()"
[disabled]="!selectedDeckId"
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
Move
</button>
</div>
</div>
</div>

View File

@@ -1,15 +1,14 @@
// src/app/move-image-modal.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DeckImage, Deck, DeckService } from '../deck.service';
import { Deck, DeckImage, DeckService } from '../deck.service';
import { PopoverService } from '../services/popover.service';
@Component({
selector: 'app-move-image-modal',
templateUrl: './move-image-modal.component.html',
standalone: true,
imports: [CommonModule, FormsModule]
imports: [CommonModule, FormsModule],
})
export class MoveImageModalComponent {
@Input() image!: DeckImage;
@@ -20,22 +19,25 @@ export class MoveImageModalComponent {
selectedDeckId: number | null = null;
constructor(private deckService: DeckService) { }
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
moveImage(): void {
if (this.selectedDeckId === null) {
return;
}
this.deckService.moveImage(this.image.id, this.selectedDeckId).subscribe({
this.deckService.moveImage(this.image.bildid, this.selectedDeckId).subscribe({
next: () => {
this.moveCompleted.emit();
this.close();
},
error: (err) => {
console.error('Fehler beim Verschieben des Bildes:', err);
alert('Fehler beim Verschieben des Bildes.');
}
error: err => {
console.error('Error moving image:', err);
this.popoverService.show({
title: 'Error',
message: 'Error moving image.',
});
},
});
}

View File

@@ -0,0 +1,73 @@
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Auth } from '@angular/fire/auth';
import { from } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(Auth); // Injizieren Sie den Auth-Dienst
const token = localStorage.getItem('accessToken');
if (token) {
const decodedToken = decodeToken(token);
const expirationTime = decodedToken.exp * 1000; // Umwandeln in Millisekunden
const currentTime = Date.now();
if (currentTime > expirationTime) {
// Token ist abgelaufen, erneuern Sie es
return from(refreshToken(auth)).pipe(
switchMap(newToken => {
const clonedReq = req.clone({
setHeaders: {
Authorization: `Bearer ${newToken}`,
},
});
return next(clonedReq);
}),
catchError(error => {
console.error('Failed to refresh token', error);
return next(req); // Ohne Token fortfahren
}),
);
} else {
// Token ist gültig
const clonedReq = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
return next(clonedReq);
}
} else {
return next(req);
}
};
async function refreshToken(auth: Auth): Promise<string> {
return new Promise((resolve, reject) => {
const unsubscribe = auth.onAuthStateChanged(async user => {
if (user) {
try {
const newToken = await user.getIdToken(true); // Token erneuern
localStorage.setItem('accessToken', newToken);
resolve(newToken);
} catch (error) {
console.error('Failed to refresh token', error);
reject(error);
}
} else {
reject(new Error('No authenticated user found'));
}
unsubscribe(); // Abonnement beenden
});
});
}
function decodeToken(token: string): any {
try {
return JSON.parse(atob(token.split('.')[1]));
} catch (e) {
console.error('Error decoding token', e);
return null;
}
}

View File

@@ -0,0 +1,19 @@
import { Directive, ElementRef, EventEmitter, HostListener, Output } from '@angular/core';
@Directive({
selector: '[appClickOutside]',
standalone: true,
})
export class ClickOutsideDirective {
@Output() clickOutside = new EventEmitter<void>();
constructor(private elementRef: ElementRef) {}
@HostListener('document:click', ['$event.target'])
onClick(target: HTMLElement) {
const clickedInside = this.elementRef.nativeElement.contains(target);
if (!clickedInside) {
this.clickOutside.emit();
}
}
}

View File

@@ -0,0 +1,38 @@
// popover.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class PopoverService {
private showPopoverSource = new Subject<{
title: string;
message: string;
showInput: boolean;
showCancel: boolean;
inputValue: string;
confirmText: string;
onConfirm: () => void;
onCancel?: () => void;
}>();
popoverState$ = this.showPopoverSource.asObservable();
show(options: { title: string; message: string; confirmText?: string; showCancel?: boolean; onConfirm?: (inputValue?: string) => void; onCancel?: () => void }) {
this.showPopoverSource.next({
showInput: false,
inputValue: null,
confirmText: 'Ok',
showCancel: false,
onConfirm: (inputValue?: string) => {},
...options,
});
}
showWithInput(options: { title: string; message: string; confirmText: string; inputValue: string; onConfirm: (inputValue?: string) => void; onCancel?: () => void }) {
this.showPopoverSource.next({
showInput: true,
showCancel: true,
...options,
});
}
}

View File

@@ -1,53 +1,52 @@
<!-- src/app/training.component.html -->
<div class="mt-10">
<h2 class="text-2xl font-bold mb-4">Training: {{ deck.name }}</h2>
<div class="bg-white shadow rounded-lg p-6 flex flex-col items-center">
<canvas #canvas class="mb-4 border max-h-[50vh]"></canvas>
<div class="flex space-x-4 mb-4">
<!-- Anzeigen Button -->
<!-- Show Button -->
<button
(click)="showText()"
class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600"
[disabled]="isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Anzeigen
Show
</button>
<!-- Nochmal Button -->
<!-- Again Button -->
<button
(click)="markAgain()"
class="bg-orange-500 disabled:bg-orange-200 text-white py-2 px-4 rounded hover:bg-orange-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Nochmal ({{ getNextInterval(currentBox, 'again') }})
Again ({{ getNextInterval(currentBox, 'again') }})
</button>
<!-- Gut Button -->
<!-- Good Button -->
<button
(click)="markGood()"
class="bg-blue-500 disabled:bg-blue-200 text-white py-2 px-4 rounded hover:bg-blue-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Gut ({{ getNextInterval(currentBox, 'good') }})
Good ({{ getNextInterval(currentBox, 'good') }})
</button>
<!-- Einfach Button -->
<!-- Easy Button -->
<button
(click)="markEasy()"
class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
>
Einfach ({{ getNextInterval(currentBox, 'easy') }})
Easy ({{ getNextInterval(currentBox, 'easy') }})
</button>
<!-- Nächstes Bild Button -->
<!-- Next Image Button -->
<button
(click)="skipToNextImage()"
class="bg-yellow-500 disabled:bg-yellow-200 text-white py-2 px-4 rounded hover:bg-yellow-600"
[disabled]="currentImageIndex >= deck.images.length"
>
Nächstes Bild
Next Image
</button>
</div>
@@ -57,7 +56,7 @@
(click)="closeTraining()"
class="mt-4 text-gray-500 hover:text-gray-700 underline"
>
Training beenden
End Training
</button>
</div>
</div>
</div>

View File

@@ -1,33 +1,33 @@
// training.component.ts
import { Component, Input, Output, EventEmitter, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Deck, DeckImage, DeckService, Box } from '../deck.service';
import { CommonModule } from '@angular/common';
import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { lastValueFrom } from 'rxjs';
import { Box, Deck, DeckImage, DeckService } from '../deck.service';
import { PopoverService } from '../services/popover.service';
const LEARNING_STEPS = {
AGAIN: 1, // 1 minute
GOOD: 10, // 10 minutes
GRADUATION: 1440 // 1 day (in minutes)
AGAIN: 1, // 1 minute
GOOD: 10, // 10 minutes
GRADUATION: 1440, // 1 day (in minutes)
};
const FACTOR_CHANGES = {
AGAIN: 0.85, // Reduce factor by 15%
EASY: 1.15, // Increase factor by 15%
MIN: 1.3, // Minimum factor allowed
MAX: 2.9 // Maximum factor allowed
AGAIN: 0.85, // Reduce factor by 15%
EASY: 1.15, // Increase factor by 15%
MIN: 1.3, // Minimum factor allowed
MAX: 2.9, // Maximum factor allowed
};
const EASY_INTERVAL = 4 * 1440; // 4 days in minutes
@Component({
selector: 'app-training',
templateUrl: './training.component.html',
standalone: true,
imports: [CommonModule]
imports: [CommonModule],
})
export class TrainingComponent implements OnInit {
@Input() deck!: Deck;
@Output() close = new EventEmitter<void>();
@ViewChild('canvas',{static : false}) canvasRef!: ElementRef<HTMLCanvasElement>;
@ViewChild('canvas', { static: false }) canvasRef!: ElementRef<HTMLCanvasElement>;
currentImageIndex: number = 0;
currentImageData: DeckImage | null = null;
@@ -38,25 +38,28 @@ export class TrainingComponent implements OnInit {
isShowingBox: boolean = false;
isTrainingFinished: boolean = false;
constructor(private deckService: DeckService) { }
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
ngOnInit(): void {
// Initialisierung wurde in ngAfterViewInit durchgeführt
// Initialization was done in ngAfterViewInit
}
ngAfterViewInit(){
// Initialisiere das erste Bild und die dazugehörigen Boxen
ngAfterViewInit() {
// Initialize the first image and its boxes
if (this.deck && this.deck.images.length > 0) {
this.loadImage(this.currentImageIndex);
} else {
alert('Kein Deck oder keine Bilder vorhanden.');
this.popoverService.show({
title: 'Information',
message: 'No deck or images available.',
});
this.close.emit();
}
}
/**
* Lädt das Bild basierend auf dem gegebenen Index und initialisiert die zu überprüfenden Boxen.
* @param imageIndex Index des zu ladenden Bildes im Deck
* Loads the image based on the given index and initializes the boxes to review.
* @param imageIndex Index of the image to load in the deck
*/
loadImage(imageIndex: number): void {
if (imageIndex >= this.deck.images.length) {
@@ -65,13 +68,13 @@ export class TrainingComponent implements OnInit {
}
this.currentImageData = this.deck.images[imageIndex];
// Initialisiere die Boxen für die aktuelle Runde
// Initialize the boxes for the current round
this.initializeBoxesToReview();
}
/**
* Ermittelt alle fälligen Boxen für die aktuelle Runde, mischt sie und setzt den aktuellen Box-Index zurück.
* Wenn keine Boxen mehr zu überprüfen sind, wird zum nächsten Bild gewechselt.
* Determines all due boxes for the current round, shuffles them, and resets the current box index.
* If no boxes are left to review, it moves to the next image.
*/
initializeBoxesToReview(): void {
if (!this.currentImageData) {
@@ -79,42 +82,42 @@ export class TrainingComponent implements OnInit {
return;
}
// Filtere alle Boxen, die fällig sind (due <= heute)
// Filter all boxes that are due (due <= today)
const today = this.getTodayInDays();
this.boxesToReview = this.currentImageData.boxes.filter(box => box.due === undefined || box.due <= today);
if (this.boxesToReview.length === 0) {
// Keine Boxen mehr für dieses Bild, wechsle zum nächsten Bild
// No more boxes for this image, move to the next image
this.nextImage();
return;
}
// Mische die Boxen zufällig
// Shuffle the boxes randomly
this.boxesToReview = this.shuffleArray(this.boxesToReview);
// Initialisiere den Array zur Verfolgung der enthüllten Boxen
// Initialize the array to track revealed boxes
this.boxRevealed = new Array(this.boxesToReview.length).fill(false);
// Setze den aktuellen Box-Index zurück
// Reset the current box index
this.currentBoxIndex = 0;
this.isShowingBox = false;
// Zeichne das Canvas neu
// Redraw the canvas
this.drawCanvas();
}
/**
* Gibt das heutige Datum in Tagen seit der UNIX-Epoche zurück.
* Returns today's date in days since the UNIX epoch.
*/
getTodayInDays(): number {
const epoch = new Date(1970, 0, 1); // Anki verwendet UNIX-Epoche
const epoch = new Date(1970, 0, 1); // Anki uses UNIX epoch
const today = new Date();
return Math.floor((today.getTime() - epoch.getTime()) / (1000 * 60 * 60 * 24));
}
/**
* Zeichnet das aktuelle Bild und die Boxen auf das Canvas.
* Boxen werden rot dargestellt, wenn sie verdeckt sind, und grün, wenn sie enthüllt sind.
* Draws the current image and boxes on the canvas.
* Boxes are displayed in red if hidden and green if revealed.
*/
drawCanvas(): void {
const canvas = this.canvasRef.nativeElement;
@@ -122,29 +125,29 @@ export class TrainingComponent implements OnInit {
if (!ctx || !this.currentImageData) return;
const img = new Image();
img.src = `/api/debug_image/${this.currentImageData.id}/original_compressed.jpg`;
img.src = `/debug_images/${this.currentImageData.bildid}/original_compressed.jpg`;
img.onload = () => {
// Setze die Größe des Canvas auf die Größe des Bildes
// Set the canvas size to the image size
canvas.width = img.width;
canvas.height = img.height;
// Zeichne das Bild
// Draw the image
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Zeichne die Boxen
// Draw the boxes
this.boxesToReview.forEach((box, index) => {
ctx.beginPath();
ctx.rect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1);
if (this.currentBoxIndex === index && this.isShowingBox || (box.due && box.due-this.getTodayInDays()>0)) {
// Box ist aktuell enthüllt, keine Überlagerung
if ((this.currentBoxIndex === index && this.isShowingBox) || (box.due && box.due - this.getTodayInDays() > 0)) {
// Box is currently revealed, no overlay
return;
} else if (this.currentBoxIndex === index && !this.isShowingBox) {
// Box ist enthüllt
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Undurchsichtige grüne Überlagerung
// Box is revealed
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Opaque green overlay
} else {
// Box ist verdeckt
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Undurchsichtige rote Überlagerung
// Box is hidden
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Opaque red overlay
}
ctx.fill();
ctx.lineWidth = 2;
@@ -154,36 +157,39 @@ export class TrainingComponent implements OnInit {
};
img.onerror = () => {
console.error('Fehler beim Laden des Bildes für Canvas.');
alert('Fehler beim Laden des Bildes für Canvas.');
console.error('Error loading image for canvas.');
this.popoverService.show({
title: 'Error',
message: 'Error loading image for canvas.',
});
this.close.emit();
};
}
/**
* Mischt ein Array zufällig.
* @param array Das zu mischende Array
* @returns Das gemischte Array
* Shuffles an array randomly.
* @param array The array to shuffle
* @returns The shuffled array
*/
shuffleArray<T>(array: T[]): T[] {
let currentIndex = array.length, randomIndex;
let currentIndex = array.length,
randomIndex;
// Solange noch Elemente zum Mischen vorhanden sind
// While there are elements to shuffle
while (currentIndex !== 0) {
// Wähle ein verbleibendes Element
// Pick a remaining element
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// Tausche es mit dem aktuellen Element
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
// Swap it with the current element
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
/**
* Gibt die aktuelle Box zurück, die überprüft wird.
* Returns the current box being reviewed.
*/
get currentBox(): Box | null {
if (this.currentBoxIndex < this.boxesToReview.length) {
@@ -193,7 +199,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Zeigt den Inhalt der aktuellen Box an.
* Reveals the content of the current box.
*/
showText(): void {
if (this.currentBoxIndex >= this.boxesToReview.length) return;
@@ -203,7 +209,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Nochmal" und fährt mit der nächsten Box fort.
* Marks the current box as "Again" and proceeds to the next box.
*/
async markAgain(): Promise<void> {
await this.updateCard('again');
@@ -212,7 +218,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Gut" und fährt mit der nächsten Box fort.
* Marks the current box as "Good" and proceeds to the next box.
*/
async markGood(): Promise<void> {
await this.updateCard('good');
@@ -221,7 +227,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Einfach" und fährt mit der nächsten Box fort.
* Marks the current box as "Easy" and proceeds to the next box.
*/
async markEasy(): Promise<void> {
await this.updateCard('easy');
@@ -230,8 +236,8 @@ export class TrainingComponent implements OnInit {
}
/**
* Aktualisiert die SRS-Daten der aktuellen Box basierend auf der gegebenen Aktion.
* @param action Die durchgeführte Aktion ('again', 'good', 'easy')
* Updates the SRS data of the current box based on the given action.
* @param action The action performed ('again', 'good', 'easy')
*/
async updateCard(action: 'again' | 'good' | 'easy'): Promise<void> {
if (this.currentBoxIndex >= this.boxesToReview.length) return;
@@ -239,100 +245,122 @@ export class TrainingComponent implements OnInit {
const box = this.boxesToReview[this.currentBoxIndex];
const today = this.getTodayInDays();
// Berechne das neue Intervall und eventuell den neuen Faktor
// Calculate the new interval and possibly the new factor
const { newIvl, newFactor, newReps, newLapses, newIsGraduated } = this.calculateNewInterval(box, action);
// Aktualisiere das Fälligkeitsdatum
const nextDue = today + Math.floor(newIvl/1440);
// Update the due date
const nextDue = today + Math.floor(newIvl / 1440);
// Aktualisiere das Box-Objekt
// Update the box object
box.ivl = newIvl;
box.factor = newFactor;
box.reps = newReps;
box.lapses = newLapses;
box.due = nextDue;
box.isGraduated = newIsGraduated
box.isGraduated = newIsGraduated;
// Sende das Update an das Backend
// Send the update to the backend
try {
await lastValueFrom(this.deckService.updateBox(box));
} catch (error) {
console.error('Fehler beim Aktualisieren der Box:', error);
alert('Fehler beim Aktualisieren der Box.');
console.error('Error updating box:', error);
this.popoverService.show({
title: 'Error',
message: 'Error updating box.',
});
}
}
/**
* Berechnet das neue Intervall, den Faktor, die Wiederholungen und die Lapses basierend auf der Aktion.
* @param box Die aktuelle Box
* @param action Die Aktion ('again', 'good', 'easy')
* @returns Ein Objekt mit den neuen Werten für ivl, factor, reps und lapses
* Calculates the new interval, factor, repetitions, and lapses based on the action.
* @param box The current box
* @param action The action ('again', 'good', 'easy')
* @returns An object with the new values for ivl, factor, reps, and lapses
*/
calculateNewInterval(box: Box, action: 'again' | 'good' | 'easy'): { newIvl: number, newFactor: number, newReps: number, newLapses: number, newIsGraduated: boolean } {
calculateNewInterval(
box: Box,
action: 'again' | 'good' | 'easy',
): {
newIvl: number;
newFactor: number;
newReps: number;
newLapses: number;
newIsGraduated: boolean;
} {
const LEARNING_STEPS = {
AGAIN: 1, // 1 minute
GOOD: 10, // 10 minutes
GRADUATION: 1440, // 1 day (1440 minutes)
};
const EASY_BONUS = 1.3; // Zusätzlicher Easy-Multiplikator
/* const FACTOR_CHANGES = {
MIN: 1.3,
MAX: 2.5,
AGAIN: 0.85,
EASY: 1.15
}; */
let newIvl = box.ivl || 0;
let newFactor = box.factor || 2.5;
let newReps = box.reps || 0;
let newLapses = box.lapses || 0;
let newIsGraduated = box.isGraduated || false
let newIsGraduated = box.isGraduated || false;
if (action === 'again') {
newLapses++;
newReps = 0;
newIvl = LEARNING_STEPS.AGAIN;
newIsGraduated = false;
// Reduce factor but not below minimum
newFactor = Math.max(
FACTOR_CHANGES.MIN,
newFactor * FACTOR_CHANGES.AGAIN
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
if (action === 'again') {
newLapses++;
newReps = 0;
newIvl = LEARNING_STEPS.AGAIN;
newIsGraduated = false;
newFactor = Math.max(FACTOR_CHANGES.MIN, newFactor * FACTOR_CHANGES.AGAIN);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
if (action === 'easy') {
newReps++;
newReps++;
// Faktor zuerst aktualisieren
const updatedFactor = Math.min(FACTOR_CHANGES.MAX, newFactor * FACTOR_CHANGES.EASY);
if (!newIsGraduated) {
// Direkte Graduierung mit Easy
newIsGraduated = true;
newIvl = EASY_INTERVAL;
// Increase factor but not above maximum
newFactor = Math.min(
FACTOR_CHANGES.MAX,
newFactor * FACTOR_CHANGES.EASY
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };;
newIvl = LEARNING_STEPS.GRADUATION; // 1 Tag (1440 Minuten)
} else {
// Anki-Formel für Easy in der Review-Phase
newIvl = Math.round((newIvl + LEARNING_STEPS.GRADUATION / 2) * updatedFactor * EASY_BONUS);
}
newFactor = updatedFactor;
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
// Handle 'good' action
newReps++;
if (!newIsGraduated) {
// Card is in learning phase
if (newReps === 1) {
newIvl = LEARNING_STEPS.GOOD;
} else {
// Graduate the card
newIsGraduated = true;
newIvl = LEARNING_STEPS.GRADUATION;
}
if (newReps === 1) {
newIvl = LEARNING_STEPS.GOOD; // 10 Minuten
} else {
newIsGraduated = true;
newIvl = LEARNING_STEPS.GRADUATION; // 1 Tag nach zweiter Good-Antwort
}
} else {
// Card is in review phase, apply space repetition
newIvl = Math.round(newIvl * newFactor);
// Standard-SR-Formel
newIvl = Math.round(newIvl * newFactor);
}
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };;
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
/**
* Berechnet das nächste Intervall basierend auf der Aktion und gibt es als String zurück.
* @param box Die aktuelle Box
* @param action Die Aktion ('again', 'good', 'easy')
* @returns Das nächste Intervall als String (z.B. "10 min", "2 d")
* Calculates the next interval based on the action and returns it as a string.
* @param box The current box
* @param action The action ('again', 'good', 'easy')
* @returns The next interval as a string (e.g., "10 min", "2 d")
*/
getNextInterval(box: Box | null, action: 'again' | 'good' | 'easy'): string {
if (!box)
return '';
if (!box) return '';
const { newIvl } = this.calculateNewInterval(box, action);
@@ -340,18 +368,18 @@ export class TrainingComponent implements OnInit {
}
/**
* Formatiert das Intervall als String, entweder in Minuten oder Tagen.
* @param ivl Das Intervall in Tagen
* @returns Das formatierte Intervall als String
* Formats the interval as a string, either in minutes or days.
* @param ivl The interval in days
* @returns The formatted interval as a string
*/
formatInterval(minutes: number): string {
if (minutes < 60) return `${minutes}min`;
if (minutes < 1440) return `${Math.round(minutes/60)}h`;
return `${Math.round(minutes/1440)}d`;
if (minutes < 1440) return `${Math.round(minutes / 60)}h`;
return `${Math.round(minutes / 1440)}d`;
}
/**
* Deckt die aktuelle Box wieder auf (verdeckt sie erneut).
* Covers the current box again (hides it).
*/
coverCurrentBox(): void {
this.boxRevealed[this.currentBoxIndex] = false;
@@ -359,24 +387,24 @@ export class TrainingComponent implements OnInit {
}
/**
* Geht zur nächsten Box. Wenn alle Boxen in der aktuellen Runde bearbeitet wurden,
* wird eine neue Runde gestartet.
* Moves to the next box. If all boxes in the current round have been processed,
* a new round is started.
*/
nextBox(): void {
this.isShowingBox = false;
if (this.currentBoxIndex >= this.boxesToReview.length - 1) {
// Runde abgeschlossen, starte eine neue Runde
// Round completed, start a new round
this.initializeBoxesToReview();
} else {
// Gehe zur nächsten Box
// Move to the next box
this.currentBoxIndex++;
this.drawCanvas();
}
}
/**
* Wechselt zum nächsten Bild im Deck.
* Moves to the next image in the deck.
*/
nextImage(): void {
this.currentImageIndex++;
@@ -384,39 +412,48 @@ export class TrainingComponent implements OnInit {
}
/**
* Überspringt zum nächsten Bild im Deck.
* Skips to the next image in the deck.
*/
skipToNextImage(): void {
if (this.currentImageIndex < this.deck.images.length - 1) {
this.currentImageIndex++;
this.loadImage(this.currentImageIndex);
} else {
alert('Dies ist das letzte Bild im Deck.');
this.popoverService.show({
title: 'Information',
message: 'This is the last image in the deck.',
});
}
}
/**
* Beendet das Training und gibt eine Abschlussmeldung aus.
* Ends the training and displays a completion message.
*/
endTraining(): void {
this.isTrainingFinished = true;
alert(`Training beendet!`);
this.popoverService.show({
title: 'Information',
message: 'Training completed!',
});
this.close.emit();
}
/**
* Fragt den Benutzer, ob das Training beendet werden soll, und schließt es gegebenenfalls.
* Asks the user if they want to end the training and closes it if confirmed.
*/
closeTraining(): void {
if (confirm('Möchtest du das Training wirklich beenden?')) {
this.close.emit();
}
this.popoverService.show({
title: 'End Training',
message: 'Do you really want to end the training?',
confirmText: 'End Training',
onConfirm: (inputValue?: string) => this.close.emit(),
});
}
/**
* Gibt den Fortschritt des Trainings an, z.B. "Bild 2 von 5".
* Returns the progress of the training, e.g., "Image 2 of 5".
*/
get progress(): string {
return `Bild ${this.currentImageIndex + 1} von ${this.deck.images.length}`;
return `Image ${this.currentImageIndex + 1} of ${this.deck.images.length}`;
}
}

View File

@@ -1,34 +0,0 @@
<!-- src/app/upload-image-modal.component.html -->
<div #uploadImageModal id="uploadImageModal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full">
<div class="relative h-full contents">
<div class="relative bg-white rounded-lg shadow">
<button type="button" class="absolute top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center" (click)="closeModal()">
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
<span class="sr-only">Schließen</span>
</button>
<div class="p-6 relative">
<h3 class="mb-4 text-xl font-medium text-gray-900">Bild zu Deck hinzufügen</h3>
<!-- Formular zum Hochladen -->
<div class="mb-4">
<label for="imageFile" class="block text-sm font-medium text-gray-700">Bild hochladen</label>
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/*" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" />
</div>
<!-- Statusanzeige -->
<div *ngIf="processingStatus" class="mt-4">
<p class="text-sm text-gray-700">{{ processingStatus }}</p>
</div>
<!-- Ladeanzeige als Overlay -->
<div *ngIf="loading" class="absolute inset-0 bg-gray-800 bg-opacity-50 flex items-center justify-center z-10">
<div class="bg-white p-4 rounded shadow">
<p class="text-sm text-gray-700">Verarbeitung läuft...</p>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@@ -1,113 +0,0 @@
// src/app/upload-image-modal.component.ts
import { Component, Input, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { Box, DeckImage, DeckService, OcrResult } from '../deck.service';
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Modal } from 'flowbite';
@Component({
selector: 'app-upload-image-modal',
templateUrl: './upload-image-modal.component.html',
standalone: true,
imports: [CommonModule]
})
export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
@Input() deckName: string = '';
@Output() imageUploaded = new EventEmitter<{ imageSrc: string | ArrayBuffer | null | undefined, deckImage:DeckImage }>();
@ViewChild('uploadImageModal') modalElement!: ElementRef;
@ViewChild('imageFile') imageFileElement!: ElementRef;
imageFile: File | null = null;
processingStatus: string = '';
loading: boolean = false;
modal: any;
constructor(private deckService: DeckService, private http: HttpClient) { }
ngAfterViewInit(): void {
this.modal = new Modal(this.modalElement.nativeElement);
}
ngOnDestroy(): void {
// Modal wird automatisch von Flowbite verwaltet
}
open(): void {
this.resetState();
this.modal.show();
}
closeModal(): void {
this.modal.hide();
}
resetState(): void {
this.imageFile = null;
this.processingStatus = '';
this.loading = false;
}
onFileChange(event: any): void {
const file: File = event.target.files[0];
if (!file) return;
this.imageFile = file;
this.processingStatus = 'Verarbeitung läuft...';
this.loading = true;
const reader = new FileReader();
reader.onload = async (e) => {
const imageSrc = e.target?.result;
// Bild als Base64-String ohne Präfix (data:image/...)
const imageBase64 = (imageSrc as string).split(',')[1];
try {
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
if (!response || !response.results) {
this.processingStatus = 'Ungültige Antwort vom OCR-Service';
this.loading = false;
return;
}
this.processingStatus = 'Verarbeitung abgeschlossen';
this.loading = false;
// Emit Event mit Bilddaten und OCR-Ergebnissen
const bildname=this.imageFile?.name??'';
const bildid=response.results.length>0?response.results[0].name:null
const boxes:Box[] = [];
response.results.forEach((result: OcrResult) => {
const box = result.box;
const xs = box.map((point: number[]) => point[0]);
const ys = box.map((point: number[]) => point[1]);
const xMin = Math.min(...xs);
const xMax = Math.max(...xs);
const yMin = Math.min(...ys);
const yMax = Math.max(...ys);
boxes.push({x1:xMin,x2:xMax,y1:yMin,y2:yMax})
});
const deckImage:DeckImage={name:bildname,id:bildid,boxes}
this.imageUploaded.emit({ imageSrc, deckImage });
this.resetFileInput();
// Schließe das Upload-Modal
this.closeModal();
} catch (error) {
console.error('Fehler beim OCR-Service:', error);
this.processingStatus = 'Fehler beim OCR-Service';
this.loading = false;
}
};
reader.readAsDataURL(file);
}
/**
* Setzt das Datei-Input-Feld zurück, sodass dieselbe Datei erneut ausgewählt werden kann.
*/
resetFileInput(): void {
if (this.imageFileElement && this.imageFileElement.nativeElement) {
this.imageFileElement.nativeElement.value = '';
}
}
}

View File

@@ -2,7 +2,7 @@
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"strict": false,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
@@ -17,10 +17,7 @@
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"lib": [
"ES2022",
"dom"
]
"lib": ["ES2022", "dom"]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,