changed to a non nx monorepo

This commit is contained in:
Andreas Knuth 2025-02-14 18:35:39 -06:00
parent a4f77ac63a
commit 2f16c30dad
57 changed files with 20069 additions and 272 deletions

5
.postcssrc.json Normal file
View File

@ -0,0 +1,5 @@
{
"plugins": {
"@tailwindcss/postcss": {}
}
}

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
}

28
.vscode/launch.json vendored
View File

@ -10,11 +10,31 @@
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"type": "node",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
"name": "Debug Nest Framework",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "start:debug", "--", "--inspect-brk"],
"autoAttachChildProcesses": true,
"restart": true,
"sourceMaps": true,
"stopOnEntry": false,
"console": "integratedTerminal",
"env": {
"HOST_NAME": "localhost"
}
},
{
"name": "Debug NestJS API",
"type": "node",
"request": "launch",
"runtimeExecutable": "npx",
"runtimeArgs": ["nest", "start", "--debug", "--watch"],
"port": 9229,
"cwd": "${workspaceFolder}/api",
"envFile": "${workspaceFolder}/api/.env",
"console": "integratedTerminal",
"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,59 +0,0 @@
# Haiky
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 19.1.7.
## Development server
To start a local development server, run:
```bash
ng serve
```
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the project run:
```bash
ng build
```
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Running unit tests
To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.

View File

@ -51,12 +51,19 @@
{
"glob": "**/*",
"input": "public"
}
},
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
"scripts": [],
"fileReplacements": [
{
"replace": "src/app/environments/environment.ts",
"with": "src/app/environments/environment.prod.ts"
}
]
},
"configurations": {
"production": {
@ -84,6 +91,9 @@
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "haiky:build:production"

56
api/.gitignore vendored Normal file
View File

@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

4
api/.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

32
api/eslint.config.mjs Normal file
View File

@ -0,0 +1,32 @@
// @ts-check
// export default tseslint.config(
// {
// ignores: ['eslint.config.mjs'],
// },
// eslint.configs.recommended,
// ...tseslint.configs.recommendedTypeChecked,
// eslintPluginPrettierRecommended,
// {
// languageOptions: {
// globals: {
// ...globals.node,
// ...globals.jest,
// },
// ecmaVersion: 5,
// sourceType: 'module',
// parserOptions: {
// projectService: true,
// tsconfigRootDir: import.meta.dirname,
// },
// },
// },
// {
// rules: {
// '@typescript-eslint/no-explicit-any': 'off',
// 'eslint-disable-next-line prettier/prettier': 'off',
// // '@typescript-eslint/no-floating-promises': 'warn',
// // '@typescript-eslint/no-unsafe-argument': 'warn'
// },
// },
// );

8
api/nest-cli.json Normal file
View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

12991
api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

77
api/package.json Normal file
View File

@ -0,0 +1,77 @@
{
"name": "api",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^11.0.1",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"chalk": "^5.4.1",
"drizzle-kit": "^0.30.4",
"drizzle-orm": "^0.39.3",
"pg": "^8.13.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@swc/cli": "^0.6.0",
"@swc/core": "^1.10.7",
"@types/express": "^5.0.0",
"@types/jest": "^29.5.14",
"@types/node": "^22.10.7",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^15.14.0",
"jest": "^29.7.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

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

@ -0,0 +1,13 @@
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';
import { UserController } from './user.controller';
@Module({
imports: [],
controllers: [DecksController, ProxyController, UserController],
providers: [DrizzleService, SqlLoggerService],
})
export class AppModule {}

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

@ -0,0 +1,63 @@
import * as t from 'drizzle-orm/pg-core';
import { pgEnum, pgTable as table } from 'drizzle-orm/pg-core';
export const rolesEnum = pgEnum('roles', ['admin', 'guest', 'pro']);
export const deck = table(
'deck',
{
id: t.integer('id').primaryKey().generatedAlwaysAsIdentity(),
deckname: t.varchar('deckname').notNull(),
bildname: t.varchar('bildname'),
bildid: t.varchar('bildid'),
x1: t.real('x1'),
x2: t.real('x2'),
y1: t.real('y1'),
y2: t.real('y2'),
due: t.integer('due'),
ivl: t.real('ivl'),
factor: t.real('factor'),
reps: t.integer('reps'),
lapses: t.integer('lapses'),
isGraduated: t.integer('isgraduated'),
user: t.varchar('user').notNull(),
inserted: t.timestamp('inserted', { mode: 'date' }).defaultNow(),
updated: t.timestamp('updated', { mode: 'date' }).defaultNow(),
},
table => [t.uniqueIndex('deck_idx').on(table.id)],
);
export type InsertDeck = typeof deck.$inferInsert;
export type SelectDeck = typeof deck.$inferSelect;
export const users = table(
'users',
{
id: t.integer().primaryKey().generatedAlwaysAsIdentity(),
name: t.varchar('name', { length: 256 }),
email: t.varchar().notNull(),
role: rolesEnum().default('guest'),
sign_in_provider: t.varchar('sign_in_provider', { length: 50 }),
lastLogin: t.timestamp('lastLogin', { mode: 'date' }).defaultNow(),
numberOfLogins: t.integer('numberOfLogins').default(1), // Neue Spalte
},
table => [t.uniqueIndex('users_idx').on(table.id)],
);
export type InsertUser = typeof users.$inferInsert;
export type SelectUser = typeof users.$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;
}

204
api/src/decks.controller.ts Normal file
View File

@ -0,0 +1,204 @@
// decks.controller.ts
import {
Body,
Controller,
Delete,
Get,
HttpException,
HttpStatus,
Param,
Post,
Put,
Request,
UseGuards,
} from '@nestjs/common';
import { User } from './db/schema';
import { DrizzleService } from './drizzle.service';
import { AuthGuard } from './service/auth.guard';
@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);
}
@Put('image/:bildid/rename')
async renameImage(
@Request() req,
@Param('bildid') bildid: string,
@Body() data: { newImageName: string },
) {
if (!data.newImageName) {
throw new HttpException(
'New image name is required',
HttpStatus.BAD_REQUEST,
);
}
const user: User = req['user'];
return this.drizzleService.renameImage(bildid, data.newImageName, 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);
}
}

505
api/src/drizzle.service.ts Normal file
View File

@ -0,0 +1,505 @@
// drizzle.service.ts
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { and, eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { deck, InsertUser, SelectDeck, User, users } 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(process.env['DATABASE_URL']!, {
logger: {
logQuery: (query: string, params: any[]) => {
this.sqlLogger.logQuery(query, params);
},
},
});
}
/**
* Hilfsmethode: Ermittelt die Rolle eines Users anhand der E-Mail.
*/
private async getUserRole(email: string): Promise<'guest' | 'pro' | 'admin'> {
const result = await this.db
.select({ role: users.role })
.from(users)
.where(eq(users.email, email))
.limit(1);
if (result.length === 0) {
// Falls der User nicht gefunden wird, gehen wir von "guest" aus.
return 'guest';
}
return result[0].role;
}
/**
* Methode zum Abrufen der Decks eines Benutzers.
* Hier wird unterschieden in Deck-Header (deck.bildid IS NULL) und
* zugehörige Bilder (deck.bildid IS NOT NULL). Zudem werden
* - für "guest" maximal 2 Decks und 20 Bilder pro Deck
* - für "pro" maximal 10 Decks und 40 Bilder pro Deck
* zurückgegeben.
*/
async getDecks(user: User) {
const role = await this.getUserRole(user.email);
const maxDecks =
role === 'guest' ? 2 : role === 'pro' ? 10 : Number.MAX_SAFE_INTEGER;
const maxImages =
role === 'guest' ? 20 : role === 'pro' ? 40 : Number.MAX_SAFE_INTEGER;
// Abrufen der Deck-Header (d.h. Einträge ohne Bilddaten)
const deckHeaders = await this.db
.select()
.from(deck)
.where(and(eq(deck.user, user.email), sql`bildid IS NULL`))
.limit(maxDecks);
// Für jedes Deck werden nun die zugehörigen Bilder (Einträge mit bildid) abgerufen.
const imagesForDecks = await Promise.all(
deckHeaders.map(async (header: any) => {
const images: Array<any> = await this.db
.select()
.from(deck)
.where(
and(
eq(deck.user, user.email),
eq(deck.deckname, header.deckname),
sql`bildid IS NOT NULL`,
),
);
const minimizedImagesArray = (() => {
const selectedBildnamen: Array<any> = [];
// Sammle die ersten maxImages verschiedenen Bildnamen
for (const item of images) {
if (
!selectedBildnamen.includes(item.bildname) &&
selectedBildnamen.length < maxImages
) {
selectedBildnamen.push(item.bildname);
}
}
// Filtere das Array, um nur Einträge mit diesen Bildnamen zu behalten
return images.filter((item) =>
selectedBildnamen.includes(item.bildname),
);
})();
return { minimizedImagesArray };
//return { images };
}),
);
return imagesForDecks.flatMap((item) => item.minimizedImagesArray);
}
/**
* Methode zum Erstellen eines neuen Decks.
* Hier wird geprüft, ob der User (basierend auf seiner Rolle) bereits
* die maximale Anzahl an Decks erstellt hat.
*/
async createDeck(deckname: string, user: User) {
const role = await this.getUserRole(user.email);
const maxDecks =
role === 'guest' ? 2 : role === 'pro' ? 10 : Number.MAX_SAFE_INTEGER;
// Zähle nur die Deck-Header (Einträge ohne Bilddaten)
const deckCountResult = await this.db
.select({ count: sql`count(*) as count` })
.from(deck)
.where(and(eq(deck.user, user.email), sql`bildid IS NULL`))
.all();
const deckCount = Number(deckCountResult[0].count);
if (deckCount >= maxDecks) {
throw new HttpException(
`Maximale Anzahl an Decks (${maxDecks}) erreicht für Rolle "${role}"`,
HttpStatus.FORBIDDEN,
);
}
// 'inserted' und 'updated' werden automatisch von der Datenbank gesetzt
const result = await this.db
.insert(deck)
.values({
deckname,
user: user.email,
})
.returning();
return { status: 'success', deck: result };
}
/**
* Methode zum Abrufen eines Decks nach Name.
* (Hinweis: Diese Methode wird intern z.B. in updateImage verwendet.
* Daher wird hier nicht die Limitierung angewendet.)
*/
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: new Date(),
})
.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.
* Hier wird vor dem Anlegen eines neuen Bildes geprüft, ob das
* maximale Limit pro Deck (basierend auf der User-Rolle) erreicht wurde.
*/
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);
}
// Rollenbasierte Limitierung: max. Bilder pro Deck
const role = await this.getUserRole(user.email);
const maxImages =
role === 'guest' ? 20 : role === 'pro' ? 40 : Number.MAX_SAFE_INTEGER;
// Prüfen, ob für die angegebene bildid bereits Einträge existieren.
const imageGroupExists = existingDecks.some(
(row) => row.bildid === data.bildid,
);
if (!imageGroupExists) {
// Zähle die unterschiedlichen Bilder (distinct bildid, wobei nur Einträge mit gesetzter bildid zählen)
const distinctImagesResult = await this.db
.select({ count: sql`count(distinct bildid) as count` })
.from(deck)
.where(
and(
eq(deck.user, user.email),
eq(deck.deckname, data.deckname),
sql`bildid IS NOT NULL`,
),
)
.all();
const distinctImageCount = Number(distinctImagesResult[0].count);
if (distinctImageCount >= maxImages) {
throw new HttpException(
`Maximale Anzahl an Bildern (${maxImages}) für Deck "${data.deckname}" erreicht`,
HttpStatus.FORBIDDEN,
);
}
}
// 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,
})
.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: new Date(),
})
.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
const existingIdsInDb = existingDecks
.filter(
(entry) =>
entry.bildid === data.bildid && entry.deckname === data.deckname,
)
.map((entry) => entry.id);
const incomingIds = existingEntries.map((entry) => entry.id);
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)));
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)));
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: new Date(),
})
.where(and(eq(deck.bildid, bildid), eq(deck.user, user.email)));
return { status: 'success', moved_entries: existingImages.length };
}
/**
* Methode zum Umbenennen eines Bildes.
*/
async renameImage(bildId: string, newImagename: 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('Deck not found', HttpStatus.NOT_FOUND);
}
await this.db
.update(deck)
.set({
bildname: newImagename,
updated: new Date(),
})
.where(and(eq(deck.bildid, bildId), eq(deck.user, user.email)));
return {
status: 'success',
message: 'Image Entries renamed successfully',
};
}
/**
* Methode zum Aktualisieren einer Box.
*/
async updateBox(
id: number,
data: {
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?: boolean;
inserted?: string;
},
user: User,
) {
const updateData: any = { ...data };
if (typeof data.isGraduated === 'boolean') {
updateData.isGraduated = Number(data.isGraduated);
}
updateData.updated = new Date();
updateData.inserted = new Date(data.inserted as string);
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' };
}
/**
* Methode zum Abrufen aller eindeutigen Bild-IDs aus der Datenbank.
*/
async getDistinctBildIds(user: User): Promise<string[]> {
try {
const result = await this.db
.selectDistinct([deck.bildid])
.from(deck)
.all();
const usedIds = result
.map((row: any) => row['0'])
.filter((id: string | null) => id !== null) as string[];
console.log(usedIds);
return usedIds;
} catch (error) {
this.sqlLogger.logQuery('Error fetching distinct bildids', []);
throw new HttpException(
`Fehler beim Abrufen der Bild-IDs - ${error}`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* Führt den Login-Vorgang durch:
* - Existiert der Benutzer bereits (überprüft via E-Mail), wird das Feld `lastLogin`
* (und ggf. weitere Felder) aktualisiert.
* - Existiert der Benutzer nicht, wird ein neuer Datensatz angelegt.
*/
async logIn(createUserDto: InsertUser) {
const existingUser = await this.db
.select()
.from(users)
.where(eq(users.email, createUserDto.email))
.limit(1);
if (existingUser.length > 0) {
const updatedUser = await this.db
.update(users)
.set({
lastLogin: new Date(),
name: createUserDto.name,
sign_in_provider: createUserDto.sign_in_provider,
numberOfLogins: sql`${users.numberOfLogins} + 1`,
})
.where(eq(users.email, createUserDto.email))
.returning();
return updatedUser;
} else {
const insertedUser = await this.db
.insert(users)
.values({
name: createUserDto.name,
email: createUserDto.email,
sign_in_provider: createUserDto.sign_in_provider,
lastLogin: new Date(),
role: 'guest',
})
.returning();
return insertedUser;
}
}
}

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

@ -0,0 +1,21 @@
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { json, urlencoded } from 'express';
import { AppModule } from './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}`,
);
}
void bootstrap();

133
api/src/proxy.controller.ts Normal file
View File

@ -0,0 +1,133 @@
// decks.controller.ts
import {
Body,
Controller,
HttpException,
HttpStatus,
Post,
Res,
UseGuards,
} from '@nestjs/common';
import express from 'express';
import { DrizzleService } from './drizzle.service';
import { AuthGuard } from './service/auth.guard';
@Controller('')
@UseGuards(AuthGuard)
export class ProxyController {
constructor(private readonly drizzleService: DrizzleService) {}
// --------------------
// 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,
);
}
}
// --------------------
// Cleanup Endpoint
// --------------------
@Post('cleanup')
async cleanupEndpoint(
@Body() data: { dryrun?: boolean },
@Res() res: express.Response,
) {
try {
const user = res.req['user']; // Benutzerinformationen aus dem Request
// 2. Nur Benutzer mit der spezifischen E-Mail dürfen fortfahren
if (user.email !== 'andreas.knuth@gmail.com') {
throw new HttpException('Zugriff verweigert.', HttpStatus.FORBIDDEN);
}
// 1. Abrufen der distinct bildid aus der Datenbank
const usedIds = await this.drizzleService.getDistinctBildIds(user);
// 3. Verarbeitung des dryrun Parameters
const dryrun = data.dryrun !== undefined ? data.dryrun : true;
if (typeof dryrun !== 'boolean') {
throw new HttpException(
"'dryrun' muss ein boolescher Wert sein.",
HttpStatus.BAD_REQUEST,
);
}
// 4. Aufruf des Flask-Backend-Endpunkts
const response = await fetch('http://localhost:5000/api/cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ dryrun, usedIds }),
});
const result = await response.json();
if (!response.ok) {
throw new HttpException(
result.error || 'Cleanup failed',
response.status,
);
}
// 5. Rückgabe der Ergebnisse an den Client
return res.status(HttpStatus.OK).json(result);
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException(
'Interner Serverfehler',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}

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;

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);
}
}

View File

@ -0,0 +1,17 @@
// user.controller.ts
import { Body, Controller, Post, UseGuards } from '@nestjs/common';
import type { InsertUser } from './db/schema';
import { DrizzleService } from './drizzle.service';
import { AuthGuard } from './service/auth.guard';
@Controller('users')
@UseGuards(AuthGuard)
export class UserController {
constructor(private readonly drizzleService: DrizzleService) {}
@Post()
async createUser(@Body() createUserDto: InsertUser) {
// Hier kannst du zusätzliche Validierungen oder Logik einbauen.
return await this.drizzleService.logIn(createUserDto);
}
}

4
api/tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
api/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}

3595
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"start": "ng serve --port=4202",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
@ -14,11 +14,19 @@
"@angular/common": "^19.1.0",
"@angular/compiler": "^19.1.0",
"@angular/core": "^19.1.0",
"@angular/fire": "^19.0.0",
"@angular/forms": "^19.1.0",
"@angular/platform-browser": "^19.1.0",
"@angular/platform-browser-dynamic": "^19.1.0",
"@angular/router": "^19.1.0",
"@tailwindcss/postcss": "^4.0.6",
"fabric": "^5.4.1",
"firebase": "^11.3.1",
"firebase-admin": "^13.1.0",
"flowbite": "^3.1.2",
"postcss": "^8.5.2",
"rxjs": "~7.8.0",
"tailwindcss": "^4.0.6",
"tslib": "^2.3.0",
"zone.js": "~0.15.0"
},

12
proxy.conf.json Normal file
View File

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

BIN
public/favicon-16x16.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 489 B

BIN
public/favicon-32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 562 B

BIN
public/favicon-48x48.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 593 B

View File

@ -1,12 +1,195 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import { Auth } from '@angular/fire/auth';
import { GoogleAuthProvider, signInWithPopup, UserCredential } 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';
import { UserService } from './services/user.service';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
template: `
<div *ngIf="!isLoggedIn" class="min-h-screen flex flex-col items-center justify-center" style="background: rgba(0, 119, 179, 0.1)">
<div class="text-center">
<h1 class="text-5xl font-bold mb-4">Master Your Learning</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="bg-white shadow mb-4">
<div class="container mx-auto px-4 py-2 flex justify-between items-center">
<!-- Logo und Name -->
<div class="flex items-center space-x-2">
<img src="../assets/logo.svg" alt="Logo" class="w-10 h-10" />
<span class="text-xl font-bold">Haiky</span>
</div>
<!-- Navigation -->
<div class="hidden md:flex space-x-6">
<span class="text-xl font-bold">Spaced Repetition Training</span>
</div>
<!-- User-Bereich -->
<div appClickOutside class="relative" (clickOutside)="showDropdown = false">
<img *ngIf="photoURL" [src]="photoURL" alt="User Photo" class="w-10 h-10 rounded-full cursor-pointer" (click)="toggleDropdown()" referrerpolicy="no-referrer" crossorigin="anonymous" />
<div *ngIf="!photoURL" class="image-placeholder w-10 h-10 rounded-full cursor-pointer bg-gray-300"></div>
<!-- Dropdown -->
<div *ngIf="showDropdown" class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg z-10">
<button (click)="logout()" class="block w-full text-left px-4 py-2 text-gray-700 hover:bg-gray-100">Logout</button>
</div>
</div>
</div>
</div>
<app-deck-list *ngIf="isLoggedIn"></app-deck-list>
<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,
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 = 'haiky';
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, private userService: UserService) {
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: UserCredential = 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;
await this.userService.logIn({ name: result.user.displayName, email: result.user.email, sign_in_provider: result.providerId });
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,8 +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 { environment } from './environments/environment';
import { authInterceptor } from './service/auth.interceptor';
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes)]
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

@ -0,0 +1,24 @@
<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">
<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">Close</span>
</button>
<div class="p-6">
<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>
<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">
Create
</button>
</form>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,59 @@
import { CommonModule } from '@angular/common';
import { AfterViewInit, Component, ElementRef, EventEmitter, Output, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Modal } from 'flowbite';
import { DeckService } from '../services/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],
})
export class CreateDeckModalComponent implements AfterViewInit {
@Output() deckCreated = new EventEmitter<void>();
@ViewChild('createDeckModal') modalElement!: ElementRef;
deckName: string = '';
modal!: Modal;
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
ngAfterViewInit(): void {
this.modal = new Modal(this.modalElement.nativeElement);
}
open(): void {
this.modal.show();
}
createDeck(event: Event): void {
event.preventDefault();
if (this.deckName.trim() === '') {
this.popoverService.show({
title: 'Information',
message: 'Please enter a deck name !',
});
return;
}
this.deckService.createDeck(this.deckName).subscribe({
next: () => {
this.deckName = '';
this.deckCreated.emit();
this.modal.hide();
},
error: err => {
console.error('Error creating deck', err);
this.popoverService.show({
title: 'Error',
message: 'Error creating deck.',
});
},
});
}
closeModal(): void {
this.modal.hide();
}
}

View File

@ -0,0 +1,144 @@
<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 [ngClass]="{ 'text-blue-500 font-bold': isToday(getNextTrainingDate(deck)), 'text-rose-500 font-bold': isBeforeToday(getNextTrainingDate(deck)) }">
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>
</div>
</div>
<!-- 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 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">
<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="/images/{{ image.bildid }}/thumbnail.webp" alt="{{ image.name }}" class="w-full h-auto object-cover" />
</div>
<span class="font-medium cursor-pointer">{{ image.name }}</span>
</div>
<span class="text-gray-600">({{ image.boxes.length }} boxes)</span>
</div>
<div class="flex space-x-2">
<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>
<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>
<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 (click)="openRenameImagePopover(image)" class="text-yellow-500 hover:text-yellow-700" title="Rename 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="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>
</li>
</ul>
<div class="flex flex-row space-x-2 items-stretch">
<button (click)="openTraining(activeDeck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 flex items-center justify-center whitespace-nowrap">Start Training</button>
<div class="flex-1">
<div class="relative h-full">
<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 h-full">
<div class="flex flex-col items-center">
<div class="whitespace-nowrap">Add Image</div>
<div class="text-xs whitespace-nowrap">(from file)</div>
</div>
</label>
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/jpeg,image/png,image/gif,image/webp" required class="hidden" />
</div>
</div>
<!-- Neuer Button Paste Image -->
<div class="flex-1">
<button (click)="pasteImage()" class="w-full bg-purple-500 text-white py-2 px-4 rounded hover:bg-purple-600 flex items-center justify-center h-full">
<div class="flex flex-col items-center">
<div class="whitespace-nowrap">Paste Image</div>
<div class="text-xs whitespace-nowrap">(from clipboard)</div>
</div>
</button>
</div>
</div>
</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 (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="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>

View File

@ -0,0 +1,546 @@
import { CommonModule } from '@angular/common';
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 { EditImageModalComponent } from './edit-image-modal/edit-image-modal.component';
import { MoveImageModalComponent } from './move-image-modal/move-image-modal.component';
import { Box, Deck, DeckImage, DeckService, OcrResult } from './services/deck.service';
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,
TrainingComponent,
EditImageModalComponent,
MoveImageModalComponent, // Adding the new component
FormsModule,
],
})
export class DeckListComponent implements OnInit {
decks: Deck[] = [];
trainingsDeck: Deck | null = null;
activeDeck: Deck | null = null;
loading: boolean = false;
@ViewChild(CreateDeckModalComponent)
createDeckModal!: CreateDeckModalComponent;
@ViewChild(EditImageModalComponent) editModal!: EditImageModalComponent;
@ViewChild('imageFile') imageFileElement!: ElementRef;
imageData: {
imageSrc: string | ArrayBuffer | null;
deckImage: DeckImage;
} | null = null;
// Set to track expanded decks
expandedDecks: Set<string> = new Set<string>();
// State for moving images
imageToMove: { image: DeckImage; sourceDeck: Deck } | null = null;
constructor(private deckService: DeckService, private cdr: ChangeDetectorRef, private http: HttpClient, private popoverService: PopoverService) {}
ngOnInit(): void {
this.loadExpandedDecks();
this.loadDecks();
}
loadDecks(): void {
this.deckService.getDecks().subscribe({
next: data => {
this.decks = data;
// Versuche, das zuvor gespeicherte aktive Deck zu laden
const storedActiveDeckName = localStorage.getItem('activeDeckName');
if (storedActiveDeckName) {
const foundDeck = this.decks.find(deck => deck.name === storedActiveDeckName);
if (foundDeck) {
this.activeDeck = foundDeck;
} else if (this.decks.length > 0) {
this.activeDeck = this.decks[0];
localStorage.setItem('activeDeckName', this.activeDeck.name);
}
} else if (this.decks.length > 0) {
this.activeDeck = this.decks[0];
localStorage.setItem('activeDeckName', this.activeDeck.name);
} else {
this.activeDeck = null;
}
},
error: err => console.error('Error loading decks', err),
});
}
// Updated toggle method
toggleDeckExpansion(deck: Deck): void {
this.activeDeck = deck;
localStorage.setItem('activeDeckName', deck.name);
}
// 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();
this.activeDeck = this.decks.length > 0 ? this.decks[0] : null;
},
error: err => console.error('Error deleting deck', err),
});
}
// 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),
});
}
// 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.');
}
}
openRenameImagePopover(image: DeckImage): void {
this.popoverService.showWithInput({
title: 'Rename Deck',
message: 'Enter the new name for the deck:',
confirmText: 'Rename',
inputValue: image.name,
onConfirm: (inputValue?: string) => this.confirmRenameImage(image, inputValue),
});
}
// Method to confirm the renaming of a deck
confirmRenameImage(image: DeckImage, newName?: string): void {
if (newName && newName.trim() !== '' && newName !== image.name) {
this.deckService.renameImage(image.bildid, newName).subscribe({
next: () => {
this.loadDecks();
},
error: err => console.error('Error renaming image', err),
});
} else {
// Optional: Handle ungültigen neuen Namen
console.warn('Invalid new image 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();
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;
fetch(`/images/${image.bildid}/original.webp`)
.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.trainingsDeck = null;
this.loadDecks();
}
// Method to open the create deck modal
openCreateDeckModal(): void {
this.createDeckModal.open();
}
// Method to check if a deck is expanded
isDeckExpanded(deckName: string): boolean {
return this.expandedDecks.has(deckName);
}
// Method to load expanded decks from sessionStorage
loadExpandedDecks(): void {
const stored = sessionStorage.getItem('expandedDecks');
if (stored) {
try {
const parsed: string[] = JSON.parse(stored);
this.expandedDecks = new Set<string>(parsed);
} catch (e) {
console.error('Error parsing expanded decks from sessionStorage', e);
}
} else {
// If no data is stored, do not expand any decks by default
this.expandedDecks = new Set<string>();
}
}
// Method to save expanded decks to sessionStorage
saveExpandedDecks(): void {
const expandedArray = Array.from(this.expandedDecks);
sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray));
}
// Handler for the imageUploaded event
onImageUploaded(imageData: any): void {
this.imageData = imageData;
}
onClosed() {
this.imageData = null;
}
async onImageSaved() {
// Handle saving the image data, e.g., update the list of images
this.imageData = null;
// 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;
}
}
}
// Method to open the MoveImageModal
openMoveImageModal(deck: Deck, image: DeckImage): void {
this.imageToMove = { image, sourceDeck: deck };
}
// Handler for the moveCompleted event
onImageMoved(): void {
this.imageToMove = null;
// 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 = '';
}
}
/**
* Liest das aktuelle Bild aus der Zwischenablage und setzt imageData, sodass die Edit-Image-Komponente
* mit dem eingefügten Bild startet.
*/
pasteImage(): void {
if (!navigator.clipboard || !navigator.clipboard.read) {
this.popoverService.show({
title: 'Fehler',
message: 'Das Clipboard-API wird in diesem Browser nicht unterstützt.',
});
return;
}
navigator.clipboard
.read()
.then(items => {
// Suche im Clipboard nach einem Element, das ein Bild enthält
for (const item of items) {
for (const type of item.types) {
if (type.startsWith('image/')) {
// Hole den Blob des Bildes
item.getType(type).then(blob => {
const reader = new FileReader();
this.loading = true;
reader.onload = async e => {
const imageSrc = e.target?.result;
// Extrahiere den Base64-String (ähnlich wie in onFileChange)
const imageBase64 = (imageSrc as string).split(',')[1];
try {
// Optional: OCR-Request wie im File-Upload
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
let deckImage: DeckImage;
if (response && response.results) {
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 });
});
deckImage = {
name: 'Pasted Image',
bildid: response.results.length > 0 ? response.results[0].name : null,
boxes,
};
} else {
// Falls kein OCR-Ergebnis vorliegt, lege leere Boxen an
deckImage = {
name: 'Pasted Image',
bildid: null,
boxes: [],
};
}
// Setze imageData dadurch wird in der Template der <app-edit-image-modal> eingeblendet
this.imageData = { imageSrc, deckImage };
} catch (error) {
console.error('Error with OCR service:', error);
this.popoverService.show({
title: 'Error',
message: 'Error with OCR service.',
});
} finally {
this.loading = false;
}
};
reader.readAsDataURL(blob);
});
return; // Beende die Schleife, sobald ein Bild gefunden wurde.
}
}
}
// Falls kein Bild gefunden wurde:
this.popoverService.show({
title: 'Information',
message: 'Keine Bilddaten im Clipboard gefunden.',
});
})
.catch(err => {
console.error('Fehler beim Zugriff auf das Clipboard:', err);
this.popoverService.show({
title: 'Fehler',
message: 'Fehler beim Zugriff auf das Clipboard.',
});
});
}
// Methode zur Berechnung des nächsten Trainingsdatums
getNextTrainingDate(deck: Deck): number {
const today = this.getTodayInDays();
const dueDates = deck.images.flatMap(image => image.boxes.map(box => (box.due ? box.due : null)));
if (dueDates.includes(null)) {
return today;
}
//const futureDueDates = dueDates.filter(date => date && date >= now);
if (dueDates.length > 0) {
const nextDate = dueDates.reduce((a, b) => (a < b ? a : b));
return nextDate;
}
return today;
}
getNextTrainingString(deck: Deck): string {
return this.daysSinceEpochToLocalDateString(this.getNextTrainingDate(deck));
}
// In deiner Component TypeScript Datei
isToday(epochDays: number): boolean {
return this.getTodayInDays() - epochDays === 0;
}
isBeforeToday(epochDays: number): boolean {
return this.getTodayInDays() - epochDays > 0;
}
// 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;
const today = this.getTodayInDays();
return deck.images.flatMap(image => image.boxes.filter(box => (box.due && box.due <= today) || !box.due)).length;
// this.currentImageData.boxes.filter(box => box.due === undefined || box.due <= today);
}
getTodayInDays(): number {
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));
}
daysSinceEpochToLocalDateString(days: number): string {
const msPerDay = 24 * 60 * 60 * 1000;
// Erstelle ein Datum, das den exakten UTC-Zeitpunkt (Mitternacht UTC) repräsentiert:
const utcDate = new Date(days * msPerDay);
// Formatiere das Datum: Mit timeZone: 'UTC' wird der UTC-Wert genutzt,
// aber das Ausgabeformat (z.B. "4.2.2025" oder "2/4/2025") richtet sich nach der Locale.
return new Intl.DateTimeFormat(undefined, {
timeZone: 'UTC',
day: 'numeric',
month: 'numeric',
year: 'numeric',
}).format(utcDate);
}
}

View File

@ -0,0 +1,42 @@
<div
#editImageModal
id="editImageModal"
data-modal-backdrop="static"
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 p-[20px]">
<!-- Header with box count -->
<div class="flex items-center justify-between px-4 pb-4 border-b rounded-t dark:border-gray-600 border-gray-200">
<h3 class="text-xl font-semibold text-gray-900 dark:text-white">
Edit Image <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'es' : '' }})</span>
</h3>
<button
type="button"
class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
(click)="closeModal()"
>
<svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
</svg>
<span class="sr-only">Close modal</span>
</button>
</div>
<!-- Canvas -->
<div class="p-4 md:p-5 space-y-4">
<div class="mt-4">
<canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas>
</div>
</div>
<!-- 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">New Box</button>
</div>
</div>
<!-- </div> -->
</div>
</div>

View File

@ -0,0 +1,280 @@
// src/app/edit-image-modal.component.ts
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 } from '../services/deck.service';
import { PopoverService } from '../services/popover.service';
@Component({
selector: 'app-edit-image-modal',
templateUrl: './edit-image-modal.component.html',
standalone: true,
imports: [CommonModule],
})
export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// 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 };
@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; id: number; inserted: string; updated: string }[] = [];
canvas!: fabric.Canvas;
maxCanvasWidth: number = 0;
maxCanvasHeight: number = 0;
private keyDownHandler!: (e: KeyboardEvent) => void;
modal: any;
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
async ngAfterViewInit() {
this.modal = new Modal(this.modalElement.nativeElement, {
backdrop: 'static',
onHide: () => {
this.closed.emit();
},
});
this.maxCanvasWidth = window.innerWidth * 0.6;
this.maxCanvasHeight = window.innerHeight * 0.6;
this.keyDownHandler = this.onKeyDown.bind(this);
document.addEventListener('keydown', this.keyDownHandler);
await this.initializeCanvas();
this.modal.show();
}
ngOnDestroy(): void {
document.removeEventListener('keydown', this.keyDownHandler);
if (this.canvas) {
this.canvas.dispose();
}
}
open(): void {
this.modal.show();
}
closeModal(): void {
this.modal.hide();
}
async initializeCanvas() {
await this.processImage();
}
private loadFabricImage(url: string): Promise<fabric.Image> {
return new Promise((resolve, reject) => {
fabric.Image.fromURL(
url,
img => {
resolve(img);
},
{
crossOrigin: 'anonymous',
originX: 'left',
originY: 'top',
},
);
});
}
async processImage(): Promise<void> {
try {
if (!this.imageData) {
return;
}
this.canvas = new fabric.Canvas(this.canvasElement.nativeElement);
// Set background image
const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string);
const originalWidth = backgroundImage.width!;
const originalHeight = backgroundImage.height!;
const scaleX = this.maxCanvasWidth / originalWidth;
const scaleY = this.maxCanvasHeight / originalHeight;
const scaleFactor = Math.min(scaleX, scaleY, 1);
const canvasWidth = originalWidth * scaleFactor;
const canvasHeight = originalHeight * scaleFactor;
this.canvas.setWidth(canvasWidth);
this.canvas.setHeight(canvasHeight);
backgroundImage.set({
scaleX: scaleFactor,
scaleY: scaleFactor,
});
this.canvas.setBackgroundImage(backgroundImage, this.canvas.renderAll.bind(this.canvas));
this.boxes = [];
// 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, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
objectCaching: false,
data: { id: box.id, inserted: box.inserted, updated: box.updated },
});
rect.on('modified', () => {
this.updateBoxCoordinates();
});
rect.on('moved', () => {
this.updateBoxCoordinates();
});
rect.on('scaled', () => {
this.updateBoxCoordinates();
});
rect.on('rotated', () => {
this.updateBoxCoordinates();
});
rect.on('removed', () => {
this.updateBoxCoordinates();
});
this.canvas.add(rect);
});
this.updateBoxCoordinates();
// this.detectedText = ocrResults.map(result => result.text).join('\n');
} catch (error) {
console.error('Error processing image:', error);
}
}
onKeyDown(e: KeyboardEvent): void {
if (e.key === 'Delete' || e.key === 'Del') {
const activeObject = this.canvas.getActiveObject();
if (activeObject) {
this.canvas.remove(activeObject);
this.canvas.requestRenderAll();
this.updateBoxCoordinates();
}
}
}
updateBoxCoordinates(): void {
this.boxes = [];
let scaleFactor = 1;
const bgImage = this.canvas.backgroundImage;
if (bgImage && bgImage instanceof fabric.Image) {
scaleFactor = bgImage.get('scaleX') || 1;
}
this.canvas.getObjects('rect').forEach((rect: fabric.Rect) => {
const left = rect.left!;
const top = rect.top!;
const width = rect.width! * rect.scaleX!;
const height = rect.height! * rect.scaleY!;
const x1 = left / scaleFactor;
const y1 = top / scaleFactor;
const x2 = (left + width) / scaleFactor;
const y2 = (top + height) / scaleFactor;
this.boxes.push({
x1: Math.round(x1),
x2: Math.round(x2),
y1: Math.round(y1),
y2: Math.round(y2),
id: rect.data?.id,
inserted: rect.data?.inserted,
updated: rect.data?.updated,
});
});
this.canvas.requestRenderAll();
}
addNewBox(): void {
if (!this.canvas) {
return;
}
const boxWidth = 100;
const boxHeight = 50;
const canvasWidth = this.canvas.getWidth();
const canvasHeight = this.canvas.getHeight();
const rect = new fabric.Rect({
left: (canvasWidth - boxWidth) / 2,
top: (canvasHeight - boxHeight) / 2,
width: boxWidth,
height: boxHeight,
fill: this.BOX_COLOR, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
objectCaching: false,
});
rect.on('modified', () => {
this.updateBoxCoordinates();
});
rect.on('moved', () => {
this.updateBoxCoordinates();
});
rect.on('scaled', () => {
this.updateBoxCoordinates();
});
rect.on('rotated', () => {
this.updateBoxCoordinates();
});
rect.on('removed', () => {
this.updateBoxCoordinates();
});
this.canvas.add(rect);
this.canvas.setActiveObject(rect);
this.canvas.requestRenderAll();
this.updateBoxCoordinates();
}
save(): void {
// 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?.bildid,
boxes: this.boxes,
};
this.deckService.saveImageData(data).subscribe({
next: () => {
this.imageSaved.emit();
this.closeModal();
},
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

@ -0,0 +1,22 @@
<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">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

@ -0,0 +1,47 @@
import { CommonModule } from '@angular/common';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Deck, DeckImage, DeckService } from '../services/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],
})
export class MoveImageModalComponent {
@Input() image!: DeckImage;
@Input() sourceDeck!: Deck;
@Input() decks: Deck[] = [];
@Output() moveCompleted = new EventEmitter<void>();
@Output() closed = new EventEmitter<void>();
selectedDeckId: number | null = null;
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
moveImage(): void {
if (this.selectedDeckId === null) {
return;
}
this.deckService.moveImage(this.image.bildid, this.selectedDeckId).subscribe({
next: () => {
this.moveCompleted.emit();
this.close();
},
error: err => {
console.error('Error moving image:', err);
this.popoverService.show({
title: 'Error',
message: 'Error moving image.',
});
},
});
}
close(): void {
this.closed.emit();
}
}

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,140 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
export interface Deck {
name: string;
images: DeckImage[];
}
export interface DeckImage {
boxes: Box[];
name: string;
bildid: string;
}
export interface Box {
id?: number;
x1: number;
x2: number;
y1: number;
y2: number;
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?: boolean;
inserted: string;
updated: string;
}
export interface BackendBox {
bildname: string;
deckid: number;
id: number;
x1: number;
x2: number;
y1: number;
y2: number;
}
// Defines a single point pair [x, y]
type OcrPoint = [number, number];
// Defines the box as an array of four points
type OcrBox = [OcrPoint, OcrPoint, OcrPoint, OcrPoint];
// Interface for each JSON object
export interface OcrResult {
box: OcrBox;
confidence: number;
name: string;
text: string;
}
@Injectable({
providedIn: 'root',
})
export class DeckService {
private apiUrl = '/api/decks';
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),
})),
),
);
}
private groupImagesByName(images: any[]): DeckImage[] {
const imageMap: { [key: string]: DeckImage } = {};
images.forEach(image => {
if (!imageMap[image.bildid]) {
imageMap[image.bildid] = {
name: image.name,
bildid: image.bildid,
boxes: [],
};
}
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,
inserted: image.inserted,
updated: image.updated,
});
});
return Object.values(imageMap);
}
getDeck(deckname: string): Observable<Deck> {
return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`);
}
createDeck(deckname: string): Observable<any> {
return this.http.post(this.apiUrl, { deckname });
}
deleteDeck(deckName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/${encodeURIComponent(deckName)}`);
}
renameDeck(oldDeckName: string, newDeckName: string): Observable<any> {
return this.http.put(`${this.apiUrl}/${encodeURIComponent(oldDeckName)}/rename`, { newDeckName });
}
renameImage(bildid: string, newImageName: string): Observable<any> {
return this.http.put(`${this.apiUrl}/image/${encodeURIComponent(bildid)}/rename`, { newImageName });
}
saveImageData(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/image`, data);
}
// New method to delete an image
deleteImage(imageName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/image/${imageName}`);
}
// New method to move an image
moveImage(imageId: string, targetDeckId: number): Observable<any> {
return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId });
}
updateBox(box: Box): Observable<any> {
return this.http.put(`${this.apiUrl}/boxes/${box.id}`, box);
}
}

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

@ -0,0 +1,26 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { lastValueFrom } from 'rxjs';
export interface User {
name: string;
email: string;
sign_in_provider: string;
}
@Injectable({
providedIn: 'root',
})
export class UserService {
// Passe die URL an, je nachdem wie dein Backend-Routing definiert ist.
private apiUrl = '/api/users';
constructor(private http: HttpClient) {}
/**
* Sendet die Benutzerinformationen an das Backend.
*/
logIn(user: User): Promise<any> {
return lastValueFrom(this.http.post<any>(this.apiUrl, user));
}
}

View File

@ -0,0 +1,33 @@
<div class="mt-10 mx-auto max-w-5xl">
<h2 class="text-2xl font-bold mb-4">Training: {{ deck.name }}</h2>
<div class="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">
<!-- 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">Show</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">
Again ({{ getNextInterval(currentBox, 'again') }})
</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">
Good ({{ getNextInterval(currentBox, 'good') }})
</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">
Easy ({{ getNextInterval(currentBox, 'easy') }})
</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">Next Image</button>
</div>
<p class="mt-2">{{ progress }}</p>
<button (click)="closeTraining()" class="mt-4 text-gray-500 hover:text-gray-700 underline">End Training</button>
</div>
</div>

View File

@ -0,0 +1,459 @@
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 '../services/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)
};
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
};
const EASY_INTERVAL = 4 * 1440; // 4 days in minutes
@Component({
selector: 'app-training',
templateUrl: './training.component.html',
standalone: true,
imports: [CommonModule],
})
export class TrainingComponent implements OnInit {
@Input() deck!: Deck;
@Output() close = new EventEmitter<void>();
@ViewChild('canvas', { static: false }) canvasRef!: ElementRef<HTMLCanvasElement>;
currentImageIndex: number = 0;
currentImageData: DeckImage | null = null;
currentBoxIndex: number = 0;
boxesToReview: Box[] = [];
boxRevealed: boolean[] = [];
isShowingBox: boolean = false;
isTrainingFinished: boolean = false;
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
ngOnInit(): void {
// Initialization was done in ngAfterViewInit
}
ngAfterViewInit() {
// Initialize the first image and its boxes
if (this.deck && this.deck.images.length > 0) {
this.loadImage(this.currentImageIndex);
} else {
this.popoverService.show({
title: 'Information',
message: 'No deck or images available.',
});
this.close.emit();
}
}
/**
* 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) {
this.endTraining();
return;
}
this.currentImageData = this.deck.images[imageIndex];
// Initialize the boxes for the current round
this.initializeBoxesToReview();
}
/**
* 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) {
this.nextImage();
return;
}
// 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) {
// No more boxes for this image, move to the next image
this.nextImage();
return;
}
// Shuffle the boxes randomly
this.boxesToReview = this.shuffleArray(this.boxesToReview);
// Initialize the array to track revealed boxes
this.boxRevealed = new Array(this.boxesToReview.length).fill(false);
// Reset the current box index
this.currentBoxIndex = 0;
this.isShowingBox = false;
// Redraw the canvas
this.drawCanvas();
}
/**
* Returns today's date in days since the UNIX epoch.
*/
getTodayInDays(): number {
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));
}
/**
* 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;
const ctx = canvas.getContext('2d');
if (!ctx || !this.currentImageData) return;
const img = new Image();
img.src = `/images/${this.currentImageData.bildid}/original.webp`;
img.onload = () => {
// Set the canvas size to the image size
canvas.width = img.width;
canvas.height = img.height;
// Draw the image
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// 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 is currently revealed, no overlay
return;
} else if (this.currentBoxIndex === index && !this.isShowingBox) {
// Box is revealed
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Opaque green overlay
} else {
// Box is hidden
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Opaque red overlay
}
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
});
};
img.onerror = () => {
console.error('Error loading image for canvas.');
this.popoverService.show({
title: 'Error',
message: 'Error loading image for canvas.',
});
this.close.emit();
};
}
/**
* Shuffles an array randomly.
* @param array The array to shuffle
* @returns The shuffled array
*/
shuffleArray<T>(array: T[]): T[] {
let currentIndex = array.length,
randomIndex;
// While there are elements to shuffle
while (currentIndex !== 0) {
// Pick a remaining element
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// Swap it with the current element
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
}
/**
* Returns the current box being reviewed.
*/
get currentBox(): Box | null {
if (this.currentBoxIndex < this.boxesToReview.length) {
return this.boxesToReview[this.currentBoxIndex];
}
return null;
}
/**
* Reveals the content of the current box.
*/
showText(): void {
if (this.currentBoxIndex >= this.boxesToReview.length) return;
this.boxRevealed[this.currentBoxIndex] = true;
this.isShowingBox = true;
this.drawCanvas();
}
/**
* Marks the current box as "Again" and proceeds to the next box.
*/
async markAgain(): Promise<void> {
await this.updateCard('again');
this.coverCurrentBox();
this.nextBox();
}
/**
* Marks the current box as "Good" and proceeds to the next box.
*/
async markGood(): Promise<void> {
await this.updateCard('good');
this.coverCurrentBox();
this.nextBox();
}
/**
* Marks the current box as "Easy" and proceeds to the next box.
*/
async markEasy(): Promise<void> {
await this.updateCard('easy');
this.coverCurrentBox();
this.nextBox();
}
/**
* 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;
const box = this.boxesToReview[this.currentBoxIndex];
const today = this.getTodayInDays();
// Calculate the new interval and possibly the new factor
const { newIvl, newFactor, newReps, newLapses, newIsGraduated } = this.calculateNewInterval(box, action);
// Update the due date
const nextDue = today + Math.floor(newIvl / 1440);
// Update the box object
box.ivl = newIvl;
box.factor = newFactor;
box.reps = newReps;
box.lapses = newLapses;
box.due = nextDue;
box.isGraduated = newIsGraduated;
// Send the update to the backend
try {
await lastValueFrom(this.deckService.updateBox(box));
} catch (error) {
console.error('Error updating box:', error);
this.popoverService.show({
title: 'Error',
message: 'Error updating box.',
});
}
}
/**
* 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;
} {
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;
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++;
// Faktor zuerst aktualisieren
const updatedFactor = Math.min(FACTOR_CHANGES.MAX, newFactor * FACTOR_CHANGES.EASY);
if (!newIsGraduated) {
// Direkte Graduierung mit Easy
newIsGraduated = true;
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) {
if (newReps === 1) {
newIvl = LEARNING_STEPS.GOOD; // 10 Minuten
} else {
newIsGraduated = true;
newIvl = LEARNING_STEPS.GRADUATION; // 1 Tag nach zweiter Good-Antwort
}
} else {
// Standard-SR-Formel
newIvl = Math.round(newIvl * newFactor);
}
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
/**
* 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 '';
const { newIvl } = this.calculateNewInterval(box, action);
return this.formatInterval(newIvl);
}
/**
* 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`;
}
/**
* Covers the current box again (hides it).
*/
coverCurrentBox(): void {
this.boxRevealed[this.currentBoxIndex] = false;
this.drawCanvas();
}
/**
* 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) {
// Round completed, start a new round
this.initializeBoxesToReview();
} else {
// Move to the next box
this.currentBoxIndex++;
this.drawCanvas();
}
}
/**
* Moves to the next image in the deck.
*/
nextImage(): void {
this.currentImageIndex++;
this.loadImage(this.currentImageIndex);
}
/**
* 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 {
this.popoverService.show({
title: 'Information',
message: 'This is the last image in the deck.',
});
}
}
/**
* Ends the training and displays a completion message.
*/
endTraining(): void {
this.isTrainingFinished = true;
this.popoverService.show({
title: 'Information',
message: 'Training completed!',
});
this.close.emit();
}
/**
* Asks the user if they want to end the training and closes it if confirmed.
*/
closeTraining(): void {
this.popoverService.show({
title: 'End Training',
message: 'Do you really want to end the training?',
confirmText: 'End Training',
onConfirm: (inputValue?: string) => this.close.emit(),
});
}
/**
* Returns the progress of the training, e.g., "Image 2 of 5".
*/
get progress(): string {
return `Image ${this.currentImageIndex + 1} of ${this.deck.images.length}`;
}
}

19
src/assets/logo.svg Normal file
View File

@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
<!-- Hintergrund -->
<rect width="40" height="40" fill="#ffffff"/>
<!-- Basis H - Rot -->
<path d="M6 4 H14 V16 H26 V4 H34 V36 H26 V24 H14 V36 H6 Z" fill="#FF4F4F"/>
<!-- Grünes Element -->
<path d="M6 4 H14 V16 H26 V4 H34 V20 H6 Z" fill="#2ECC40"/>
<!-- Gelber Bereich -->
<path d="M10 8 H16 V16 H24 V8 H30 V32 H24 V24 H16 V32 H10 Z" fill="#FFBE00"/>
<!-- Jadegrüner Bereich -->
<path d="M12 12 H18 V16 H22 V12 H28 V28 H22 V24 H18 V28 H12 Z" fill="#00C4A7"/>
<!-- Innerstes blaues Element -->
<path d="M14 14 H19 V16 H21 V14 H26 V26 H21 V24 H19 V26 H14 Z" fill="#0077B3"/>
</svg>

After

Width:  |  Height:  |  Size: 682 B

View File

@ -1,13 +1,22 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Haiky</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<head>
<meta charset="utf-8" />
<title>Vokabeltraining</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png" />
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="48x48" href="favicon-48x48.png" />
<style>
body {
margin: 0;
height: 100vh;
background: rgba(0, 119, 179, 0.1);
}
</style>
</head>
<body>
<app-root></app-root>
</body>
</body>
</html>

6
src/proxy.conf.json Normal file
View File

@ -0,0 +1,6 @@
{
"/api": {
"target": "http://localhost:5000",
"secure": false
}
}

View File

@ -1 +1,4 @@
/* You can add global styles to this file, and also import other style files */
@use 'tailwindcss' as *;
button {
cursor: pointer;
}

13
tailwind.config.js Normal file
View File

@ -0,0 +1,13 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{html,ts}",
"./node_modules/flowbite/**/*.js" // add this line
],
theme: {
extend: {},
},
plugins: [
require('flowbite/plugin')
],
}

View File

@ -4,7 +4,7 @@
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"strict": false,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,

View File

@ -1,15 +0,0 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}