25 Commits

Author SHA1 Message Date
16d631423c feat: header refactor starting 2024-07-21 21:03:41 +03:00
c8168580d6 feat: dmca footer 2024-07-21 19:54:59 +03:00
f3a3344004 feat: started header changing 2024-07-20 23:47:35 +03:00
3713ac502c fix: manga page btns position 2024-07-20 23:08:04 +03:00
a81c7535c5 fix: clear search on going to main page 2024-07-20 23:01:22 +03:00
8c9efd4371 feat: click on manga page to change page 2024-07-20 22:36:31 +03:00
d710d6bac5 feat: popular titles on main page 2024-07-20 15:04:04 +03:00
6b209077ef feat: started popular titles on main page 2024-07-20 00:59:00 +03:00
2becf42487 feat: current page indicator 2024-07-19 15:57:36 +03:00
7b2c6d9fc8 feat: almost abstractions 2024-07-19 15:06:35 +03:00
00213d25a1 fix: manhwa scroll unloading pages 2024-07-18 16:51:30 +03:00
5465d1635c feat: loading indication 2024-07-18 16:50:48 +03:00
d414223df2 feat: auth btn in header 2024-07-18 16:35:46 +03:00
c427c6d0b4 feat: new token saving 2024-07-18 15:41:09 +03:00
4105933098 feat: manhwa scroll and cache pages rework 2024-07-17 23:46:33 +03:00
0fea62b639 todo: scroll offset 2024-07-17 17:00:07 +03:00
e040edb5bd feat: manhwa scroll 2024-07-17 16:58:22 +03:00
8c87401482 feat: manhwa check 2024-07-17 16:38:12 +03:00
c9c959ce76 feat: started work with directive 2024-07-15 00:05:58 +03:00
45389364ff feat: use map instead of interface 2024-07-14 23:50:16 +03:00
5a4206a81e fix(half): manhwa scroll 2024-07-14 01:05:16 +03:00
35ff603849 feat: scrolling manhwa 2024-07-12 01:32:32 +03:00
ccbd9b2f5c feat: started manhwa scrolling 2024-07-10 23:33:40 +03:00
03b200c829 feat: notification component 2024-07-10 23:02:14 +03:00
d1e32a94ca feat(rulib): token check 2024-07-10 19:22:53 +03:00
39 changed files with 779 additions and 204 deletions

View File

@@ -9,5 +9,8 @@
// "**/node_modules": true, // "**/node_modules": true,
"**/.angular": true "**/.angular": true
}, },
"editor.formatOnSave": true "editor.formatOnSave": true,
"cSpell.words": [
"Manhwa"
]
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -7,7 +7,9 @@
} }
} }
<app-header></app-header> <app-header></app-header>
<div class="h-10"></div> <div class="h-12"></div>
<main> <div class="content">
<router-outlet></router-outlet> <router-outlet></router-outlet>
</main> <app-footer></app-footer>
</div>
<app-notification></app-notification>

View File

@@ -1,4 +1,4 @@
main { .content {
overflow-y: auto; overflow-y: auto;
height: calc(100vh - 3rem); height: calc(100vh - 3rem);
} }

View File

@@ -1,12 +1,19 @@
import { Component } from "@angular/core"; import { Component } from "@angular/core";
import { RouterModule } from "@angular/router"; import { RouterModule } from "@angular/router";
import { AppService } from "./app.service"; import { AppService } from "./app.service";
import { FooterComponent } from "./components/footer/footer.component";
import { HeaderComponent } from "./components/header/header.component"; import { HeaderComponent } from "./components/header/header.component";
import { Datum } from "./services/parsers/rulib/rulib.search.dto"; import { NotificationComponent } from "./components/notification/notification.component";
@Component({ @Component({
standalone: true, standalone: true,
imports: [RouterModule, HeaderComponent], imports: [
RouterModule,
HeaderComponent,
NotificationComponent,
NotificationComponent,
FooterComponent,
],
selector: "app-root", selector: "app-root",
templateUrl: "./app.component.html", templateUrl: "./app.component.html",
styleUrl: "./app.component.less", styleUrl: "./app.component.less",
@@ -14,7 +21,6 @@ import { Datum } from "./services/parsers/rulib/rulib.search.dto";
}) })
export class AppComponent { export class AppComponent {
title = "NwaifuAnime"; title = "NwaifuAnime";
items: Datum[] = [];
constructor(private sw: AppService) {} constructor(private sw: AppService) {}
get hasUpdate() { get hasUpdate() {

View File

@@ -3,6 +3,9 @@ import { ApplicationConfig, isDevMode, provideZoneChangeDetection } from "@angul
import { provideRouter } from "@angular/router"; import { provideRouter } from "@angular/router";
import { provideServiceWorker } from "@angular/service-worker"; import { provideServiceWorker } from "@angular/service-worker";
import { appRoutes } from "./app.routes"; import { appRoutes } from "./app.routes";
import { Parser } from "./services/parsers/parser";
import { MangalibParserService } from "./services/parsers/rulib/mangalib.parser.service";
import { SlashlibParserService } from "./services/parsers/rulib/slashlib.parser.service";
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
@@ -13,5 +16,7 @@ export const appConfig: ApplicationConfig = {
registrationStrategy: "registerWhenStable:30000", registrationStrategy: "registerWhenStable:30000",
}), }),
provideHttpClient(withFetch()), provideHttpClient(withFetch()),
{ provide: Parser, multi: true, useClass: MangalibParserService },
{ provide: Parser, multi: true, useClass: SlashlibParserService },
], ],
}; };

View File

@@ -29,6 +29,18 @@
Вход Вход
</a> </a>
</li> </li>
<li>
<div class="flex flex-row gap-3">
<button
type="button"
(click)="checkToken()"
class="hover:bg-slate-600 bg-slate-400 p-3 rounded-md text-white"
>
Проверить токен
</button>
<h3 class="self-center">{{ isRuLibAuth ? "Авторизован" : "Не авторизован" }}</h3>
</div>
</li>
</ol> </ol>
</div> </div>
</div> </div>

View File

@@ -2,6 +2,7 @@ import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from "@angular/core"; import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from "@angular/core";
import { ActivatedRoute, Router, RouterLink } from "@angular/router"; import { ActivatedRoute, Router, RouterLink } from "@angular/router";
import { Subject, takeUntil } from "rxjs"; import { Subject, takeUntil } from "rxjs";
import { NotificationService } from "../../services/notification/notification.service";
import { RulibAuthService } from "../../services/parsers/rulib/rulib.auth.service"; import { RulibAuthService } from "../../services/parsers/rulib/rulib.auth.service";
import { EAuthTokenService } from "./enum"; import { EAuthTokenService } from "./enum";
@@ -15,22 +16,39 @@ import { EAuthTokenService } from "./enum";
export class AuthComponent implements AfterViewInit, OnDestroy { export class AuthComponent implements AfterViewInit, OnDestroy {
private destroy$ = new Subject<void>(); private destroy$ = new Subject<void>();
@ViewChild("libSocialToken") libSocialToken: ElementRef<HTMLInputElement> | null = null; @ViewChild("libSocialToken") libSocialToken: ElementRef<HTMLInputElement> | null = null;
isRuLibAuth = false;
constructor( constructor(
private route: ActivatedRoute, private route: ActivatedRoute,
private router: Router, private router: Router,
private rulibAuthService: RulibAuthService, private rulibAuthService: RulibAuthService,
private notificationService: NotificationService,
) {} ) {}
private setToken(service: EAuthTokenService, token: string) { private setToken(service: EAuthTokenService, token: string) {
switch (service) { switch (service) {
case EAuthTokenService.RULIB: case EAuthTokenService.RULIB:
this.rulibAuthService.setToken(token); this.rulibAuthService
.setToken(token)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
if (data) {
this.router.navigate(["/"]);
this.notificationService.info("Успешная авторизация в RuLib!", "Вход");
} else {
this.router.navigate(["/", "auth"]);
this.notificationService.error(
"Не удалось авторизоваться в RuLib! Попробуйте ещё раз.",
"Вход",
4000,
);
}
});
break; break;
default: default:
this.router.navigate(["/", "auth"]); this.router.navigate(["/", "auth"]);
this.notificationService.error("Неизвестный сервис авторизации!", "Вход");
return; return;
} }
this.router.navigate(["/"]);
} }
setLibSocialToken() { setLibSocialToken() {
@@ -40,6 +58,15 @@ export class AuthComponent implements AfterViewInit, OnDestroy {
} }
} }
checkToken() {
this.rulibAuthService
.checkToken(this.rulibAuthService.getToken())
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
this.isRuLibAuth = data;
});
}
ngAfterViewInit(): void { ngAfterViewInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => { this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const { token, service } = params; const { token, service } = params;
@@ -50,6 +77,7 @@ export class AuthComponent implements AfterViewInit, OnDestroy {
if (this.libSocialToken) { if (this.libSocialToken) {
this.libSocialToken.nativeElement.value = this.rulibAuthService.getToken(); this.libSocialToken.nativeElement.value = this.rulibAuthService.getToken();
} }
this.checkToken();
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.destroy$.next(); this.destroy$.next();

View File

@@ -56,6 +56,7 @@ export class DetailComponent implements AfterViewInit, OnDestroy {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => { this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const url = params["url"]; const url = params["url"];
if (url) { if (url) {
this.searchService.setMangalibParser();
this.getDetails(url); this.getDetails(url);
} else { } else {
this.router.navigate(["/"]); this.router.navigate(["/"]);

View File

@@ -0,0 +1,19 @@
<div class="footer w-full border-t border-black bg-gray-300 pt-3">
<p class="text-3xl ps-[5rem]">DMCA Disclaimer</p>
<div class="footer-content h-full px-[5rem] py-6 flex flex-col gap-3">
<div class="block">
<p>На русском:</p>
<p>
Разработчики этого приложения не имеют никакого отношения к контенту, доступному в
приложении. Оно собрано из источников, свободно доступных через любой веб-браузер.
</p>
</div>
<div class="block">
<p>English:</p>
<p>
The developers of this application does not have any affiliation with the content available
in the app. It is collecting from the sources freely available through any web browser.
</p>
</div>
</div>
</div>

View File

@@ -0,0 +1,9 @@
import { Component } from "@angular/core";
@Component({
selector: "app-footer",
templateUrl: "./footer.component.html",
styleUrls: ["./footer.component.less"],
standalone: true,
})
export class FooterComponent {}

View File

@@ -1,28 +1,6 @@
<div <div
class="header fixed flex justify-between w-full p-2 bg-gray-700 md:h-8 items-center md:flex-row flex-col md:gap-0 gap-3 text-xl md:text-base" class="header fixed flex flex-row items-center px-2 justify-between top-0 left-0 h-12 bg-gray-700 w-full"
> >
<div class="flex justify-between flex-row w-full align-middle"> <a routerLink="/" title="Main page"><p class="text-xl text-white">NwaifuAnime</p></a>
<a href="/"><h1 class="text-white" title="Main page">NwaifuAnime</h1></a> <app-search-field></app-search-field>
<!-- Search bar on small screens -->
<button type="button" class="md:hidden" (click)="changeMenu()">
<i [class]="menuBtnClass"></i>
</button>
</div>
<!-- Search bar on big screens -->
<div [class]="searchBarClass">
<input
type="search"
#searchInput
class="outline-none ps-1 text-sm leading-6 w-full border-0 bg-transparent border-r border-gray-700"
(keydown.enter)="search()"
/>
<button
class="align-middle w-[100px] text-center border-0 flex flex-col items-center justify-center"
type="submit"
(click)="search()"
>
<span class="text-sm text-black h-full">Поиск</span>
</button>
</div>
</div> </div>

View File

@@ -1,3 +1,7 @@
.header { .header {
transition: height 0.3s; transition: height 0.3s;
} }
:host {
z-index: 20;
position: fixed;
}

View File

@@ -1,17 +1,17 @@
import { CommonModule } from "@angular/common"; import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from "@angular/core"; import { Component, OnDestroy } from "@angular/core";
import { ActivatedRoute, NavigationEnd, Router } from "@angular/router"; import { ActivatedRoute, NavigationEnd, Router, RouterLink } from "@angular/router";
import { Subject, filter, takeUntil } from "rxjs"; import { Subject, filter, takeUntil } from "rxjs";
import { SearchFieldComponent } from "../search-field/search-field.component";
@Component({ @Component({
selector: "app-header", selector: "app-header",
templateUrl: "./header.component.html", templateUrl: "./header.component.html",
styleUrls: ["./header.component.less"], styleUrls: ["./header.component.less"],
standalone: true, standalone: true,
imports: [CommonModule], imports: [CommonModule, RouterLink, SearchFieldComponent],
}) })
export class HeaderComponent implements AfterViewInit, OnDestroy { export class HeaderComponent implements OnDestroy {
@ViewChild("searchInput") searchInput: ElementRef<HTMLInputElement> | null = null;
menuOpened = false; menuOpened = false;
private destroy$ = new Subject<void>(); private destroy$ = new Subject<void>();
constructor( constructor(
@@ -19,8 +19,10 @@ export class HeaderComponent implements AfterViewInit, OnDestroy {
private route: ActivatedRoute, private route: ActivatedRoute,
) { ) {
this.router.events this.router.events
.pipe(filter((event) => event instanceof NavigationEnd)) .pipe(
.pipe(takeUntil(this.destroy$)) filter((event) => event instanceof NavigationEnd),
takeUntil(this.destroy$),
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
.subscribe((val: any) => { .subscribe((val: any) => {
if (val.url.startsWith("/detail") || val.url.startsWith("/reader")) { if (val.url.startsWith("/detail") || val.url.startsWith("/reader")) {
@@ -28,6 +30,7 @@ export class HeaderComponent implements AfterViewInit, OnDestroy {
} }
}); });
} }
changeMenu() { changeMenu() {
this.menuOpened = !this.menuOpened; this.menuOpened = !this.menuOpened;
} }
@@ -37,23 +40,7 @@ export class HeaderComponent implements AfterViewInit, OnDestroy {
} }
get searchBarClass(): string { get searchBarClass(): string {
return `search-bar bg-slate-300 md:w-[50%] w-full md:m-0 ms-2 me-2 md:h-6 h-10 md:flex justify-start flex-row items-center rounded-md ${this.menuOpened ? "flex" : "hidden"}`; return `search-bar bg-slate-300 md:w-full w-full md:m-0 ms-2 me-2 md:h-6 h-10 md:flex justify-start flex-row items-center rounded-md ${this.menuOpened ? "flex" : "hidden"}`;
}
search() {
if (this.searchInput) {
const text = this.searchInput.nativeElement.value;
this.router.navigateByUrl(`/?search=${text}`);
}
}
ngAfterViewInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const search = params["search"];
if (search && this.searchInput) {
this.searchInput.nativeElement.value = search;
}
});
} }
ngOnDestroy(): void { ngOnDestroy(): void {

View File

@@ -1,5 +1,40 @@
<h1>It's home component</h1> @if (!search) {
@if (loading) {
<p class="text-5xl text-center mb-16">Подождите...</p>
} @else {
<p class="text-5xl text-center mb-10">Популярное:</p>
<div class="flex flex-col gap-3 items-center w-full px-4 overflow-x-hidden">
@for (popular of popularItems; track popular[0]) {
<p class="text-5xl text-center">{{ popular[0] }}</p>
<div class="w-full overflow-x-auto py-3">
<div class="flex flex-row items-center gap-4 h-[400px] w-max">
@for (popularTitle of popular[1]; track popularTitle.id) {
<a routerLink="/detail" [queryParams]="{ url: popularTitle.slug_url }" class="h-full">
<div
class="flex flex-col justify-around border-black rounded-md p-4 w-[400px] items-center border h-full flex-shrink-0"
>
<img
[src]="popularTitle.cover.thumbnail"
[alt]="popularTitle.slug"
class="w-[200px] h-auto aspect-auto"
/>
<p>{{ popularTitle.rus_name }}</p>
</div>
</a>
}
</div>
</div>
}
</div>
}
} @else {
<div class="flex flex-col items-center w-full px-3"> <div class="flex flex-col items-center w-full px-3">
@if (loading) {
<h1>Loading...</h1>
}
@if (notFound && !loading) {
<h1>Not found</h1>
}
@for (item of items; track $index) { @for (item of items; track $index) {
<a <a
routerLink="/detail" routerLink="/detail"
@@ -7,10 +42,17 @@
title="{{ item.name }}" title="{{ item.name }}"
class="mb-6 max-w-[700px] w-full" class="mb-6 max-w-[700px] w-full"
> >
<div class="card flex flex-col items-center border-black border-2 rounded-md p-4 w-full"> <div
class="card flex flex-col items-center border-black border-2 rounded-md p-4 w-full h-[350px]"
>
<h1>{{ item.rus_name }}</h1> <h1>{{ item.rus_name }}</h1>
<img [src]="item.cover.thumbnail" [alt]="item.slug" class="w-[200px] h-auto aspect-auto" /> <img
[src]="item.cover.thumbnail"
[alt]="item.slug"
class="w-[200px] h-auto max-h-[300px] aspect-auto"
/>
</div> </div>
</a> </a>
} }
</div> </div>
}

View File

@@ -1,7 +1,8 @@
import { CommonModule } from "@angular/common"; import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, Input, OnDestroy } from "@angular/core"; import { Component, Input, OnDestroy, OnInit } from "@angular/core";
import { ActivatedRoute, RouterLink } from "@angular/router"; import { ActivatedRoute, RouterLink } from "@angular/router";
import { Subject, takeUntil } from "rxjs"; import { map, Subject, Subscription, takeUntil } from "rxjs";
import { IRuLIBPopular } from "../../services/parsers/rulib/rulib.popular.dto";
import { Datum } from "../../services/parsers/rulib/rulib.search.dto"; import { Datum } from "../../services/parsers/rulib/rulib.search.dto";
import { SearchService } from "../../services/search.service"; import { SearchService } from "../../services/search.service";
@@ -12,31 +13,79 @@ import { SearchService } from "../../services/search.service";
styleUrls: ["./home.component.less"], styleUrls: ["./home.component.less"],
imports: [CommonModule, RouterLink], imports: [CommonModule, RouterLink],
}) })
export class HomeComponent implements OnDestroy, AfterViewInit { export class HomeComponent implements OnDestroy, OnInit {
@Input() items: Datum[] = []; @Input() items: Datum[] = [];
loading = false;
notFound = false;
search: string = "";
popularItemsMap: Map<string, IRuLIBPopular[]> = new Map<string, IRuLIBPopular[]>();
private destroy$ = new Subject<void>(); private destroy$ = new Subject<void>();
private popularSubscription = new Subscription();
constructor( constructor(
private searchService: SearchService, private searchService: SearchService,
private route: ActivatedRoute, private route: ActivatedRoute,
) {} ) {
this.searchService.setMangalibParser();
}
ngOnDestroy(): void { ngOnDestroy(): void {
this.destroy$.next(); this.destroy$.next();
this.destroy$.complete(); this.destroy$.complete();
this.popularSubscription.unsubscribe();
} }
ngAfterViewInit(): void { private getPopular(parserName: string) {
this.route.queryParams.subscribe((params) => {
const search = params["search"];
if (search) {
this.searchService this.searchService
.search(search) .getPopular()
.pipe(
map((data) => data as IRuLIBPopular[]),
takeUntil(this.destroy$),
)
.subscribe({
next: (data) => {
this.popularItemsMap.set(parserName, data);
this.loading = false;
},
error: (error) => {
console.error(error);
},
});
}
private getPopularMangalib() {
this.searchService.setMangalibParser();
this.getPopular(this.searchService.getRuLibName());
}
private getPopularSlashlib() {
this.searchService.setSlashlibParser();
this.getPopular(this.searchService.getRuLibName());
}
get popularItems() {
return Array.from(this.popularItemsMap.entries()).sort((a, b) => (a[0] > b[0] ? 1 : -1));
}
ngOnInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
this.search = params["search"] ?? "";
this.items = [];
this.loading = true;
if (this.search) {
this.searchService.setMangalibParser();
this.searchService
.search(this.search)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe((data) => { .subscribe((data) => {
this.loading = false;
this.items = data.data; this.items = data.data;
this.notFound = this.items.length === 0;
}); });
} else {
this.getPopularMangalib();
this.getPopularSlashlib();
} }
}); });
} }

View File

@@ -0,0 +1,12 @@
<div
class="notification-container fixed md:right-0 bottom-0 max-w-[100%] min-w-[100%] min-h-[8rem] h-[8rem] md:min-w-[20rem] px-3 pb-4"
[hidden]="!show_notification"
>
<div [class]="'notification rounded-md bg-white border-2 ' + borderColor + ' h-full'">
<div [class]="'head flex flex-row justify-between px-2 py-2 h-5 border-b-2 ' + borderColor">
<h3 class="self-center">{{ notification.name }}</h3>
<button class="self-center" (click)="closeNotification()" type="button">X</button>
</div>
<div class="notification-text mx-3 my-1">{{ notification.message }}</div>
</div>
</div>

View File

@@ -0,0 +1,53 @@
import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, OnDestroy } from "@angular/core";
import { Subject, takeUntil } from "rxjs";
import { INotification } from "../../services/notification/notification.dto";
import { NotificationService } from "../../services/notification/notification.service";
@Component({
standalone: true,
selector: "app-notification",
templateUrl: "./notification.component.html",
styleUrls: ["./notification.component.less"],
imports: [CommonModule],
})
export class NotificationComponent implements AfterViewInit, OnDestroy {
show_notification = false;
isError = false;
private closeNotificationTimer: ReturnType<typeof setTimeout> | null = null;
notification: INotification = { isError: false, message: "", name: "", time: 0 };
private destroy$ = new Subject<void>();
constructor(private notificationService: NotificationService) {}
ngAfterViewInit(): void {
this.notificationService.notification$
.asObservable()
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
if (!data) return;
this.notification = data;
this.show_notification = true;
if (this.closeNotificationTimer) {
clearTimeout(this.closeNotificationTimer);
}
this.closeNotificationTimer = setTimeout(() => {
this.show_notification = false;
}, data.time);
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
closeNotification() {
this.show_notification = false;
}
get borderColor(): string {
return this.notification.isError ? "border-red-600" : "border-green-600";
}
}

View File

@@ -11,18 +11,38 @@
<h3>{{ currentChapterInfo?.number }}. {{ currentChapterInfo?.name || "Нет названия" }}</h3> <h3>{{ currentChapterInfo?.number }}. {{ currentChapterInfo?.name || "Нет названия" }}</h3>
</div> </div>
<div class="flex flex-col items-center"> <div class="flex flex-col items-center">
@if (pages.length > 0 && cachedPages[currentPageIndex]) { @if (pages.length > 0 && currentPage) {
<div [class]="imageContainerClass"> <div [class]="imageContainerClass">
<app-scale-image [imageSrc]="imageUrl"></app-scale-image> @if (!isManhwa) {
<app-scale-image
[imageSrc]="currentPage.imageUrl"
(clickLeft)="prevPage()"
(clickRight)="nextPage()"
></app-scale-image>
} @else {
@for (page of manhwaPages; track page.id) {
<app-scale-image
[imageSrc]="page.imageUrl"
[host]="host"
(view)="loadPage(page.index)"
[hostScrollable]="isHostScrollable()"
></app-scale-image>
}
}
</div> </div>
<div class="flex items-center justify-center space-x-4 my-10"> <div class="flex items-center justify-center space-x-4 mt-[6rem]">
<button (click)="prevPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg"> <button (click)="prevPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg">
</button> </button>
<p>{{ pages[currentPageIndex].slug }} / {{ pages.length }}</p> <p *ngIf="!isManhwa">{{ pages[currentPageIndex].slug }} / {{ pages.length }}</p>
<button (click)="nextPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg"> <button (click)="nextPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg">
</button> </button>
</div> </div>
@if (isManhwa) {
<div class="hidden md:block md:fixed right-10 top-[50%]">
{{ currentPageIndex + 1 }} / {{ pages.length }}
</div>
}
} }
</div> </div>

View File

@@ -1,12 +1,20 @@
import { CommonModule } from "@angular/common"; import { CommonModule, isPlatformBrowser } from "@angular/common";
import { AfterViewInit, Component, OnDestroy } from "@angular/core"; import {
Component,
ElementRef,
HostListener,
Inject,
OnDestroy,
OnInit,
PLATFORM_ID,
} from "@angular/core";
import { ActivatedRoute, Router, RouterLink } from "@angular/router"; import { ActivatedRoute, Router, RouterLink } from "@angular/router";
import { Observable, Subject, map, takeUntil } from "rxjs"; import { Subject, takeUntil } from "rxjs";
import { Chapter, Page } from "../../services/parsers/rulib/rulib.chapter.dto"; import { Chapter, Page } from "../../services/parsers/rulib/rulib.chapter.dto";
import { IRulibChapter } from "../../services/parsers/rulib/rulib.chapters.dto"; import { IRulibChapter } from "../../services/parsers/rulib/rulib.chapters.dto";
import { SearchService } from "../../services/search.service"; import { SearchService } from "../../services/search.service";
import { ScaleImageComponent } from "../scale-image/scale-image.component"; import { ScaleImageComponent } from "../scale-image/scale-image.component";
import { CachedPages } from "./reader.dto"; import { CachedPage, CachedPages } from "./reader.dto";
@Component({ @Component({
selector: "app-reader", selector: "app-reader",
@@ -15,17 +23,17 @@ import { CachedPages } from "./reader.dto";
standalone: true, standalone: true,
imports: [CommonModule, ScaleImageComponent, RouterLink], imports: [CommonModule, ScaleImageComponent, RouterLink],
}) })
export class ReaderComponent implements AfterViewInit, OnDestroy { export class ReaderComponent implements OnInit, OnDestroy {
pages: Page[] = []; pages: Page[] = [];
currentPageIndex = 0; currentPageIndex = 0;
cachedPages: CachedPages = {}; cachedPages: CachedPages = new Map<number, CachedPage>();
imageUrl: string = ""; imageUrl: string = "";
isManhwa = false; isManhwa = false;
currentChapterInfo: Chapter | null = null; currentChapterInfo: Chapter | null = null;
url = "";
private chaptersInfo: IRulibChapter[] = []; private chaptersInfo: IRulibChapter[] = [];
private chapterNum: number = 0; private chapterNum: number = 0;
private chapterVol: number = 0; private chapterVol: number = 0;
url = "";
private fromTowards = false; private fromTowards = false;
private destroy$ = new Subject<void>(); private destroy$ = new Subject<void>();
@@ -33,37 +41,62 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
private route: ActivatedRoute, private route: ActivatedRoute,
private router: Router, private router: Router,
private searchService: SearchService, private searchService: SearchService,
public host: ElementRef,
@Inject(PLATFORM_ID) private platformId: object,
) {} ) {}
ngOnDestroy(): void { ngOnDestroy(): void {
this.destroy$.next(); this.destroy$.next();
this.destroy$.complete(); this.destroy$.complete();
} }
ngAfterViewInit(): void { get manhwaPages() {
return this.cachedPages.values();
}
ngOnInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => { this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const url = params["url"]; const url = params["url"];
const chapter = params["chapter"]; const chapter = params["chapter"];
const volume = params["volume"]; const volume = params["volume"];
const fromTowards = params["from_towards"]; const fromTowards = params["from_towards"];
if (url && chapter && volume) { if (url && chapter && volume) {
this.searchService.setMangalibParser();
if (fromTowards) this.fromTowards = Boolean(+fromTowards); if (fromTowards) this.fromTowards = Boolean(+fromTowards);
else this.fromTowards = false; else this.fromTowards = false;
this.chapterNum = +chapter; this.chapterNum = +chapter;
this.chapterVol = +volume; this.chapterVol = +volume;
this.url = url; this.url = url;
this.loadChapter(url, chapter, volume);
this.searchService this.searchService
.getChapters(url) .getChapters(url)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe((data) => { .subscribe((data) => {
this.chaptersInfo = data.data; this.chaptersInfo = data.data;
}); });
this.searchService
.isManhwa(url)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
this.isManhwa = data;
this.loadChapter(url, chapter, volume);
});
} else { } else {
this.router.navigate(["/"]); this.router.navigate(["/"]);
} }
}); });
} }
public isHostScrollable(): boolean {
if (isPlatformBrowser(this.platformId)) {
const style = window.getComputedStyle(this.host.nativeElement);
return (
style.getPropertyValue("overflow") === "auto" ||
style.getPropertyValue("overflow-y") === "scroll"
);
}
return false;
}
backToTitle() { backToTitle() {
this.router.navigate(["/", "detail"], { queryParams: { url: this.url } }); this.router.navigate(["/", "detail"], { queryParams: { url: this.url } });
} }
@@ -76,6 +109,15 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
next: (data) => { next: (data) => {
this.currentChapterInfo = data.data; this.currentChapterInfo = data.data;
this.pages = data.data.pages; this.pages = data.data.pages;
this.pages.forEach((page, index) => {
this.cachedPages.set(index, {
...page,
imageUrl: "",
isManhwa: this.isManhwa,
index,
});
});
this.loadPage(0);
if (this.fromTowards) { if (this.fromTowards) {
this.currentPageIndex = this.pages.length - 1; this.currentPageIndex = this.pages.length - 1;
this.loadPage(this.pages.length - 1); // Загрузить последнюю страницу при открытии главы this.loadPage(this.pages.length - 1); // Загрузить последнюю страницу при открытии главы
@@ -88,37 +130,61 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
}); });
} }
public intersectionLoadPage(id: number) {
const data = Array.from(this.cachedPages.values()).find((page) => page.id === id)!;
this.fetchPage(data);
}
private loadPageByIndex(index: number) {
const data = this.cachedPages.get(index)!;
this.fetchPage(data);
}
get currentPage() {
return this.cachedPages.get(this.currentPageIndex);
}
private fetchPage(page: CachedPage) {
if (!page.imageUrl)
this.searchService
.getImageData(this.searchService.getImageServer() + page.url)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
const url = this.getImageUrl(data);
this.cachedPages.set(page.index, {
...page,
imageUrl: url,
});
});
}
private cachePage(index: number) {
for (let i = index; i < Math.min(index + 2, this.cachedPages.size); i++) {
this.loadPageByIndex(i);
}
}
private clearCache(index: number) {
for (let i = 0; i <= index; i++) {
const imgUrl = this.cachedPages.get(i)!.imageUrl;
this.cachedPages.get(i)!.imageUrl = "";
URL.revokeObjectURL(imgUrl);
}
}
loadPage(index: number) { loadPage(index: number) {
if (index >= 0 && index < this.pages.length) { if (index >= 0 && index < this.pages.length) {
this.currentPageIndex = index; this.currentPageIndex = index;
this.cachePage(index); // Кэшируем текущую и соседние страницы this.cachePage(index);
this.unloadCachedPages(index); // Сгружаем ненужные страницы из кэша this.clearCache(index - 2);
const container = document.querySelector("app-reader"); } else if (index == this.cachedPages.size) {
if (container) {
container.scrollTo({
top: 0,
behavior: "smooth",
});
}
if (!this.cachedPages[index]?.imageData) {
// Если страница не закэширована, загружаем её
this.fetchAndCachePage(index)
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.updateImage();
});
} else {
// Если страница уже в кэше, просто обновляем изображение
this.updateImage();
}
} else if (index == this.pages.length) {
const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => { const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => {
return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol; return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol;
}); });
const nextChapterIndex = Math.min(thisChapterIndex + 1, this.chaptersInfo.length - 1); const nextChapterIndex = Math.min(thisChapterIndex + 1, this.chaptersInfo.length - 1);
const nextChapter = this.chaptersInfo[nextChapterIndex]; const nextChapter = this.chaptersInfo[nextChapterIndex];
if (nextChapter !== this.chaptersInfo[thisChapterIndex]) { if (nextChapter !== this.chaptersInfo[thisChapterIndex]) {
this.cachedPages = []; this.cachedPages.clear();
this.router.navigate(["/", "reader"], { this.router.navigate(["/", "reader"], {
queryParams: { queryParams: {
url: this.url, url: this.url,
@@ -134,7 +200,7 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
const prevChapterIndex = Math.max(thisChapterIndex - 1, 0); const prevChapterIndex = Math.max(thisChapterIndex - 1, 0);
const prevChapter = this.chaptersInfo[prevChapterIndex]; const prevChapter = this.chaptersInfo[prevChapterIndex];
if (prevChapter !== this.chaptersInfo[thisChapterIndex]) { if (prevChapter !== this.chaptersInfo[thisChapterIndex]) {
this.cachedPages = []; this.cachedPages.clear();
this.router.navigate(["/", "reader"], { this.router.navigate(["/", "reader"], {
queryParams: { queryParams: {
url: this.url, url: this.url,
@@ -147,67 +213,22 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
} }
} }
// Кэширование текущей страницы и несколько соседних для ускорения процесса навигации по страницам @HostListener("window:keydown", ["$event"])
private cachePage(index: number) { onKeydown(event: KeyboardEvent) {
const startIndex = Math.max(0, index - 2); if (event.key === "ArrowRight") {
const endIndex = Math.min(this.pages.length - 1, index + 2); this.nextPage();
} else if (event.key === "ArrowLeft") {
for (let i = startIndex; i <= endIndex; i++) { this.prevPage();
if (!this.isPageCached(i)) {
this.fetchAndCachePage(i)
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
if (i === this.currentPageIndex) {
this.updateImage();
}
});
}
} }
} }
private isPageCached(index: number): boolean { private getImageUrl(imageData?: Uint8Array): string {
return !!this.cachedPages[index]?.imageData; if (!imageData) {
return "";
} }
const blob = new Blob([imageData], { type: "image/jpeg" });
// Загрузка и сохранение изображения в кэш
private fetchAndCachePage(index: number): Observable<void> {
return this.searchService
.getImageData(this.searchService.getImageServer() + this.pages[index].url)
.pipe(
map((imageData) => {
this.cachedPages[index] = {
...this.pages[index],
imageData,
};
}),
);
}
// Выгрузка из кэша старых страниц
private unloadCachedPages(index: number) {
for (const key in this.cachedPages) {
const pageIndex = +key;
if (index - pageIndex > 2) {
delete this.cachedPages[pageIndex];
}
}
}
// Обновляем изображение на странице
private updateImage() {
const currentPage = this.cachedPages[this.currentPageIndex];
if (currentPage && currentPage.imageData) {
const blob = new Blob([currentPage.imageData], { type: "image/jpeg" });
const urlCreator = window.URL || window.webkitURL; const urlCreator = window.URL || window.webkitURL;
this.imageUrl = urlCreator.createObjectURL(blob); return urlCreator.createObjectURL(blob);
const imageUrl = this.imageUrl;
const image = new Image();
image.onload = () => {
this.isManhwa = image.naturalHeight / image.naturalWidth >= 5;
URL.revokeObjectURL(imageUrl);
};
image.src = imageUrl;
}
} }
nextPage() { nextPage() {
@@ -219,6 +240,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
} }
get imageContainerClass() { get imageContainerClass() {
return `${this.isManhwa ? "h-auto" : "h-[70vh]"} w-[95vw] md:w-[700px] md:h-auto`; return `${this.isManhwa ? "h-auto" : "min-h-[70vh]"} w-screen md:w-[450px] flex flex-col`;
} }
} }

View File

@@ -1,9 +1,10 @@
import { Page } from "../../services/parsers/rulib/rulib.chapter.dto"; import { Page } from "../../services/parsers/rulib/rulib.chapter.dto";
interface CachedPage extends Page { export interface CachedPage extends Page {
imageData?: Uint8Array; imageData?: Uint8Array;
imageUrl: string;
index: number;
isManhwa: boolean;
} }
export interface CachedPages { export type CachedPages = Map<number, CachedPage>;
[key: number]: CachedPage;
}

View File

@@ -1,3 +1,7 @@
<div class="image-container" #container> <div class="image-container" #container>
<img #image [src]="imageSrc" (load)="onImageLoad()" alt="Manga page" /> @if (imageSrc) {
<img #image [src]="imageSrc" (load)="onImageLoad()" alt="Manga page" class="cursor-pointer" />
} @else {
<div class="h-screen flex flex-col items-center justify-center"><h1>Loading...</h1></div>
}
</div> </div>

View File

@@ -1,5 +1,16 @@
import { AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild } from "@angular/core"; import {
import { Subscription, debounceTime, fromEvent } from "rxjs"; AfterViewInit,
Component,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
QueryList,
ViewChild,
ViewChildren,
} from "@angular/core";
import { Subject, Subscription, debounceTime, fromEvent, map, takeUntil } from "rxjs";
@Component({ @Component({
selector: "app-scale-image", selector: "app-scale-image",
@@ -11,15 +22,62 @@ export class ScaleImageComponent implements AfterViewInit, OnDestroy {
@Input({ required: true }) imageSrc: string = ""; @Input({ required: true }) imageSrc: string = "";
@ViewChild("container", { static: true }) containerRef: ElementRef | null = null; @ViewChild("container", { static: true }) containerRef: ElementRef | null = null;
@ViewChild("image", { static: true }) imageRef: ElementRef | null = null; @ViewChild("image", { static: true }) imageRef: ElementRef | null = null;
@ViewChildren("image") imageList: QueryList<ElementRef<HTMLImageElement>> = new QueryList<
ElementRef<HTMLImageElement>
>();
@Output() view = new EventEmitter<void>();
@Output() clickLeft = new EventEmitter<void>();
@Output() clickRight = new EventEmitter<void>();
@Input() host: ElementRef | null = null;
@Input() hostScrollable: boolean = false;
private destroy$ = new Subject<void>();
private resizeSubscription: Subscription = new Subscription(); private resizeSubscription: Subscription = new Subscription();
private observer!: IntersectionObserver;
ngAfterViewInit(): void { ngAfterViewInit(): void {
this.setupResizeListener(); this.setupResizeListener();
if (this.host) {
this.observer = new IntersectionObserver(
([entry]) => entry.isIntersecting && this.view.emit(),
{
root: this.hostScrollable ? this.host.nativeElement : null,
rootMargin: "100px",
},
);
if (this.containerRef) this.observer.observe(this.containerRef.nativeElement);
}
if (!this.host) {
this.imageList.changes
.pipe<QueryList<ElementRef<HTMLImageElement>>>(takeUntil(this.destroy$))
.subscribe((imageList) => {
fromEvent(imageList.first.nativeElement, "click")
.pipe(
takeUntil(this.destroy$),
map((e) => e as MouseEvent),
)
.subscribe((e) => {
const target = e.target as HTMLImageElement;
const imageWidth = target.clientWidth;
const clickX = e.offsetX;
if (clickX < imageWidth / 2) this.clickLeft.emit();
else this.clickRight.emit();
});
});
}
// fromEvent(this.imageRef.first.nativeElement, "click")
// .pipe(takeUntil(this.destroy$))
// .subscribe((e) => {
// console.log(e);
// });
} }
ngOnDestroy(): void { ngOnDestroy(): void {
if (this.resizeSubscription) this.resizeSubscription.unsubscribe(); if (this.resizeSubscription) this.resizeSubscription.unsubscribe();
if (this.observer) this.observer.disconnect();
this.destroy$.next();
this.destroy$.complete();
} }
onImageLoad() { onImageLoad() {

View File

@@ -0,0 +1,6 @@
<div class="flex flex-row gap-3 justify-between items-center">
<div class="input-block max-h-0"></div>
<div class="input-btn rounded-full w-8 h-8 bg-slate-400 flex justify-center items-center">
<i class="lni lni-search-alt"></i>
</div>
</div>

View File

@@ -0,0 +1,42 @@
import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { Subject, takeUntil } from "rxjs";
@Component({
selector: "app-search-field",
standalone: true,
imports: [CommonModule],
templateUrl: "./search-field.component.html",
styleUrl: "./search-field.component.less",
})
export class SearchFieldComponent implements AfterViewInit, OnDestroy {
@ViewChild("searchInput") searchInput: ElementRef<HTMLInputElement> | null = null;
private destroy$ = new Subject<void>();
constructor(
private route: ActivatedRoute,
private router: Router,
) {}
ngAfterViewInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const search = params["search"];
if (search && this.searchInput) {
this.searchInput.nativeElement.value = search;
}
});
}
search() {
if (this.searchInput && this.searchInput.nativeElement.value)
this.router.navigate(["/", "search"], {
queryParams: { search: this.searchInput.nativeElement.value },
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}

View File

@@ -0,0 +1,6 @@
export interface INotification {
message: string;
isError: boolean;
time: number;
name: string;
}

View File

@@ -0,0 +1,36 @@
import { Injectable, OnDestroy } from "@angular/core";
import { Subject } from "rxjs";
import { INotification } from "./notification.dto";
@Injectable({
providedIn: "root",
})
export class NotificationService implements OnDestroy {
readonly notification$ = new Subject<INotification>();
private sendNotification(message: INotification) {
this.notification$.next(message);
}
info(message: string, title: string = "", time = 3000) {
this.sendNotification({
message,
isError: false,
time: time,
name: title,
});
}
error(message: string, title: string = "", time = 3000) {
this.sendNotification({
message,
isError: true,
time: time,
name: title,
});
}
ngOnDestroy(): void {
this.notification$.complete();
}
}

View File

@@ -0,0 +1,4 @@
export enum EParser {
MangaLib = 0,
SlashLib = 1,
}

View File

@@ -15,4 +15,6 @@ export abstract class Parser {
abstract getChapters(url: string): Observable<object>; abstract getChapters(url: string): Observable<object>;
abstract getChapter(url: string, chapter: string, volume: string): Observable<object>; abstract getChapter(url: string, chapter: string, volume: string): Observable<object>;
abstract getPopular(): Observable<object[]>;
} }

View File

@@ -6,9 +6,9 @@ import { RulibAuthService } from "./rulib.auth.service";
import { IRulibChapterResult } from "./rulib.chapter.dto"; import { IRulibChapterResult } from "./rulib.chapter.dto";
import { IRulibChaptersResult } from "./rulib.chapters.dto"; import { IRulibChaptersResult } from "./rulib.chapters.dto";
import { IRulibDetailResult } from "./rulib.detail.dto"; import { IRulibDetailResult } from "./rulib.detail.dto";
import { IRuLIBPopular } from "./rulib.popular.dto";
import { IRulibSearchResult } from "./rulib.search.dto"; import { IRulibSearchResult } from "./rulib.search.dto";
//TODO: Make abstract classes
@Injectable({ @Injectable({
providedIn: "root", providedIn: "root",
}) })
@@ -84,4 +84,35 @@ export class LibSocialParserService extends Parser {
catchError((error) => throwError(() => `Now found ${error}`)), catchError((error) => throwError(() => `Now found ${error}`)),
); );
} }
isManhwa(slug_url: string): Observable<boolean> {
return this.http
.get(
`${this.url}/api/manga/${slug_url}?fields[]=summary&fields[]=genres&fields[]=tags&fields[]=authors`,
)
.pipe(
map((data) => {
const res = data as IRulibDetailResult;
return [5, 6, 4].includes(res.data.type.id);
}),
catchError((error) => throwError(() => `Now found ${error}`)),
);
}
getPopular(): Observable<IRuLIBPopular[]> {
return this.http
.get<{ data: { popular: IRuLIBPopular[] } }>(`${this.url}/api/`, {
headers: {
Authorization: "Bearer " + this.rulibAuthService.getToken(),
"Site-Id": this.site_id,
},
})
.pipe(
map((data) => {
const res = data.data.popular;
return res;
}),
catchError((error) => throwError(() => `Now found ${error}`)),
);
}
} }

View File

@@ -1,15 +1,47 @@
import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http";
import { Injectable, OnDestroy } from "@angular/core";
import { Observable, Subject, catchError, map, of, takeUntil } from "rxjs";
import { IToken } from "../token.dto";
@Injectable({ @Injectable({
providedIn: "root", providedIn: "root",
}) })
export class RulibAuthService { export class RulibAuthService implements OnDestroy {
setToken(token: string) { private destroy$ = new Subject<void>();
localStorage.setItem("token", token); private api_url = "https://api.lib.social";
constructor(private http: HttpClient) {}
setToken(token: string): Observable<boolean> {
return this.checkToken(token).pipe(
takeUntil(this.destroy$),
map((data) => {
if (!data) return false;
const token_data: IToken = JSON.parse(localStorage.getItem("token") ?? "{}");
token_data.rulib_token = token;
localStorage.setItem("token", JSON.stringify(token_data));
return true;
}),
);
} }
getToken(): string { getToken(): string {
return localStorage.getItem("token") ?? ""; const token_data: IToken = JSON.parse(localStorage.getItem("token") ?? "{}");
return token_data.rulib_token ?? "";
} }
//TODO: Проверка токена checkToken(token: string): Observable<boolean> {
return this.http
.get(this.api_url + "/api/auth/me", {
headers: { Authorization: `Bearer ${token}` },
})
.pipe(
takeUntil(this.destroy$),
map(() => true),
catchError(() => of(false)),
);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
} }

View File

@@ -0,0 +1,61 @@
export interface IRuLIBPopular {
id: number;
name: string;
rus_name: string;
eng_name: string;
slug: string;
slug_url: string;
cover: Cover;
ageRestriction: AgeRestriction;
site: number;
type: AgeRestriction;
rating: Rating;
last_item_at: Date;
metadata: Metadata;
model: Model;
status: AgeRestriction;
releaseDateString: string;
}
export interface AgeRestriction {
id: number;
label: string;
}
export interface Cover {
filename: string;
thumbnail: string;
default: string;
md: string;
}
export interface Metadata {
last_item: LastItem;
}
export interface LastItem {
id: number;
number: string;
volume: number | string;
name: string;
branch_id: number | null;
status?: null;
type?: string;
number_secondary?: string;
slug?: number;
manga_id?: null;
created_at?: Date;
likes_count?: null;
}
export enum Model {
Manga = "manga",
}
export interface Rating {
average: string;
averageFormated: string;
votes: number;
votesFormated: string;
user: number;
}

View File

@@ -0,0 +1,10 @@
import { Injectable } from "@angular/core";
import { ParserDecorator } from "../decorators/parser.decorator";
import { ESiteUrls } from "../urls";
import { LibSocialParserService } from "./lib.social.parser.service";
@Injectable({
providedIn: "root",
})
@ParserDecorator({ site_name: "Slashlib", url: ESiteUrls.LIB_SOCIAL, site_id: 2 })
export class SlashlibParserService extends LibSocialParserService {}

View File

@@ -0,0 +1,3 @@
export interface IToken {
rulib_token?: string;
}

View File

@@ -1,4 +1,5 @@
export enum ESiteUrls { export enum ESiteUrls {
LIB_SOCIAL = "https://api.lib.social", LIB_SOCIAL = "https://api.lib.social",
MANGALIB = "https://api.mangalib.me", MANGALIB = "https://api.mangalib.me",
SLASHLIB = "https://api.slashlib.me",
} }

View File

@@ -1,25 +1,37 @@
import { HttpClient } from "@angular/common/http"; import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core"; import { Inject, Injectable } from "@angular/core";
import { BehaviorSubject, Observable, map } from "rxjs"; import { Observable, map } from "rxjs";
import { MangalibParserService } from "./parsers/rulib/mangalib.parser.service"; import { EParser } from "./parsers/enums/parser";
import { Parser } from "./parsers/parser";
import { IRulibChapterResult } from "./parsers/rulib/rulib.chapter.dto"; import { IRulibChapterResult } from "./parsers/rulib/rulib.chapter.dto";
import { IRulibChaptersResult } from "./parsers/rulib/rulib.chapters.dto"; import { IRulibChaptersResult } from "./parsers/rulib/rulib.chapters.dto";
import { IRulibDetailResult } from "./parsers/rulib/rulib.detail.dto"; import { IRulibDetailResult } from "./parsers/rulib/rulib.detail.dto";
import { Datum, IRulibSearchResult } from "./parsers/rulib/rulib.search.dto"; import { IRulibSearchResult } from "./parsers/rulib/rulib.search.dto";
@Injectable({ providedIn: "root" }) @Injectable({ providedIn: "root" })
export class SearchService { export class SearchService {
private itemsTerm = new BehaviorSubject<Datum[]>([]); private parser!: Parser;
currentItemsTerm = this.itemsTerm.asObservable();
constructor( constructor(
private parser: MangalibParserService,
private http: HttpClient, private http: HttpClient,
@Inject(Parser) private parsers: Parser[],
) {} ) {}
setMangalibParser() {
this.setParser(EParser.MangaLib);
}
setSlashlibParser() {
this.setParser(EParser.SlashLib);
}
private setParser(parser: EParser) {
this.parser = this.parsers[parser];
}
search(query: string): Observable<IRulibSearchResult> { search(query: string): Observable<IRulibSearchResult> {
return this.parser.searchManga(query).pipe( return this.parser.searchManga(query).pipe(
map((data) => { map((data) => {
return data; return data as IRulibSearchResult;
}), }),
); );
} }
@@ -27,7 +39,7 @@ export class SearchService {
getDetails(slug_url: string): Observable<IRulibDetailResult> { getDetails(slug_url: string): Observable<IRulibDetailResult> {
return this.parser.getDetails(slug_url).pipe( return this.parser.getDetails(slug_url).pipe(
map((data) => { map((data) => {
return data; return data as IRulibDetailResult;
}), }),
); );
} }
@@ -35,7 +47,7 @@ export class SearchService {
getChapters(url: string): Observable<IRulibChaptersResult> { getChapters(url: string): Observable<IRulibChaptersResult> {
return this.parser.getChapters(url).pipe( return this.parser.getChapters(url).pipe(
map((data) => { map((data) => {
return data; return data as IRulibChaptersResult;
}), }),
); );
} }
@@ -43,13 +55,14 @@ export class SearchService {
getChapter(url: string, chapter: string, volume: string): Observable<IRulibChapterResult> { getChapter(url: string, chapter: string, volume: string): Observable<IRulibChapterResult> {
return this.parser.getChapter(url, chapter, volume).pipe( return this.parser.getChapter(url, chapter, volume).pipe(
map((data) => { map((data) => {
return data; return data as IRulibChapterResult;
}), }),
); );
} }
getImageServer() { getImageServer() {
return this.parser.imageServer; // eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.parser as any).imageServer;
} }
getImageData(imageUrl: string): Observable<Uint8Array> { getImageData(imageUrl: string): Observable<Uint8Array> {
@@ -59,4 +72,18 @@ export class SearchService {
}), }),
); );
} }
isManhwa(url: string): Observable<boolean> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.parser as any).isManhwa(url);
}
getPopular(): Observable<object[]> {
return this.parser.getPopular();
}
getRuLibName(): string {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.parser as any).site_name;
}
} }