Added angular website, with login, registration & searching.

This commit is contained in:
Tom
2025-06-24 18:56:19 +00:00
parent a0e8506027
commit e20231639c
71 changed files with 16742 additions and 0 deletions

View File

@ -0,0 +1,10 @@
.loading-container {
display: flex;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.7);
z-index: 1000;
}

View File

@ -0,0 +1,6 @@
@if (loading) {
<div class="loading-container flex-content-center">
<div>hello, loading world.</div>
</div>
}
<router-outlet />

View File

@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'angular-seshat' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('angular-seshat');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, angular-seshat');
});
});

View File

@ -0,0 +1,53 @@
import { Component, inject, OnDestroy, OnInit, PLATFORM_ID } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { AuthService } from './services/auth/auth.service';
import { ConfigService } from './services/config.service';
import { isPlatformBrowser } from '@angular/common';
import { LoadingService } from './services/loading.service';
import { Subscription } from 'rxjs';
import { RedirectionService } from './services/redirection.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit, OnDestroy {
private readonly _auth = inject(AuthService);
private readonly _config = inject(ConfigService);
private readonly _loading = inject(LoadingService);
private readonly _platformId = inject(PLATFORM_ID);
private readonly _redirect = inject(RedirectionService);
private readonly _subscriptions: Subscription[] = [];
loading: boolean = false;
ngOnInit() {
if (!isPlatformBrowser(this._platformId)) {
return;
}
this.listenToLoading();
this._config.fetch();
this._auth.update();
this._loading.listenUntilReady()
.subscribe(async () => {
this._redirect.redirect(null);
});
}
ngOnDestroy(): void {
this._subscriptions.forEach(s => s.unsubscribe());
}
listenToLoading(): void {
this._subscriptions.push(
this._loading.listen()
.subscribe((loading) => this.loading = loading)
);
}
}

View File

@ -0,0 +1,11 @@
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering()
],
};
export const config = mergeApplicationConfig(appConfig, serverConfig);

View File

@ -0,0 +1,21 @@
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withInterceptorsFromDi, withFetch, HTTP_INTERCEPTORS } from '@angular/common/http';
import { LoadingInterceptor } from './shared/interceptors/loading.interceptor';
import { TokenValidationInterceptor } from './shared/interceptors/token-validation.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(),
provideHttpClient(
withInterceptorsFromDi(),
withFetch()
),
LoadingInterceptor,
TokenValidationInterceptor,
]
};

View File

@ -0,0 +1,22 @@
import { Routes } from '@angular/router';
import { LoginFormComponent } from './login/login-form/login-form.component';
import { RegisterFormComponent } from './register/register-form/register-form.component';
import { AddNewPageComponent } from './library/add-new-page/add-new-page.component';
export const routes: Routes = [
{
path: 'login',
component: LoginFormComponent,
canActivate: [],
},
{
path: 'register',
component: RegisterFormComponent,
canActivate: [],
},
{
path: 'add/new',
component: AddNewPageComponent,
canActivate: [],
},
];

View File

@ -0,0 +1,37 @@
.results-box {
background: #5757576c;
display: flex;
flex-direction: column;
flex: 1;
overflow: auto;
}
.result-item {
padding: 10px;
}
.results-error {
text-align: center;
font-size: 16px;
color: red;
padding: 20px;
}
.results-end {
text-align: center;
font-size: 16px;
color: #ff8c00;
padding: 20px;
}
.results-error img, .results-end img {
vertical-align: middle;
}
.filter-error {
filter: brightness(0) saturate(100%) invert(25%) sepia(67%) saturate(2736%) hue-rotate(340deg) brightness(110%) contrast(100%);
}
.filter-warning {
filter: brightness(0) saturate(100%) invert(52%) sepia(95%) saturate(2039%) hue-rotate(3deg) brightness(106%) contrast(102%);
}

View File

@ -0,0 +1,28 @@
<div class="search-content">
<search-box
(searchOutput)="search.next($event)"
(filtersOutput)="filters.next($event)" />
<div class="results-box"
(scroll)="onResultsScroll($event)">
@for (result of results; track $index) {
<media-search-item class="result-item"
[media]="result" />
}
@if (searchError() != null) {
<p class="results-error">
<img src="/icons/error_icon.svg"
alt="error icon"
class="filter-error" />
{{searchError()}}
</p>
}
@if (endOfResults()) {
<div class="results-end">
<img src="/icons/warning_icon.svg"
alt="warning icon"
class="filter-warning" />
No more results returned from the provider.
</div>
}
</div>
</div>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AddNewPageComponent } from './add-new-page.component';
describe('AddNewPageComponent', () => {
let component: AddNewPageComponent;
let fixture: ComponentFixture<AddNewPageComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AddNewPageComponent]
})
.compileComponents();
fixture = TestBed.createComponent(AddNewPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,126 @@
import { Component, inject, NgZone, OnDestroy, signal } from '@angular/core';
import { AuthService } from '../../services/auth/auth.service';
import { ReactiveFormsModule } from '@angular/forms';
import { BehaviorSubject, combineLatest, distinctUntilChanged, filter, scan, Subscription, tap, throttleTime } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { RedirectionService } from '../../services/redirection.service';
import { BookSearchResultDto } from '../../shared/dto/book-search-result.dto';
import { MediaSearchItemComponent } from '../media-search-item/media-search-item.component';
import { SearchBoxComponent } from "../search-box/search-box.component";
import { SearchContextDto } from '../../shared/dto/search-context.dto';
@Component({
selector: 'add-new-page',
standalone: true,
imports: [
MediaSearchItemComponent,
ReactiveFormsModule,
SearchBoxComponent
],
templateUrl: './add-new-page.component.html',
styleUrl: './add-new-page.component.css'
})
export class AddNewPageComponent implements OnDestroy {
private readonly _auth = inject(AuthService);
private readonly _http = inject(HttpClient);
private readonly _redirect = inject(RedirectionService);
private readonly _subscriptions: Subscription[] = [];
private readonly _zone = inject(NgZone);
search = new BehaviorSubject<string>('');
filters = new BehaviorSubject<SearchContextDto>(new SearchContextDto());
page = new BehaviorSubject<number>(0);
results: BookSearchResultDto[] = [];
resultsPerPage = signal<number>(10);
endOfResults = signal<boolean>(false);
searchError = signal<string | null>(null);
constructor() {
this._zone.runOutsideAngular(() =>
// Subscription for the search bar.
this._subscriptions.push(
combineLatest({
search: this.search.pipe(
filter(value => value != null),
),
filters: this.filters,
page: this.page.pipe(
throttleTime(3000, undefined, { leading: true, trailing: true }),
),
}).pipe(
filter(entry => !this.endOfResults() && entry.search!.length > 1),
throttleTime(1000, undefined, { leading: false, trailing: true }),
scan((acc, next) => {
if (acc.search != next.search) {
this.results = [];
return {
...next,
page: 0
};
}
if (this.searchError() != null) {
return acc;
}
return {
...next,
page: Math.min(acc.page + 1, next.page),
};
}),
distinctUntilChanged(),
filter(entry => entry.page >= 0),
tap(_ => this.endOfResults.set(false)),
).subscribe((entry) => {
this._http.get('/api/providers/search',
{
params: {
...this.filters.value.values,
provider: 'google',
search: entry.search!,
startIndex: entry.page * this.resultsPerPage(),
}
}
).subscribe({
next: (results: any) => {
[].push.apply(this.results, results);
if (results.length < this.resultsPerPage()) {
this.endOfResults.set(true);
}
},
error: (err) => {
if (err instanceof HttpErrorResponse) {
if (err.status == 400) {
this.searchError.set('Something went wrong when Google received the request.');
} else if (err.status == 401) {
this.searchError.set('Unauthorized. Refresh the page to login again.');
} else if (err.status == 429) {
this.searchError.set('Too many requests. Try again in a minute.');
} else {
this.searchError.set(err.name + ': ' + err.message);
}
}
}
});
})
)
);
}
ngOnDestroy(): void {
this._subscriptions.forEach(s => s.unsubscribe());
}
onResultsScroll(event: any): void {
const scroll = event.target;
const limit = scroll.scrollHeight - scroll.clientHeight;
// Prevent page changes when:
// - new search is happening (emptying results);
// - still scrolling through current content.
if (scroll.scrollTop == 0 || scroll.scrollTop < limit) {
return;
}
this.page.next(this.page.getValue() + 1);
}
}

View File

@ -0,0 +1,12 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class LibraryModule { }

View File

@ -0,0 +1,43 @@
.result-item {
background-color: #EEE;
padding: 10px;
border-radius: 15px;
display: flex;
flex-direction: row;
}
.result-info {
margin-left: 10px;
}
.title {
display: inline;
}
.volume {
background-color: hsl(0, 0%, 84%);
display: inline;
margin-left: 10px;
padding: 3px;
border-radius: 4px;
}
.tags {
display: inline-flex;
margin-bottom: 15px;
}
.tag {
padding: 0 5px;
margin: 0 3px;
background-color: rgb(199, 199, 199);
border-radius: 4px;
}
.body {
margin: 5px 10px;
}
.footer {
text-align: right;
}

View File

@ -0,0 +1,18 @@
<div class="result-item">
<img class="result-image" [src]="media().thumbnail" />
<div class="result-info">
<div class="header">
<h2 class="title">{{media().title}}</h2>
@if (media().volume != null) {
<label class="volume">volume {{media().volume}}</label>
}
</div>
<div class="subheader tags">
@for (tag of tags(); track $index) {
<label class="tag">{{tag}}</label>
}
</div>
<p class="body description">{{media().desc}}</p>
<p class="footer">Metadata provided by {{provider()}}</p>
</div>
</div>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MediaSearchItemComponent } from './media-search-item.component';
describe('MediaSearchItemComponent', () => {
let component: MediaSearchItemComponent;
let fixture: ComponentFixture<MediaSearchItemComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [MediaSearchItemComponent]
})
.compileComponents();
fixture = TestBed.createComponent(MediaSearchItemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,39 @@
import { Component, computed, input } from '@angular/core';
import { BookSearchResultDto } from '../../shared/dto/book-search-result.dto';
@Component({
selector: 'media-search-item',
standalone: true,
imports: [],
templateUrl: './media-search-item.component.html',
styleUrl: './media-search-item.component.css'
})
export class MediaSearchItemComponent {
media = input.required<BookSearchResultDto>();
tags = computed(() => {
const tags = [];
if (this.media().language)
tags.push(this.media().language);
if (this.media().publisher)
tags.push(this.media().publisher);
if (this.media().categories)
tags.push.apply(tags, this.media().categories);
if (this.media().maturityRating.replaceAll('_', ' '))
tags.push(this.media().maturityRating);
if (this.media().publishedAt) {
tags.push(new Date(this.media().publishedAt).getFullYear());
}
return tags;
});
provider = computed(() => {
const value = this.media().provider;
return value.split(' ')
.map(s => s[0].toUpperCase() + s.substring(1))
.join(' ')
.split('-')
.map(s => s[0].toUpperCase() + s.substring(1))
.join('-');
});
}

View File

@ -0,0 +1,102 @@
.search-content {
display: flex;
flex-direction: column;
height: 100vh;
}
.search-bar {
display: flex;
padding: 20px;
flex-direction: row;
width: calc(100% - 40px);
}
.left-side,
.center-side,
.right-side {
align-content: center;
height: 40px;
border-top: 1px;
border-bottom: 1px;
border: 1px gray solid;
}
.icon-wrapper {
width: 40px;
height: 40px;
}
.left-side {
border: 1px gray solid;
border-right: 0;
border-radius: 3px 0 0 3px;
text-align: center;
}
.center-side {
flex-grow: 1;
}
.right-side {
border: 1px gray solid;
border-left: 0;
border-radius: 0 3px 3px 0;
text-align: center;
}
.search-box {
display: flex;
}
input {
flex-grow: 1;
outline: none;
font-size: 20px;
border: 0;
padding: 0 15px;
}
input:focus {
box-sizing: border-box;
box-shadow: 0 0 4px 3px rgba(31, 128, 255, 0.5);
}
.icon-button:hover {
cursor: pointer;
}
.icon-enabled {
background-color: rgb(185, 185, 185);
}
.collapsed {
display: none;
}
.filters-box {
margin: 0 60px 10px;
font-size: 15px;
}
.checkbox-wrapper, .select-wrapper, .text-wrapper {
display: inline-flex;
height: 20px;
align-items: center;
margin: 10px;
}
.checkbox-wrapper input, .select-wrapper select, .text-wrapper input {
display: inline;
height: 20px;
margin: 5px;
}
.text-wrapper input {
font-size: 13px;
outline: 1px solid;
}
.checkbox-wrapper label, .select-wrapper label, .text-wrapper label {
display: inline;
white-space: nowrap;
}

View File

@ -0,0 +1,59 @@
<div class="search-bar">
<div class="icon-wrapper left-side">
<img src="/icons/search_icon.svg"
alt="search icon" />
</div>
<div class="icon-wrapper icon-button left-side"
[class.icon-enabled]="filtersEnabled.value">
<img src="/icons/category_search_icon.svg"
alt="advanced search icon"
(click)="filtersEnabled.setValue(!filtersEnabled.value)" />
</div>
<div class="search-box center-side">
<input type="text"
placeholder="eg. Lord of the Rings"
[formControl]="search" />
</div>
<div class="icon-wrapper icon-button right-side">
<img src="/icons/close_icon.svg"
alt="clear text button"
(click)="search.setValue('')" />
</div>
</div>
<div class="filters-box"
[class.collapsed]="!filtersEnabled.value">
<div class="select-wrapper">
<label for="languageSelect">Language</label>
<select name="languageSelect"
(change)="updateFilters('langRestrict', $event.target)">
<option value="">All</option>
@for (language of provider.languages | keyvalue; track language.key) {
<option [value]="language.key">{{language.value}}</option>
}
</select>
</div>
<div class="select-wrapper">
<label for="orderBySelect">Order By</label>
<select name="orderBySelect"
(change)="updateFilters('orderBy', $event.target)">
<option value="relevance">Relevance</option>
<option value="newest">Newest</option>
</select>
</div>
<div class="select-wrapper">
<label for="resultsSizeSelect">Results Size</label>
<select name="resultsSizeSelect"
(change)="updateFilters('maxResults', $event.target)">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</div>
<div class="text-wrapper">
<label for="resultsSizeSelect">ISBN</label>
<input type="text"
placeholder="ISBN-10 or ISBN-13"
[formControl]="isbn" />
</div>
</div>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SearchBoxComponent } from './search-box.component';
describe('SearchBoxComponent', () => {
let component: SearchBoxComponent;
let fixture: ComponentFixture<SearchBoxComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [SearchBoxComponent]
})
.compileComponents();
fixture = TestBed.createComponent(SearchBoxComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,65 @@
import { Component, inject, NgZone, OnDestroy, output } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { SearchContextDto } from '../../shared/dto/search-context.dto';
import { filter, Subscription } from 'rxjs';
import { ConfigService } from '../../services/config.service';
import { CommonModule } from '@angular/common';
@Component({
selector: 'search-box',
standalone: true,
imports: [
CommonModule,
ReactiveFormsModule,
],
templateUrl: './search-box.component.html',
styleUrl: './search-box.component.css'
})
export class SearchBoxComponent implements OnDestroy {
private readonly _subscriptions: Subscription[] = [];
private readonly _zone = inject(NgZone);
config = inject(ConfigService).config;
filtersEnabled = new FormControl<boolean>(false);
search = new FormControl<string>('');
searchOutput = output<string>();
filters = new SearchContextDto();
filtersOutput = output<SearchContextDto>();
isbn = new FormControl<string>('');
constructor() {
this._zone.runOutsideAngular(() => {
this._subscriptions.push(
this.search.valueChanges.pipe(
filter(value => value != null),
).subscribe((value) => this.searchOutput.emit(value!))
);
this._subscriptions.push(
this.isbn.valueChanges.pipe(
filter(value => value != null),
).subscribe((value) => this.updateFilters('isbn', { value: value }))
)
});
}
get provider() {
switch (this.config.providers.default) {
case 'google': return this.config.providers.google;
default: return this.config.providers.google;
}
}
updateFilters(key: string, value: any) {
if (key == 'langRestrict' && value == '') {
delete this.filters.values[key];
} else {
this.filters.values[key] = value.value;
}
this.filtersOutput.emit(this.filters);
}
ngOnDestroy(): void {
this._subscriptions.forEach(s => s.unsubscribe());
}
}

View File

@ -0,0 +1,111 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.form {
width: 500px;
height: 100%;
border: black solid 2px;
border-radius: 15px;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
margin: 0 auto;
}
h1 {
display: block;
}
.messages {
width: 100%;
display: block;
text-align: center;
margin: 0 auto;
}
input {
border: none;
background-color: transparent;
width: 100%;
height: 100%;
font-size: 16px;
}
input:focus {
outline: none;
}
.input-wrapper {
margin: 20px;
padding: 5px;
border: gray solid 1px;
border-radius: 15px;
background-color: white;
display: block;
width: 400px;
height: 50px;
}
.input-wrapper:focus {
outline: 5px solid blue;
}
.checkbox-wrapper {
display: inline-flex;
height: 20px;
align-items: center;
margin: 0 auto;
}
.checkbox-wrapper input {
display: inline;
height: 20px;
padding: 5px;
margin: 5px;
}
.checkbox-wrapper label {
display: inline;
white-space: nowrap;
}
.actions {
width: 100%;
}
button {
width: calc(100% - 30px);
height: 50px;
margin: 10px auto;
border: 1px gray solid;
border-radius: 15px;
display: block;
background-color: white;
font-size: 16px;
}
button:hover {
background-color: #FAFAFA;
cursor: pointer;
}
button:disabled {
background-color: white;
cursor: auto;
}
.register-link {
margin: 10px 0;
}
.register-link a {
text-decoration: none;
}
.register-link a:hover {
text-decoration: underline;
}

View File

@ -0,0 +1,38 @@
<div class="form">
<h1>Login</h1>
<div class="messages">
<notice [message]="errorMessage"
[level]="'error'"
[visible]="errorMessage.length > 0" />
</div>
<div class="fields">
<div class="input-wrapper">
<input type="text"
placeholder="Username"
[formControl]="username" />
</div>
<div class="input-wrapper">
<input type="password"
placeholder="Password"
[formControl]="password" />
</div>
<div class="checkbox-wrapper">
<input type="checkbox"
id="rememberme"
[formControl]="rememberMe">
<label for="rememberme">Remember me?</label>
</div>
</div>
<div class="actions">
<button type="submit"
(click)="login()"
[disabled]="!forms.valid || waitForResponse">Login</button>
</div>
@if (config.features.registration) {
<div class="register-link">
Don't have an account?
<a href="/register"
(click)="register($event)">Register here.</a>
</div>
}
</div>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginFormComponent } from './login-form.component';
describe('LoginFormComponent', () => {
let component: LoginFormComponent;
let fixture: ComponentFixture<LoginFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [LoginFormComponent]
})
.compileComponents();
fixture = TestBed.createComponent(LoginFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,81 @@
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { NoticeComponent } from "../../shared/notice/notice.component";
import { Router } from '@angular/router';
import { ConfigService } from '../../services/config.service';
import { AuthService } from '../../services/auth/auth.service';
import { LoadingService } from '../../services/loading.service';
import { RedirectionService } from '../../services/redirection.service';
@Component({
selector: 'login-form',
standalone: true,
imports: [
ReactiveFormsModule,
NoticeComponent
],
templateUrl: './login-form.component.html',
styleUrl: './login-form.component.css'
})
export class LoginFormComponent {
private readonly _auth = inject(AuthService);
private readonly _loading = inject(LoadingService);
private readonly _http = inject(HttpClient);
private readonly _redirect = inject(RedirectionService);
private readonly _router = inject(Router);
readonly config = inject(ConfigService).config;
readonly username = new FormControl('', [Validators.required]);
readonly password = new FormControl('', [Validators.required]);
readonly rememberMe = new FormControl(false);
readonly forms = new FormGroup({
username: this.username,
password: this.password,
});
waitForResponse: boolean = false;
errorMessage: string = '';
login() {
if (this.waitForResponse) {
return;
}
this.waitForResponse = true;
this.errorMessage = '';
if (!this.forms.valid) {
this.waitForResponse = false;
return;
}
this._http.post('/api/auth/login', {
user_login: this.username.value,
password: this.password.value,
remember_me: this.rememberMe.value,
}).subscribe({
next: async (response: any) => {
this._auth.update(true)
.subscribe(async () => await this._redirect.redirect(null));
},
error: (err) => this.handleLoginErrors(err),
complete: () => this.waitForResponse = false
});
}
handleLoginErrors(err: any) {
if (err.status == 400 || err.status == 401) {
this.errorMessage = 'Invalid credentials.';
} else if (err.status == 403) {
this.errorMessage = 'Something went wrong.';
} else {
this.errorMessage = 'Something went wrong: ' + err.error.statusCode + ' ' + err.error.message;
}
this.waitForResponse = false;
}
async register(event: any) {
event.preventDefault();
await this._router.navigate(['register']);
}
}

View File

@ -0,0 +1,10 @@
import { NgModule } from '@angular/core';
@NgModule({
declarations: [],
imports: [
],
providers: []
})
export class LoginModule { }

View File

@ -0,0 +1,101 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.form {
width: 500px;
height: 100%;
border: black solid 2px;
border-radius: 15px;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
margin: 0 auto;
}
h1 {
display: block;
}
.messages {
width: 100%;
display: block;
text-align: center;
margin: 0 auto;
}
input {
border: none;
background-color: transparent;
width: 100%;
height: 100%;
font-size: 16px;
}
input:focus {
outline: none;
}
.input-wrapper {
margin: 20px;
padding: 5px;
border: gray solid 1px;
border-radius: 15px;
background-color: white;
display: block;
width: 400px;
height: 50px;
}
.input-wrapper:focus {
outline: 5px solid blue;
}
.actions {
width: 100%;
}
button {
width: calc(100% - 30px);
height: 50px;
margin: 10px auto;
border: 1px gray solid;
border-radius: 15px;
display: block;
background-color: white;
font-size: 16px;
}
button:hover {
background-color: #FAFAFA;
cursor: pointer;
}
button:disabled {
background-color: white;
cursor: auto;
}
.register-link {
margin: 10px 0;
}
.register-link a {
text-decoration: none;
}
.register-link a:hover {
text-decoration: underline;
}
.disabled {
color: red;
}
.center {
font-size: 16;
text-align: center;
}

View File

@ -0,0 +1,45 @@
@if (config.features.registration) {
<div class="form">
<h1>Register</h1>
<div class="messages">
<notice [message]="errorMessage"
[level]="'error'"
[visible]="errorMessage.length > 0" />
</div>
<div class="fields">
<div class="input-wrapper">
<input type="text"
placeholder="Name"
[formControl]="name" />
</div>
<div class="input-wrapper">
<input type="text"
placeholder="Username"
[formControl]="username" />
</div>
<div class="input-wrapper">
<input type="password"
placeholder="Password"
[formControl]="password" />
</div>
<div class="input-wrapper">
<input type="password"
placeholder="Password Confirm"
[formControl]="passwordConfirmation" />
</div>
</div>
<div class="actions">
<button type="submit"
(click)="register()"
[disabled]="!forms.valid || waitForResponse">Register</button>
</div>
<div class="register-link">
Already have an account?
<a href="/login"
(click)="login($event)">Login here.</a>
</div>
</div>
} @else {
<p class="center disabled">Registrations have been disabled.</p>
<p class="center">You will be redirected to login in 3 seconds.</p>
}

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RegisterFormComponent } from './register-form.component';
describe('RegisterFormComponent', () => {
let component: RegisterFormComponent;
let fixture: ComponentFixture<RegisterFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RegisterFormComponent]
})
.compileComponents();
fixture = TestBed.createComponent(RegisterFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,92 @@
import { HttpClient } from '@angular/common/http';
import { Component, inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { NoticeComponent } from "../../shared/notice/notice.component";
import { Router } from '@angular/router';
import { ConfigService } from '../../services/config.service';
import { AuthService } from '../../services/auth/auth.service';
import { LoadingService } from '../../services/loading.service';
import { RedirectionService } from '../../services/redirection.service';
@Component({
selector: 'register-form',
standalone: true,
imports: [
NoticeComponent,
ReactiveFormsModule,
],
templateUrl: './register-form.component.html',
styleUrl: './register-form.component.css'
})
export class RegisterFormComponent implements OnInit {
private readonly _auth = inject(AuthService);
private readonly _loading = inject(LoadingService);
private readonly _http = inject(HttpClient);
private readonly _redirect = inject(RedirectionService);
private readonly _router = inject(Router);
readonly config = inject(ConfigService).config;
readonly name = new FormControl('', [Validators.required]);
readonly username = new FormControl('', [Validators.required]);
readonly password = new FormControl('', [Validators.required]);
readonly passwordConfirmation = new FormControl('', [Validators.required]);
readonly forms = new FormGroup({
name: this.name,
username: this.username,
password: this.password,
passwordConfirmation: this.passwordConfirmation
});
waitForResponse: boolean = false;
errorMessage: string = '';
ngOnInit(): void {
}
register() {
if (this.waitForResponse) {
return;
}
this.waitForResponse = true;
this.errorMessage = '';
if (!this.forms.valid) {
this.waitForResponse = false;
return;
}
if (this.password.value != this.passwordConfirmation.value) {
this.errorMessage = 'Password confirmation does not match original password.';
return;
}
this._http.post('/api/auth/register', {
user_login: this.name.value,
user_name: this.username.value,
password: this.password.value,
}).subscribe({
next: async (response: any) => {
this._auth.update(true)
.subscribe(async () => await this._redirect.redirect(null));
},
error: (err) => this.handleRegistrationErrors(err),
complete: () => this.waitForResponse = false
});
}
handleRegistrationErrors(err: any) {
if (err.status == 401) {
this.errorMessage = 'Invalid credentials.';
} else if (err.status == 400 || err.status == 403) {
this.errorMessage = 'Something went wrong.';
} else {
this.errorMessage = 'Something went wrong: ' + err.error.statusCode + ' ' + err.error.message;
}
this.waitForResponse = false;
}
async login(event: any) {
event.preventDefault();
await this._router.navigate(['login']);
}
}

View File

@ -0,0 +1,12 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class RegisterModule { }

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,70 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private readonly _http = inject(HttpClient);
private authenticated = false;
private userId: string | null = null;
private username: string | null = null;
private lastValidationCheck: number = 0;
getUserId() {
return this.userId;
}
getUsername() {
return this.username;
}
isLoggedIn() {
return this.authenticated;
}
renew() {
return this._http.patch('/api/auth/login', {});
}
update(force: boolean = false) {
if (!force && this.lastValidationCheck && this.lastValidationCheck + 90000 < Date.now()) {
return of(this.authenticated);
}
this.lastValidationCheck = Date.now();
const observable = this._http.post('/api/auth/validate', {})
observable.subscribe({
next: (response: any) => {
if (response.validation === null) {
this.renew().subscribe({
next: (res: any) => {
this.authenticated = true;
this.userId = res.userId;
this.username = res.username;
},
error: (err) => {
this.authenticated = false;
this.userId = null;
this.username = null;
}
});
return;
}
this.authenticated = response.validation;
this.userId = response.userId;
this.username = response.username;
},
error: (err) => {
this.authenticated = false;
this.userId = null;
this.username = null;
}
});
return observable;
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ConfigService } from './config.service';
describe('ConfigService', () => {
let service: ConfigService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ConfigService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,36 @@
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { AppConfig } from '../shared/dto/config.dto';
import { map, Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ConfigService {
private readonly _http = inject(HttpClient);
config: AppConfig = new AppConfig();
loaded = false;
constructor() { }
fetch(): Observable<any> {
if (this.loaded) {
return of(this.config);
}
const $ = this._http.get('/api/asset/config').pipe(map((response: any) => response.config));
$.subscribe({
next: (config: any) => {
if (!config) {
console.log('Something went wrong with fetching app configuration. Using defaults.');
return;
}
this.config = config;
this.loaded = true;
},
error: (err) => { this.loaded = true; console.log('Something went wrong with fetching app configuration. Using defaults.', err); }
});
return $;
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { LoadingService } from './loading.service';
describe('LoadingService', () => {
let service: LoadingService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(LoadingService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,47 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject, delay, filter, first } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
private readonly _subject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
private readonly _status = this._subject.asObservable().pipe(delay(0));
private readonly _set: Set<string> = new Set<string>();
listen() {
return this._status;
}
listenUntilReady() {
return this._status.pipe(
filter(status => !status),
first(),
);
}
/**
* Updates the subject based on the following:
* - If loading is true, add url to the set & update subject value to true.
* - If loading is false, remove url entry and update subject to false if set is empty.
* This supports multiple requests awaiting completion.
*
* @param loading {boolean}
* @param url {string}
*/
set(loading: boolean, url: string): void {
if (!url) {
throw new Error('URL must be provided.');
}
if (loading) {
this._set.add(url);
this._subject.next(true);
} else if (this._set.has(url)) {
this._set.delete(url);
if (this._set.size === 0) {
this._subject.next(false);
}
}
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { RedirectionService } from './redirection.service';
describe('RedirectionService', () => {
let service: RedirectionService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(RedirectionService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,55 @@
import { inject, Injectable } from '@angular/core';
import { AuthService } from './auth/auth.service';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class RedirectionService {
private readonly _auth = inject(AuthService);
private readonly _router = inject(Router);
constructor() { }
async redirect(destination: string | string[] | null) {
let uri = this._router.url;
if (!this._router.url.startsWith('/') && !this._router.url.startsWith('http')) {
uri = '/' + this._router.url;
}
if (await this.handleSpecialCases(uri)) {
return;
}
const queryParams = this._router.parseUrl(uri).queryParams;
const redirect = queryParams['rd'];
if (redirect) {
if (!(await this.handleSpecialCases(redirect))) {
await this._router.navigateByUrl(redirect);
}
} else if (typeof destination === 'string') {
await this._router.navigateByUrl(destination);
} else if (destination !== null) {
await this._router.navigate(destination);
}
}
private async handleSpecialCases(uri: string): Promise<boolean> {
if (this._auth.isLoggedIn()) {
if (uri.startsWith('/login') || uri.startsWith('/register')) {
await this._router.navigate(['add', 'new']);
return true;
}
} else if (!uri.startsWith('/login') && !uri.startsWith('/register')) {
await this._router.navigate(['login'],
{
queryParams: {
rd: uri,
}
});
return true;
}
return false;
}
}

View File

@ -0,0 +1,18 @@
export class BookSearchResultDto {
providerBookId: string = '';
providerSeriesId: string = '';
title: string = '';
desc: string = '';
volume: number|null = null;
publisher: string = '';
authors: string[] = [];
industryIdentifiers: { [key: string]: string } = {};
provider: string = '';
publishedAt: string = '';
language: string = '';
mediaType: string | null = null;
categories: string[] = [];
maturityRating: string = '';
thumbnail: string = '';
url: string = '';
}

View File

@ -0,0 +1,35 @@
export class AppConfig {
features = new FeaturesConfig();
providers = new ProvidersConfig();
}
class FeaturesConfig {
registration: boolean = false;
}
class ProvidersConfig {
default: string = 'google';
google: GoogleProviderConfig = new GoogleProviderConfig();
}
class GenericProviderConfig {
name: string = '';
filters: { [key: string]: any } = {};
}
class GoogleProviderConfig extends GenericProviderConfig {
override name: string = 'Google';
// Key represents the language's ISO-639-1 code.
// Value is the name of the language.
languages: { [key: string]: any } = {
'zh': 'Chinese',
'nl': 'Dutch',
'en': 'English',
'fr': 'Francais',
'ko': 'Korean',
'ja': 'Japanese',
'es': 'Spanish',
};
}

View File

@ -0,0 +1,3 @@
export class SearchContextDto {
values: { [key: string]: string } = {};
}

View File

@ -0,0 +1,59 @@
import { HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http";
import { inject, Injectable } from "@angular/core";
import { catchError, map, Observable } from "rxjs";
import { LoadingService } from "../../services/loading.service";
@Injectable()
class LoadingHttpInterceptor implements HttpInterceptor {
private readonly _loading = inject(LoadingService);
private readonly _filters = [
{
url: '/api/auth/validate',
methods: null,
},
{
url: '/api/asset/config',
methods: null,
},
{
url: '/api/auth/login',
methods: ['PATCH'],
}
];
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let uri = request.url;
if (!request.url.startsWith('/') && !request.url.startsWith('http')) {
uri = '/' + request.url;
}
const method = request.method.toUpperCase();
if (!this._filters.some(item => uri.startsWith(item.url) && (!item.methods || item.methods.includes(method)))) {
return next.handle(request);
}
this._loading.set(true, request.url);
return next.handle(request)
.pipe(
catchError((err) => {
this._loading.set(false, request.url);
return err;
}),
map((evt: any) => {
if (evt instanceof HttpResponse) {
this._loading.set(false, request.url);
}
return evt;
}),
);
}
}
export const LoadingInterceptor = [
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingHttpInterceptor,
multi: true,
}
];

View File

@ -0,0 +1,86 @@
import { HTTP_INTERCEPTORS, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { inject, Injectable } from "@angular/core";
import { BehaviorSubject, catchError, filter, Observable, switchMap, take, throwError } from "rxjs";
import { AuthService } from "../../services/auth/auth.service";
@Injectable()
class TokenValidationHttpInterceptor implements HttpInterceptor {
private readonly _auth = inject(AuthService);
private readonly _filters: { url: string, methods: string[] | null }[] = [
{
url: '/api/auth/validate',
methods: null,
},
{
url: '/api/asset/config',
methods: null,
},
{
url: '/api/auth/login',
methods: null,
},
{
url: '/api/auth/register',
methods: null,
},
];
private _isRefreshing = false;
private _refreshSubject = new BehaviorSubject<boolean>(false);
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let uri = request.url;
if (!request.url.startsWith('/') && !request.url.startsWith('http')) {
uri = '/' + request.url;
}
const method = request.method.toUpperCase();
if (this._filters.some(item => uri.startsWith(item.url) && (!item.methods || item.methods.includes(method)))) {
return next.handle(request);
}
return next.handle(request)
.pipe(
catchError((err) => {
if (err instanceof HttpErrorResponse && err.status == 401) {
return this.handleTokenRenewal(request, next);
}
return throwError(() => err);
}),
);
}
private handleTokenRenewal(request: HttpRequest<any>, next: HttpHandler) {
if (!this._isRefreshing) {
this._isRefreshing = true;
this._refreshSubject.next(false);
return this._auth.renew()
.pipe(
take(1),
switchMap((token: any) => {
this._isRefreshing = false;
this._refreshSubject.next(true);
return next.handle(request.clone())
})
);
}
return this._refreshSubject.pipe(
filter(token => token != null),
take(1),
switchMap(_ => {
return next.handle(request.clone());
})
);
}
}
export const TokenValidationInterceptor = [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenValidationHttpInterceptor,
multi: true,
}
];

View File

@ -0,0 +1,18 @@
.info {
background-color: #ADD8E6;
}
.warning {
background-color: #FFD580;
}
.error {
background-color: #FF474C;
}
p {
width: 80%;
padding: 10px;
border-radius: 10px;
margin: 10px auto;
}

View File

@ -0,0 +1,5 @@
@if (this.visible()) {
<p [class.info]="level() == 'info'"
[class.warning]="level() == 'warning'"
[class.error]="level() == 'error'">{{this.message()}}</p>
}

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NoticeComponent } from './notice.component';
describe('NoticeComponent', () => {
let component: NoticeComponent;
let fixture: ComponentFixture<NoticeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [NoticeComponent]
})
.compileComponents();
fixture = TestBed.createComponent(NoticeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,14 @@
import { Component, input } from '@angular/core';
@Component({
selector: 'notice',
standalone: true,
imports: [],
templateUrl: './notice.component.html',
styleUrl: './notice.component.css'
})
export class NoticeComponent {
message = input<string>('');
level = input<'info' | 'warning' | 'error'>('info');
visible = input<boolean>(this.message.length > 0);
}