- Portage des fonctionnalités de la branche main

- Ajout de node et npm dans la Dockerfile

- Ajout des Factories et Fixtures

- Ajout de npm-install dans Make install
This commit is contained in:
Jérémy Guillot
2024-06-03 19:41:24 +02:00
parent 41a1a8c44c
commit 291e85338a
53 changed files with 11825 additions and 18 deletions

7
.gitignore vendored
View File

@@ -24,3 +24,10 @@
/phpunit.xml /phpunit.xml
.phpunit.result.cache .phpunit.result.cache
###< phpunit/phpunit ### ###< phpunit/phpunit ###
###> symfony/webpack-encore-bundle ###
/node_modules/
/public/build/
npm-debug.log
yarn-error.log
###< symfony/webpack-encore-bundle ###

View File

@@ -22,6 +22,9 @@ RUN apk add --no-cache \
git \ git \
; ;
# Install Node.js and npm
RUN apk add --no-cache nodejs npm
RUN set -eux; \ RUN set -eux; \
install-php-extensions \ install-php-extensions \
@composer \ @composer \

View File

@@ -1,8 +1,10 @@
# Executables (local) # Executables (local)
DOCKER_COMP = docker compose DOCKER_COMP = docker compose
DOCKER_COMP_EXEC:=$(DOCKER_COMP) exec
# Docker containers # Docker containers
PHP_CONT = $(DOCKER_COMP) exec php PHP_CONT = $(DOCKER_COMP_EXEC) php
# Executables # Executables
PHP = $(PHP_CONT) php PHP = $(PHP_CONT) php
@@ -12,7 +14,7 @@ SF_MEMORY = $(PHP) -d memory_limit=256M bin/console
# Misc # Misc
.DEFAULT_GOAL = help .DEFAULT_GOAL = help
.PHONY : help build start install down stop logs sh composer vendor sf cc test phpmd phpcs quality fix-permissions controller entity migration migration-diff migration-migrate form crud fixtures command auth subscriber state-processor state-provider .PHONY : help build start install down stop logs sh composer vendor sf cc test phpmd phpcs quality fix-permissions controller entity migration migration-diff migration-migrate form crud fixtures command auth subscriber state-processor state-provider npm-install npm-run npm-watch
## —— 🎵 🐳 The Symfony Docker Makefile 🐳 🎵 —————————————————————————————————— ## —— 🎵 🐳 The Symfony Docker Makefile 🐳 🎵 ——————————————————————————————————
help: ## Outputs this help screen help: ## Outputs this help screen
@@ -25,7 +27,7 @@ build: ## Builds the Docker images
start: ## Start the docker hub in detached mode (no logs) start: ## Start the docker hub in detached mode (no logs)
@$(DOCKER_COMP) up --pull always -d --wait @$(DOCKER_COMP) up --pull always -d --wait
install: build start vendor## Build and start the containers install: build start vendor npm-install## Build and start the containers
down: ## Stop and remove the docker hub down: ## Stop and remove the docker hub
@$(DOCKER_COMP) down --remove-orphans @$(DOCKER_COMP) down --remove-orphans
@@ -123,3 +125,13 @@ state-processor: ## Create a new state processor
state-provider: ## Create a new state provider state-provider: ## Create a new state provider
@$(SYMFONY) make:state-provider @$(SYMFONY) make:state-provider
## —— Webpack Encore —————————————————————————————————————————————————————————————
npm-install: ## Install npm dependencies
@$(DOCKER_COMP) exec php npm install
npm-run: ## Run the dev server
@$(DOCKER_COMP) exec php npm run dev
npm-watch: ## Watch for changes
@$(DOCKER_COMP) exec php npm run watch

14
assets/app.js Normal file
View File

@@ -0,0 +1,14 @@
/*
* Welcome to your app's main JavaScript file!
*
* We recommend including the built version of this JavaScript file
* (and its CSS file) in your base layout (base.html.twig).
*/
// any CSS you import will output into a single css file (app.css in this case)
import './styles/app.scss';
// start the Stimulus application
import './bootstrap';
import 'tw-elements';

11
assets/bootstrap.js vendored Normal file
View File

@@ -0,0 +1,11 @@
import { startStimulusApp } from '@symfony/stimulus-bridge';
// Registers Stimulus controllers from controllers.json and in the controllers/ directory
export const app = startStimulusApp(require.context(
'@symfony/stimulus-bridge/lazy-controller-loader!./controllers',
true,
/\.[jt]sx?$/
));
// register any custom, 3rd party controllers here
// app.register('some_controller_name', SomeImportedController);

4
assets/controllers.json Normal file
View File

@@ -0,0 +1,4 @@
{
"controllers": [],
"entrypoints": []
}

View File

@@ -0,0 +1,16 @@
import { Controller } from '@hotwired/stimulus';
/*
* This is an example Stimulus controller!
*
* Any element with a data-controller="hello" attribute will cause
* this controller to be executed. The name "hello" comes from the filename:
* hello_controller.js -> "hello"
*
* Delete this file or adapt it for your use!
*/
export default class extends Controller {
connect() {
this.element.textContent = 'Hello Stimulus! Edit me in assets/controllers/hello_controller.js';
}
}

View File

@@ -0,0 +1,12 @@
// assets/controllers/menu_controller.js
import { Controller } from '@hotwired/stimulus';
export default class extends Controller {
static targets = ['menu'];
toggleMenu(event) {
this.menuTargets.forEach(menu => {
menu.classList.toggle('hidden', menu !== event.currentTarget);
});
}
}

3
assets/styles/app.css Normal file
View File

@@ -0,0 +1,3 @@
body {
background-color: lightgray;
}

7
assets/styles/app.scss Normal file
View File

@@ -0,0 +1,7 @@
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
body {
background-color: lightgray;
}

View File

@@ -35,6 +35,7 @@
"symfony/serializer": "7.0.*", "symfony/serializer": "7.0.*",
"symfony/twig-bundle": "7.0.*", "symfony/twig-bundle": "7.0.*",
"symfony/validator": "7.0.*", "symfony/validator": "7.0.*",
"symfony/webpack-encore-bundle": "^2.1",
"symfony/yaml": "7.0.*" "symfony/yaml": "7.0.*"
}, },
"config": { "config": {

73
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "7f30c3ed2e16470ab82ad4fd0ca8b987", "content-hash": "721e53091aa5df1279e1b346d6a8e9b7",
"packages": [ "packages": [
{ {
"name": "api-platform/core", "name": "api-platform/core",
@@ -6718,6 +6718,77 @@
], ],
"time": "2024-01-23T15:02:46+00:00" "time": "2024-01-23T15:02:46+00:00"
}, },
{
"name": "symfony/webpack-encore-bundle",
"version": "v2.1.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/webpack-encore-bundle.git",
"reference": "75cb918df3f65e28cf0d4bc03042bc45ccb19dd0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/webpack-encore-bundle/zipball/75cb918df3f65e28cf0d4bc03042bc45ccb19dd0",
"reference": "75cb918df3f65e28cf0d4bc03042bc45ccb19dd0",
"shasum": ""
},
"require": {
"php": ">=8.1.0",
"symfony/asset": "^5.4 || ^6.2 || ^7.0",
"symfony/config": "^5.4 || ^6.2 || ^7.0",
"symfony/dependency-injection": "^5.4 || ^6.2 || ^7.0",
"symfony/http-kernel": "^5.4 || ^6.2 || ^7.0",
"symfony/service-contracts": "^1.1.9 || ^2.1.3 || ^3.0"
},
"require-dev": {
"symfony/framework-bundle": "^5.4 || ^6.2 || ^7.0",
"symfony/phpunit-bridge": "^5.4 || ^6.2 || ^7.0",
"symfony/twig-bundle": "^5.4 || ^6.2 || ^7.0",
"symfony/web-link": "^5.4 || ^6.2 || ^7.0"
},
"type": "symfony-bundle",
"extra": {
"thanks": {
"name": "symfony/webpack-encore",
"url": "https://github.com/symfony/webpack-encore"
}
},
"autoload": {
"psr-4": {
"Symfony\\WebpackEncoreBundle\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Integration with your Symfony app & Webpack Encore!",
"support": {
"issues": "https://github.com/symfony/webpack-encore-bundle/issues",
"source": "https://github.com/symfony/webpack-encore-bundle/tree/v2.1.1"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2023-10-22T18:53:08+00:00"
},
{ {
"name": "symfony/yaml", "name": "symfony/yaml",
"version": "v7.0.0", "version": "v7.0.0",

View File

@@ -13,4 +13,5 @@ return [
Zenstruck\Foundry\ZenstruckFoundryBundle::class => ['dev' => true, 'test' => true], Zenstruck\Foundry\ZenstruckFoundryBundle::class => ['dev' => true, 'test' => true],
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true], Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true], Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\WebpackEncoreBundle\WebpackEncoreBundle::class => ['all' => true],
]; ];

View File

@@ -0,0 +1,45 @@
webpack_encore:
# The path where Encore is building the assets - i.e. Encore.setOutputPath()
output_path: '%kernel.project_dir%/public/build'
# If multiple builds are defined (as shown below), you can disable the default build:
# output_path: false
# Set attributes that will be rendered on all script and link tags
script_attributes:
defer: true
# Uncomment (also under link_attributes) if using Turbo Drive
# https://turbo.hotwired.dev/handbook/drive#reloading-when-assets-change
# 'data-turbo-track': reload
# link_attributes:
# Uncomment if using Turbo Drive
# 'data-turbo-track': reload
# If using Encore.enableIntegrityHashes() and need the crossorigin attribute (default: false, or use 'anonymous' or 'use-credentials')
# crossorigin: 'anonymous'
# Preload all rendered script and link tags automatically via the HTTP/2 Link header
# preload: true
# Throw an exception if the entrypoints.json file is missing or an entry is missing from the data
# strict_mode: false
# If you have multiple builds:
# builds:
# frontend: '%kernel.project_dir%/public/frontend/build'
# pass the build name as the 3rd argument to the Twig functions
# {{ encore_entry_script_tags('entry1', null, 'frontend') }}
framework:
assets:
json_manifest_path: '%kernel.project_dir%/public/build/manifest.json'
#when@prod:
# webpack_encore:
# # Cache the entrypoints.json (rebuild Symfony's cache when entrypoints.json changes)
# # Available in version 1.2
# cache: true
#when@test:
# webpack_encore:
# strict_mode: false

View File

@@ -39,3 +39,19 @@ services:
referer: true referer: true
protocols: [ 'http', 'https' ] protocols: [ 'http', 'https' ]
track_redirects: true track_redirects: true
App\Service\MangaScraperService:
arguments:
$projectDir: '%kernel.project_dir%'
App\Service\MangaExportService:
arguments:
$projectDir: '%kernel.project_dir%'
App\EventListener\MangaScrapedListener:
tags:
- { name: kernel.event_listener, event: 'manga.scraped', method: 'onMangaScraped' }
App\Controller\MenuController:
tags: [ 'controller.service_arguments' ]

View File

@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240603161848 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SEQUENCE api_token_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE chapter_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE manga_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE page_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE source_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE SEQUENCE "user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE api_token (id INT NOT NULL, owned_by_id INT NOT NULL, expires_at TIMESTAMP(0) WITHOUT TIME ZONE DEFAULT NULL, token VARCHAR(68) NOT NULL, scopes JSON NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_7BA2F5EB5E70BCD7 ON api_token (owned_by_id)');
$this->addSql('COMMENT ON COLUMN api_token.expires_at IS \'(DC2Type:datetime_immutable)\'');
$this->addSql('CREATE TABLE chapter (id INT NOT NULL, manga_id INT NOT NULL, number DOUBLE PRECISION NOT NULL, pages JSON NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_F981B52E7B6461 ON chapter (manga_id)');
$this->addSql('CREATE TABLE manga (id INT NOT NULL, title VARCHAR(255) NOT NULL, slug VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE TABLE page (id INT NOT NULL, chapter_id INT NOT NULL, number INT NOT NULL, image_url VARCHAR(255) NOT NULL, image_local_url VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_140AB620579F4768 ON page (chapter_id)');
$this->addSql('CREATE TABLE source (id INT NOT NULL, name VARCHAR(255) DEFAULT NULL, description TEXT DEFAULT NULL, base_url VARCHAR(255) NOT NULL, scrapping_parameters JSON DEFAULT NULL, is_active BOOLEAN NOT NULL, created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))');
$this->addSql('COMMENT ON COLUMN source.created_at IS \'(DC2Type:datetime_immutable)\'');
$this->addSql('COMMENT ON COLUMN source.updated_at IS \'(DC2Type:datetime_immutable)\'');
$this->addSql('CREATE TABLE "user" (id INT NOT NULL, email VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D649E7927C74 ON "user" (email)');
$this->addSql('ALTER TABLE api_token ADD CONSTRAINT FK_7BA2F5EB5E70BCD7 FOREIGN KEY (owned_by_id) REFERENCES "user" (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE chapter ADD CONSTRAINT FK_F981B52E7B6461 FOREIGN KEY (manga_id) REFERENCES manga (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE page ADD CONSTRAINT FK_140AB620579F4768 FOREIGN KEY (chapter_id) REFERENCES chapter (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
$this->addSql('DROP SEQUENCE api_token_id_seq CASCADE');
$this->addSql('DROP SEQUENCE chapter_id_seq CASCADE');
$this->addSql('DROP SEQUENCE manga_id_seq CASCADE');
$this->addSql('DROP SEQUENCE page_id_seq CASCADE');
$this->addSql('DROP SEQUENCE source_id_seq CASCADE');
$this->addSql('DROP SEQUENCE "user_id_seq" CASCADE');
$this->addSql('ALTER TABLE api_token DROP CONSTRAINT FK_7BA2F5EB5E70BCD7');
$this->addSql('ALTER TABLE chapter DROP CONSTRAINT FK_F981B52E7B6461');
$this->addSql('ALTER TABLE page DROP CONSTRAINT FK_140AB620579F4768');
$this->addSql('DROP TABLE api_token');
$this->addSql('DROP TABLE chapter');
$this->addSql('DROP TABLE manga');
$this->addSql('DROP TABLE page');
$this->addSql('DROP TABLE source');
$this->addSql('DROP TABLE "user"');
}
}

9463
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

32
package.json Normal file
View File

@@ -0,0 +1,32 @@
{
"devDependencies": {
"@babel/core": "^7.17.0",
"@babel/preset-env": "^7.16.0",
"@hotwired/stimulus": "^3.0.0",
"@symfony/stimulus-bridge": "^3.2.0",
"@symfony/webpack-encore": "^4.0.0",
"core-js": "^3.23.0",
"daisyui": "^4.4.2",
"regenerator-runtime": "^0.13.9",
"sass": "^1.59.3",
"sass-loader": "^13.2.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-notifier": "^1.15.0"
},
"license": "UNLICENSED",
"private": true,
"scripts": {
"dev-server": "encore dev-server",
"dev": "encore dev",
"watch": "encore dev --watch",
"build": "encore production --progress"
},
"dependencies": {
"alpinejs": "^3.13.3",
"autoprefixer": "^10.4.14",
"postcss-loader": "^7.1.0",
"tailwindcss": "^3.2.7",
"tw-elements": "^1.0.0-beta1"
}
}

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
}

View File

@@ -0,0 +1,209 @@
<?php
namespace App\Controller;
use App\Entity\Manga;
use App\Repository\MangaRepository;
use App\Service\MangaExportService;
use App\Service\LelScansProviderService;
use App\Service\MangaScraperService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\AsciiSlugger;
class MangaController extends AbstractController
{
private MangaScraperService $mangaScraperService;
private MangaExportService $mangaExportService;
private LelScansProviderService $mangaProviderService;
private MangaRepository $mangaRepository;
public function __construct(MangaScraperService $mangaScraperService, MangaExportService $mangaExportService, LelScansProviderService $mangaProviderService, MangaRepository $mangaRepository)
{
$this->mangaScraperService = $mangaScraperService;
$this->mangaExportService = $mangaExportService;
$this->mangaProviderService = $mangaProviderService;
$this->mangaRepository = $mangaRepository;
}
#[Route('/manga', name: 'app_manga')]
public function index(): Response
{
// $this->breadcrumbs->addItem("Accueil", $this->generateUrl("app_manga"));
// $this->breadcrumbs->addItem("Mangas", $this->generateUrl("manga_show"));
$mangas = $this->mangaRepository->findAll();
return $this->render('manga/index.html.twig', [
'controller_name' => 'MangaController',
'mangas' => $mangas,
]);
}
#[Route('/manga/{mangaSlug}', name: 'manga_show')]
public function showChapters(string $mangaSlug): Response
{
$manga = $this->mangaRepository->findOneBy(['slug' => $mangaSlug]);
if (!$manga) {
$manga = new Manga();
$manga->setSlug($mangaSlug);
$manga->setTitle($this->slugToTitle($mangaSlug));
$this->mangaRepository->save($manga, true);
}
$availableChapters = $this->mangaProviderService->getChapterList($mangaSlug);
return $this->render('manga/show_chapters.html.twig', [
'controller_name' => 'MangaController',
'manga' => $manga,
'availableChapters' => $availableChapters,
]);
}
#[Route('/manga/{mangaSlug}/{chapterNumber}/{pageNumber}', name: 'read_chapter_page')]
public function readChapterPage(string $mangaSlug, float $chapterNumber, int $pageNumber = 0): Response
{
$manga = $this->mangaRepository->findOneBy(['slug' => $mangaSlug]);
if (!$manga) {
throw $this->createNotFoundException("Le manga demandé n'existe pas.");
}
$chapter = $manga->getChapterByNumber($chapterNumber);
if (!$chapter) {
throw $this->createNotFoundException("Le chapitre demandé n'existe pas.");
}
$currentPage = $chapter->getPageByNumber($pageNumber);
if (!$currentPage) {
throw $this->createNotFoundException("La page demandée n'existe pas.");
}
return $this->render('manga/manga_reader.html.twig', [
'manga' => $manga,
'chapter' => $chapter,
'pages' => $chapter->getPagesLink(),
'currentPage' => $currentPage,
]);
}
#[Route('/manga/{mangaSlug}/chapter/{chapterNumber}/download', name: 'download_chapter')]
public function downloadChapter(string $mangaSlug, float $chapterNumber): BinaryFileResponse
{
$response = $this->mangaExportService->downloadCbz($this->slugToTitle($mangaSlug), $chapterNumber);
if($response === false){
throw $this->createNotFoundException("Le chapitre demandé n'existe pas.");
}
// Définir les en-têtes pour le téléchargement
$response->headers->set('Content-Type', 'application/x-cbz');
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
"{$mangaSlug}_{$chapterNumber}.cbz"
);
return $response;
}
#[Route('/scrape', name: 'manga_scrape', methods: 'POST')]
public function scrapeByMangaAndChapter(Request $request): Response
{
$mangaSlug = $request->request->get('mangaSlug');
$chapterNumber = $request->request->get('chapterNumber');
$response = $this->scrapeChapter($mangaSlug, $chapterNumber);
$manga = $this->mangaRepository->findOneBy(['slug' => $mangaSlug]);
$availableChapters = $this->mangaProviderService->getChapterList($mangaSlug);
return $this->render('manga/show_chapters.html.twig', [
'controller_name' => 'MangaController',
'manga' => $manga,
'availableChapters' => $availableChapters,
]);
}
#[Route('/scrapeFrom', name: 'manga_scrape_from_chapter', methods: 'POST')]
public function scrapeByMangaFromChapter(Request $request): Response
{
$mangaSlug = $request->request->get('mangaSlug');
$chapterNumber = $request->request->get('chapterNumber');
do{
$response = $this->scrapeChapter($mangaSlug, $chapterNumber);
$chapterNumber++;
}while($response !== false);
$availableChapters = $this->mangaProviderService->getChapterList($mangaSlug);
return $this->redirectToRoute('manga_show', ['mangaSlug' => $mangaSlug, 'availableChapters' => $availableChapters]);
}
#[Route('/manga/exportFrom/{mangaSlug}/{chapterNumber}', name: 'manga_export')]
public function exportMangaCbz(string $mangaSlug, float $chapterNumber)
{
$response = $this->exportCbz($this->slugToTitle($mangaSlug), $chapterNumber);
dd($response);
}
#[Route('/getList', name: 'get_manga_list')]
public function getMangaList()
{
$list = $this->mangaProviderService->getMangaList();
}
private function scrapeChapter(string $mangaSlug, float $chapterNumber): array|bool
{
$url = 'https://lelscans.net/scan-' . $mangaSlug . '/' . $chapterNumber;
$manga = $this->mangaRepository->findOneBy(['slug' => $mangaSlug]);
if(!is_null($manga)){
$scrapedManga = $this->mangaScraperService->scrapeMangaChapter($url, $manga->getTitle(), $chapterNumber);
}else{
$title = $this->slugToTitle($mangaSlug);
$manga = new Manga();
$manga->setTitle($title);
$manga->setSlug($mangaSlug);
$this->mangaRepository->save($manga);
$scrapedManga = $this->mangaScraperService->scrapeMangaChapter($url, $title, $chapterNumber);
}
return $scrapedManga;
}
private function exportCbz(string $mangaSlug, float $chapterNumber):array
{
$exported = [];
do{
$response = $this->mangaExportService->exportMangaChapter($mangaSlug, $chapterNumber);
if($response === 'already_exported'){
$exported[] = $mangaSlug . ' - ' . $chapterNumber . ' ' . $response;
}elseif($response === true){
$exported[] = $mangaSlug . ' - ' . $chapterNumber . ' exported';
}else{
$exported[] = $mangaSlug . ' - ' . $chapterNumber . ' something went wrong';
}
$chapterNumber++;
}while($response !== false);
return $exported;
}
private function slugToTitle(string $slug): string
{
$slugger = new AsciiSlugger();
$title = $slugger->slug($slug)->replace('-', ' ')->title(true)->toString();
return $title;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Controller;
use App\Repository\MangaRepository;
use App\Service\LelScansProviderService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\String\Slugger\AsciiSlugger;
class MenuController extends AbstractController
{
private MangaRepository $mangaRepository;
private LelScansProviderService $mangaProviderService;
public function __construct(MangaRepository $mangaRepository, LelScansProviderService $mangaProviderService)
{
$this->mangaRepository = $mangaRepository;
$this->mangaProviderService = $mangaProviderService;
}
public function menu(): Response
{
$availableManga = $this->mangaProviderService->getMangaList();
foreach($availableManga as $key => $manga) {
$availableManga[$key]['slug'] = $this->titleToSlug($manga['name']);
}
$mangas = $this->mangaRepository->findAll();
return $this->render('menu/menu.html.twig', [
'availableManga' => $availableManga,
'mangas' => $mangas,
]);
}
private function slugToTitle(string $slug): string
{
$slugger = new AsciiSlugger();
return $slugger->slug($slug)->replace('-', ' ')->title(true)->toString();
}
private function titleToSlug(string $title): string
{
$slugger = new AsciiSlugger();
return $slugger->slug($title)->lower()->toString();
}
}

View File

@@ -3,6 +3,9 @@
namespace App\DataFixtures; namespace App\DataFixtures;
use App\Factory\ApiTokenFactory; use App\Factory\ApiTokenFactory;
use App\Factory\ChapterFactory;
use App\Factory\MangaFactory;
use App\Factory\PageFactory;
use App\Factory\UserFactory; use App\Factory\UserFactory;
use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager; use Doctrine\Persistence\ObjectManager;
@@ -11,6 +14,32 @@ class AppFixtures extends Fixture
{ {
public function load(ObjectManager $manager): void public function load(ObjectManager $manager): void
{ {
UserFactory::createMany(20);
ApiTokenFactory::createMany(60, function () {
return [
'ownedBy' => UserFactory::random()
];
});
$mangas = MangaFactory::createMany(5);
foreach ($mangas as $manga) {
for ($i = 1; $i <= 10; $i++) {
$manga->addChapter(ChapterFactory::createOne([
'manga' => $manga,
'number' => $i
])->object());
}
foreach ($manga->getChapters() as $chapter) {
for ($i = 1; $i <= 15; $i++) {
$chapter->addPagesLink(PageFactory::createOne([
'chapter' => $chapter,
'number' => $i
])->object());
}
}
}
} }
} }

View File

@@ -10,7 +10,7 @@ use Random\RandomException;
class ApiToken class ApiToken
{ {
private const string PERSONAL_ACCESS_TOKEN_PREFIX = 'ipm_'; private const string PERSONAL_ACCESS_TOKEN_PREFIX = 'mgr_';
public const string SCOPE_USER_EDIT = 'ROLE_USER_EDIT'; public const string SCOPE_USER_EDIT = 'ROLE_USER_EDIT';
public const string SCOPE_PROJECT_CREATE = 'ROLE_PROJECT_CREATE'; public const string SCOPE_PROJECT_CREATE = 'ROLE_PROJECT_CREATE';
public const string SCOPE_PROJECT_EDIT = 'ROLE_PROJECT_EDIT'; public const string SCOPE_PROJECT_EDIT = 'ROLE_PROJECT_EDIT';

120
src/Entity/Chapter.php Normal file
View File

@@ -0,0 +1,120 @@
<?php
namespace App\Entity;
use App\Repository\ChapterRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ChapterRepository::class)]
class Chapter
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column]
private ?float $number = null;
#[ORM\Column]
private array $pages = [];
#[ORM\ManyToOne(inversedBy: 'chapters')]
#[ORM\JoinColumn(nullable: false)]
private ?Manga $manga = null;
#[ORM\OneToMany(mappedBy: 'chapter', targetEntity: Page::class, orphanRemoval: true)]
private Collection $pagesLink;
public function __construct()
{
$this->pagesLink = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNumber(): ?float
{
return $this->number;
}
public function setNumber(float $number): self
{
$this->number = $number;
return $this;
}
public function getPages(): array
{
return $this->pages;
}
public function setPages(array $pages): self
{
$this->pages = $pages;
return $this;
}
public function getManga(): ?Manga
{
return $this->manga;
}
public function setManga(?Manga $manga): self
{
$this->manga = $manga;
return $this;
}
/**
* @return Collection<int, Page>
*/
public function getPagesLink(): Collection
{
return $this->pagesLink;
}
public function addPagesLink(Page $pagesLink): self
{
if (!$this->pagesLink->contains($pagesLink)) {
$this->pagesLink->add($pagesLink);
$pagesLink->setChapter($this);
}
return $this;
}
public function removePagesLink(Page $pagesLink): self
{
if ($this->pagesLink->removeElement($pagesLink)) {
// set the owning side to null (unless already changed)
if ($pagesLink->getChapter() === $this) {
$pagesLink->setChapter(null);
}
}
return $this;
}
public function getPageByNumber(int $number): ?Page
{
/**
* @var Page $page
*/
foreach ($this->pagesLink as $page) {
if ($page->getNumber() === $number) {
return $page;
}
}
return null;
}
}

100
src/Entity/Manga.php Normal file
View File

@@ -0,0 +1,100 @@
<?php
namespace App\Entity;
use App\Repository\MangaRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: MangaRepository::class)]
class Manga
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $title = null;
#[ORM\OneToMany(mappedBy: 'manga', targetEntity: Chapter::class, orphanRemoval: true)]
private Collection $chapters;
#[ORM\Column(length: 255)]
private ?string $slug = null;
public function __construct()
{
$this->chapters = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
/**
* @return Collection<int, Chapter>
*/
public function getChapters(): Collection
{
return $this->chapters;
}
public function getChapterByNumber(float $number): ?Chapter
{
foreach ($this->chapters as $chapter) {
if ($chapter->getNumber() === $number) {
return $chapter;
}
}
return null;
}
public function addChapter(Chapter $chapter): self
{
if (!$this->chapters->contains($chapter)) {
$this->chapters->add($chapter);
$chapter->setManga($this);
}
return $this;
}
public function removeChapter(Chapter $chapter): self
{
if ($this->chapters->removeElement($chapter)) {
// set the owning side to null (unless already changed)
if ($chapter->getManga() === $this) {
$chapter->setManga(null);
}
}
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
}

81
src/Entity/Page.php Normal file
View File

@@ -0,0 +1,81 @@
<?php
namespace App\Entity;
use App\Repository\PageRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: PageRepository::class)]
class Page
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column]
private ?int $number = null;
#[ORM\Column(length: 255)]
private ?string $imageUrl = null;
#[ORM\ManyToOne(inversedBy: 'pagesLink')]
#[ORM\JoinColumn(nullable: false)]
private ?Chapter $chapter = null;
#[ORM\Column(length: 255)]
private ?string $imageLocalUrl = null;
public function getId(): ?int
{
return $this->id;
}
public function getNumber(): ?int
{
return $this->number;
}
public function setNumber(int $number): self
{
$this->number = $number;
return $this;
}
public function getImageUrl(): ?string
{
return $this->imageUrl;
}
public function setImageUrl(string $imageUrl): self
{
$this->imageUrl = $imageUrl;
return $this;
}
public function getChapter(): ?Chapter
{
return $this->chapter;
}
public function setChapter(?Chapter $chapter): self
{
$this->chapter = $chapter;
return $this;
}
public function getImageLocalUrl(): ?string
{
return $this->imageLocalUrl;
}
public function setImageLocalUrl(string $imageLocalUrl): self
{
$this->imageLocalUrl = $imageLocalUrl;
return $this;
}
}

126
src/Entity/Source.php Normal file
View File

@@ -0,0 +1,126 @@
<?php
namespace App\Entity;
use App\Repository\SourceRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SourceRepository::class)]
class Source
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $name = null;
#[ORM\Column(type: Types::TEXT, nullable: true)]
private ?string $description = null;
#[ORM\Column(length: 255)]
private ?string $baseUrl = null;
#[ORM\Column(nullable: true)]
private array $scrappingParameters = [];
#[ORM\Column]
private ?bool $isActive = null;
#[ORM\Column]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column]
private ?\DateTimeImmutable $updatedAt = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getBaseUrl(): ?string
{
return $this->baseUrl;
}
public function setBaseUrl(string $baseUrl): self
{
$this->baseUrl = $baseUrl;
return $this;
}
public function getScrappingParameters(): array
{
return $this->scrappingParameters;
}
public function setScrappingParameters(?array $scrappingParameters): self
{
$this->scrappingParameters = $scrappingParameters;
return $this;
}
public function isIsActive(): ?bool
{
return $this->isActive;
}
public function setIsActive(bool $isActive): self
{
$this->isActive = $isActive;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
public function setUpdatedAt(\DateTimeImmutable $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace App\EventListener;
use App\Entity\Chapter;
use App\Entity\Manga;
use App\Entity\Page;
use App\Event\MangaScrapedEvent;
use Doctrine\ORM\EntityManagerInterface;
class MangaScrapedListener
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function onMangaScraped(MangaScrapedEvent $event): void
{
$mangaData = $event->getMangaData();
$manga = $this->entityManager->getRepository(Manga::class)->findOneBy(['title' => $mangaData['title']]);
if (!$manga) {
$manga = new Manga();
$manga->setTitle($mangaData['title']);
$this->entityManager->persist($manga);
}
$chapter = $manga->getChapterByNumber($mangaData['chapter']);
if (!$chapter) {
$chapter = (new Chapter())
->setNumber($mangaData['chapter']);
$manga->addChapter($chapter);
$this->entityManager->persist($chapter);
$this->entityManager->persist($manga);
}
foreach ($mangaData['pages'] as $pageData) {
$page = $chapter->getPageByNumber($pageData['page_number']);
if (!$page) {
$page = (new Page())
->setNumber($pageData['page_number'])
->setImageUrl($pageData['image_url'])
->setImageLocalUrl($pageData['local_image_url']);
$chapter->addPagesLink($page);
$this->entityManager->persist($chapter);
$this->entityManager->persist($page);
}
}
$this->entityManager->flush();
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\EventSubscriber;
use Symfony\Contracts\EventDispatcher\Event;
class MangaScrapedEvent extends Event
{
public const NAME = 'manga.scraped';
private string $mangaTitle;
private float $chapterNumber;
private array $pagesData;
public function __construct(string $mangaTitle, float $chapterNumber, array $pagesData)
{
$this->mangaTitle = $mangaTitle;
$this->chapterNumber = $chapterNumber;
$this->pagesData = $pagesData;
}
public function getMangaData(): array
{
return [
'title' => $this->mangaTitle,
'chapter' => $this->chapterNumber,
'pages' => $this->pagesData
];
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace App\Factory;
use App\Entity\Chapter;
use App\Repository\ChapterRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
use Zenstruck\Foundry\RepositoryProxy;
/**
* @extends ModelFactory<Chapter>
*
* @method Chapter|Proxy create(array|callable $attributes = [])
* @method static Chapter|Proxy createOne(array $attributes = [])
* @method static Chapter|Proxy find(object|array|mixed $criteria)
* @method static Chapter|Proxy findOrCreate(array $attributes)
* @method static Chapter|Proxy first(string $sortedField = 'id')
* @method static Chapter|Proxy last(string $sortedField = 'id')
* @method static Chapter|Proxy random(array $attributes = [])
* @method static Chapter|Proxy randomOrCreate(array $attributes = [])
* @method static ChapterRepository|RepositoryProxy repository()
* @method static Chapter[]|Proxy[] all()
* @method static Chapter[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static Chapter[]|Proxy[] createSequence(iterable|callable $sequence)
* @method static Chapter[]|Proxy[] findBy(array $attributes)
* @method static Chapter[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
* @method static Chapter[]|Proxy[] randomSet(int $number, array $attributes = [])
*/
final class ChapterFactory extends ModelFactory
{
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services
*
* @todo inject services if required
*/
public function __construct()
{
parent::__construct();
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories
*
* @todo add your default values here
*/
protected function getDefaults(): array
{
return [
'manga' => MangaFactory::new(),
'number' => self::faker()->randomNumber(2),
'pages' => [],
];
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
*/
protected function initialize(): self
{
return $this
// ->afterInstantiate(function(Chapter $chapter): void {})
;
}
protected static function getClass(): string
{
return Chapter::class;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Factory;
use App\Entity\Manga;
use App\Repository\MangaRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
use Zenstruck\Foundry\RepositoryProxy;
/**
* @extends ModelFactory<Manga>
*
* @method Manga|Proxy create(array|callable $attributes = [])
* @method static Manga|Proxy createOne(array $attributes = [])
* @method static Manga|Proxy find(object|array|mixed $criteria)
* @method static Manga|Proxy findOrCreate(array $attributes)
* @method static Manga|Proxy first(string $sortedField = 'id')
* @method static Manga|Proxy last(string $sortedField = 'id')
* @method static Manga|Proxy random(array $attributes = [])
* @method static Manga|Proxy randomOrCreate(array $attributes = [])
* @method static MangaRepository|RepositoryProxy repository()
* @method static Manga[]|Proxy[] all()
* @method static Manga[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static Manga[]|Proxy[] createSequence(iterable|callable $sequence)
* @method static Manga[]|Proxy[] findBy(array $attributes)
* @method static Manga[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
* @method static Manga[]|Proxy[] randomSet(int $number, array $attributes = [])
*/
final class MangaFactory extends ModelFactory
{
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services
*
* @todo inject services if required
*/
public function __construct()
{
parent::__construct();
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories
*
* @todo add your default values here
*/
protected function getDefaults(): array
{
return [
'slug' => self::faker()->text(255),
'title' => self::faker()->text(255),
];
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
*/
protected function initialize(): self
{
return $this
// ->afterInstantiate(function(Manga $manga): void {})
;
}
protected static function getClass(): string
{
return Manga::class;
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace App\Factory;
use App\Entity\Page;
use App\Repository\PageRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
use Zenstruck\Foundry\RepositoryProxy;
/**
* @extends ModelFactory<Page>
*
* @method Page|Proxy create(array|callable $attributes = [])
* @method static Page|Proxy createOne(array $attributes = [])
* @method static Page|Proxy find(object|array|mixed $criteria)
* @method static Page|Proxy findOrCreate(array $attributes)
* @method static Page|Proxy first(string $sortedField = 'id')
* @method static Page|Proxy last(string $sortedField = 'id')
* @method static Page|Proxy random(array $attributes = [])
* @method static Page|Proxy randomOrCreate(array $attributes = [])
* @method static PageRepository|RepositoryProxy repository()
* @method static Page[]|Proxy[] all()
* @method static Page[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static Page[]|Proxy[] createSequence(iterable|callable $sequence)
* @method static Page[]|Proxy[] findBy(array $attributes)
* @method static Page[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
* @method static Page[]|Proxy[] randomSet(int $number, array $attributes = [])
*/
final class PageFactory extends ModelFactory
{
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services
*
* @todo inject services if required
*/
public function __construct()
{
parent::__construct();
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories
*
* @todo add your default values here
*/
protected function getDefaults(): array
{
return [
'chapter' => ChapterFactory::new(),
'imageLocalUrl' => self::faker()->text(255),
'imageUrl' => self::faker()->text(255),
'number' => self::faker()->randomNumber(2),
];
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
*/
protected function initialize(): self
{
return $this
// ->afterInstantiate(function(Page $page): void {})
;
}
protected static function getClass(): string
{
return Page::class;
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace App\Factory;
use App\Entity\Source;
use App\Repository\SourceRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
use Zenstruck\Foundry\RepositoryProxy;
/**
* @extends ModelFactory<Source>
*
* @method Source|Proxy create(array|callable $attributes = [])
* @method static Source|Proxy createOne(array $attributes = [])
* @method static Source|Proxy find(object|array|mixed $criteria)
* @method static Source|Proxy findOrCreate(array $attributes)
* @method static Source|Proxy first(string $sortedField = 'id')
* @method static Source|Proxy last(string $sortedField = 'id')
* @method static Source|Proxy random(array $attributes = [])
* @method static Source|Proxy randomOrCreate(array $attributes = [])
* @method static SourceRepository|RepositoryProxy repository()
* @method static Source[]|Proxy[] all()
* @method static Source[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static Source[]|Proxy[] createSequence(iterable|callable $sequence)
* @method static Source[]|Proxy[] findBy(array $attributes)
* @method static Source[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
* @method static Source[]|Proxy[] randomSet(int $number, array $attributes = [])
*/
final class SourceFactory extends ModelFactory
{
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#factories-as-services
*
* @todo inject services if required
*/
public function __construct()
{
parent::__construct();
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#model-factories
*
* @todo add your default values here
*/
protected function getDefaults(): array
{
return [
'baseUrl' => self::faker()->text(255),
'createdAt' => \DateTimeImmutable::createFromMutable(self::faker()->dateTime()),
'isActive' => self::faker()->boolean(),
'updatedAt' => \DateTimeImmutable::createFromMutable(self::faker()->dateTime()),
];
}
/**
* @see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#initialization
*/
protected function initialize(): self
{
return $this
// ->afterInstantiate(function(Source $source): void {})
;
}
protected static function getClass(): string
{
return Source::class;
}
}

View File

@@ -54,7 +54,6 @@ final class UserFactory extends ModelFactory
'roles' => [], 'roles' => [],
'firstName' => self::faker()->randomElement(self::FIRST_NAMES), 'firstName' => self::faker()->randomElement(self::FIRST_NAMES),
'lastName' => self::faker()->randomElement(self::LAST_NAMES), 'lastName' => self::faker()->randomElement(self::LAST_NAMES),
'company' => CompanyFactory::randomOrCreate(),
]; ];
} }

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Repository;
use App\Entity\Chapter;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Chapter>
*
* @method Chapter|null find($id, $lockMode = null, $lockVersion = null)
* @method Chapter|null findOneBy(array $criteria, array $orderBy = null)
* @method Chapter[] findAll()
* @method Chapter[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ChapterRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Chapter::class);
}
public function save(Chapter $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Chapter $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
// /**
// * @return Chapter[] Returns an array of Chapter objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('c')
// ->andWhere('c.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('c.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Chapter
// {
// return $this->createQueryBuilder('c')
// ->andWhere('c.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Repository;
use App\Entity\Manga;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Manga>
*
* @method Manga|null find($id, $lockMode = null, $lockVersion = null)
* @method Manga|null findOneBy(array $criteria, array $orderBy = null)
* @method Manga[] findAll()
* @method Manga[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class MangaRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Manga::class);
}
public function save(Manga $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Manga $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
// /**
// * @return Manga[] Returns an array of Manga objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('m')
// ->andWhere('m.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('m.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Manga
// {
// return $this->createQueryBuilder('m')
// ->andWhere('m.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Repository;
use App\Entity\Page;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Page>
*
* @method Page|null find($id, $lockMode = null, $lockVersion = null)
* @method Page|null findOneBy(array $criteria, array $orderBy = null)
* @method Page[] findAll()
* @method Page[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PageRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Page::class);
}
public function save(Page $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Page $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
// /**
// * @return Page[] Returns an array of Page objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('p.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Page
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Repository;
use App\Entity\Source;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Source>
*
* @method Source|null find($id, $lockMode = null, $lockVersion = null)
* @method Source|null findOneBy(array $criteria, array $orderBy = null)
* @method Source[] findAll()
* @method Source[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class SourceRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Source::class);
}
public function save(Source $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Source $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
// /**
// * @return Source[] Returns an array of Source objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('s')
// ->andWhere('s.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('s.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Source
// {
// return $this->createQueryBuilder('s')
// ->andWhere('s.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Service;
use Symfony\Component\BrowserKit\HttpBrowser as Client;
use Symfony\Component\DomCrawler\Crawler;
class LelScansProviderService implements MangaProviderInterface
{
const PROVIDER_URL = 'https://lelscans.net/';
const MANGA_SLUG = '/{manga}/{chapter}/{page}';
private Client $client;
public function __construct()
{
$this->client = new Client();
}
public function getMangaList(): array
{
$crawler = $this->client->request('GET', self::PROVIDER_URL);
$mangaList = [];
$crawler->filter('select > option')->each(function (Crawler $node) use (&$mangaList) {
$mangaName = $node->text();
$mangaUrl = $node->attr('value');
if ($mangaName && $mangaUrl && !preg_match('/^\d+(\.\d+)?$/', $mangaName)) {
$mangaList[] = [
'name' => $mangaName,
'url' => $mangaUrl,
];
}
});
return $mangaList;
}
public function getChapterList($mangaSlug): array
{
$crawler = $this->client->request('GET', self::PROVIDER_URL . 'lecture-en-ligne-' . $mangaSlug . '.php');
$chapterList = [];
$crawler->filter('select > option')->each(function (Crawler $node) use (&$chapterList) {
$chapterName = $node->text();
$chapterUrl = $node->attr('value');
if ($chapterName && $chapterUrl && preg_match('/^\d+(\.\d+)?$/', $chapterName)) {
$chapterList[] = [
'number' => $chapterName,
];
}
});
return $chapterList;
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace App\Service;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use ZipArchive;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class MangaExportService
{
const IMG_BASE_DIR = '/public/manga-images';
const EXPORT_BASE_DIR = '/public/manga-export';
private string $projectDir;
public function __construct($projectDir)
{
$this->projectDir = $projectDir;
}
public function exportMangaChapter(string $mangaTitle, int $chapterNumber): bool|string
{
$chapterDir = $this->getMangaDir($mangaTitle, $chapterNumber);
$cbzFilePath = $this->getExportDir($mangaTitle, $chapterNumber);
if(!is_dir($chapterDir)){
return false;
}
$cbzDirectory = dirname($cbzFilePath);
if (!is_dir($cbzDirectory)) {
mkdir($cbzDirectory, 0755, true);
}
$fileSystem = new Filesystem();
if($fileSystem->exists($cbzFilePath)){
return 'already_exported';
}
return $this->createCbzFromDirectory($chapterDir, $cbzFilePath);
}
public function downloadCbz(string $mangaTitle, int $chapterNumber): BinaryFileResponse|bool
{
$filePathCbz = $this->getExportDir($mangaTitle, $chapterNumber);
$fileSystem = new Filesystem();
if($fileSystem->exists($filePathCbz)){
return new BinaryFileResponse($filePathCbz);
}
$chapterDir = $this->getMangaDir($mangaTitle, $chapterNumber);
if(is_dir($chapterDir)){
if($this->exportMangaChapter($mangaTitle, $chapterNumber)){
return new BinaryFileResponse($filePathCbz);
}
}
return false;
}
private function createCbzFromDirectory(string $sourceDirectory, string $cbzFilePath): bool
{
$zip = new ZipArchive();
// Ouvre le fichier .cbz en écriture
if ($zip->open($cbzFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
return false;
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourceDirectory),
RecursiveIteratorIterator::LEAVES_ONLY
);
// Ajoute les fichiers d'image au fichier .cbz
foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($sourceDirectory) + 1);
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
return true;
}
private function getMangaDir(string $mangaTitle, int $chapterNumber): string
{
return sprintf('%s/%s/%d', $this->projectDir . self::IMG_BASE_DIR, $mangaTitle, $chapterNumber);
}
private function getExportDir(string $mangaTitle, int $chapterNumber): string
{
return sprintf('%s/%s/%d', $this->projectDir . self::EXPORT_BASE_DIR, $mangaTitle, $chapterNumber) . '.cbz';
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace App\Service;
class MangaProviderFactory
{
public static function create($providerName): MangaProviderInterface
{
return match ($providerName) {
'LelScans' => new LelScansProviderService(),
'AutreManga' => new AutreMangaProviderService(),
default => throw new \Exception("Provider {$providerName} non supporté."),
};
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace App\Service;
interface MangaProviderInterface
{
public function getMangaList(): array;
public function getChapterList(string $mangaSlug): array;
}

View File

@@ -0,0 +1,145 @@
<?php
namespace App\Service;
use App\Event\MangaScrapedEvent;
use GuzzleHttp\Client;
use PHPUnit\Util\PHP\AbstractPhpProcess;
use Psr\Container\ContainerInterface;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class MangaScraperService
{
const IMG_BASE_DIR = '/public/manga-images';
private string $projectDir;
private EventDispatcherInterface $eventDispatcher;
public function __construct($projectDir, EventDispatcherInterface $eventDispatcher)
{
$this->projectDir = $projectDir;
$this->eventDispatcher = $eventDispatcher;
}
public function extractMangaPageData(string $html): array
{
$baseUrl = 'https://lelscans.net';
$crawler = new Crawler($html);
$imgUrl = $crawler->filter('img')->attr('src');
$nextLink = $crawler->filter('a[title="Suivant"]');
if (!preg_match('/^https?:\/\//', $imgUrl)) {
$urlComponents = parse_url($baseUrl);
$scheme = $urlComponents['scheme'];
$host = $urlComponents['host'];
// Construit l'URL absolue de l'image
$imgUrl = $scheme . '://' . $host . '/' . ltrim($imgUrl, '/');
}
if($nextLink->count() > 0){
$nextUrl = $nextLink->attr('href');
}else{
$nextUrl = null;
}
return [
'image_url' => $imgUrl,
'next_page_url' => $nextUrl,
];
}
public function scrapeMangaChapter(string $chapterUrl, string $mangaTitle, float $chapterNumber): array|bool
{
if(!$this->isChapterAvailable($chapterUrl, $chapterNumber)){
return false;
}
$pageData = [];
$currentPageUrl = $chapterUrl;
$mangaDir = sprintf('%s/%s', $this->projectDir . self::IMG_BASE_DIR, $mangaTitle);
if (!is_dir($mangaDir)) {
mkdir($mangaDir, 0755, true);
}
// Créez le dossier du chapitre s'il n'existe pas
$chapterDir = sprintf('%s/%s', $mangaDir, $chapterNumber);
if (!is_dir($chapterDir)) {
mkdir($chapterDir, 0755, true);
}
do {
$html = $this->fetchHtml($currentPageUrl);
$page = $this->extractMangaPageData($html);
$pageData[] = $page;
$currentPageUrl = $page['next_page_url'];
// Construisez le nom de fichier de l'image
$imageName = sprintf('%03d.jpg', count($pageData));
// Construisez le chemin du fichier de l'image
$imagePath = sprintf('%s/%s', $chapterDir, $imageName);
// Téléchargez et enregistrez l'image
$this->downloadAndSaveImage($page['image_url'], $imagePath);
// Modifiez les données de la page pour inclure l'URL de l'image stockée localement
$pageData[count($pageData) - 1]['local_image_url'] = sprintf('/manga-images/%s/%s/%s', $mangaTitle, $chapterNumber, $imageName);
$pageData[count($pageData) - 1]['page_number'] = count($pageData);
} while ($currentPageUrl);
$event = new MangaScrapedEvent($mangaTitle, $chapterNumber, $pageData);
$this->eventDispatcher->dispatch($event, MangaScrapedEvent::NAME);
return $pageData;
}
private function fetchHtml(string $url): string
{
$client = new Client();
$response = $client->get($url);
return (string) $response->getBody();
}
private function downloadAndSaveImage(string $imageUrl, string $destinationPath): void
{
$client = new Client();
$response = $client->get($imageUrl);
file_put_contents($destinationPath, $response->getBody()->getContents());
}
private function isChapterAvailable(string $chapterUrl, float $chapterNumber): bool
{
$html = $this->fetchHtml($chapterUrl);
$crawler = new Crawler($html);
$nextLink = $crawler->filter('a[title="Suivant"]');
if($nextLink->count() === 0){
return false;
}else{
$nextUrl = $nextLink->attr('href');
}
$routeCollection = new RouteCollection();
$routeCollection->add('manga_chapter', new Route('/scan-{manga}/{chapter}/{page}'));
$context = new RequestContext('/');
$matcher = new UrlMatcher($routeCollection, $context);
$path = parse_url($nextUrl, PHP_URL_PATH);
$parameters = $matcher->match($path);
if((float) $parameters['chapter'] !== $chapterNumber){
return false;
}
return true;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Service;
use Goutte\Client;
class SushiScanProviderService implements MangaProviderInterface
{
const PROVIDER_URL = 'https://sushiscan.com/';
const MANGA_SLUG = '/{manga}/{chapter}/{page}';
private Client $client;
public function __construct()
{
$this->client = new Client();
}
/**
* @return array
*/
public function getMangaList(): array
{
// TODO: Implement getMangaList() method.
}
/**
* @param string $mangaSlug
* @return array
*/
public function getChapterList(string $mangaSlug): array
{
// TODO: Implement getChapterList() method.
}
}

View File

@@ -233,6 +233,22 @@
"config/routes/web_profiler.yaml" "config/routes/web_profiler.yaml"
] ]
}, },
"symfony/webpack-encore-bundle": {
"version": "2.1",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
"version": "2.0",
"ref": "082d754b3bd54b3fc669f278f1eea955cfd23cf5"
},
"files": [
"assets/app.js",
"assets/styles/app.css",
"config/packages/webpack_encore.yaml",
"package.json",
"webpack.config.js"
]
},
"zenstruck/foundry": { "zenstruck/foundry": {
"version": "1.36", "version": "1.36",
"recipe": { "recipe": {

14
tailwind.config.js Normal file
View File

@@ -0,0 +1,14 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./templates/**/*.html.twig',
'./node_modules/tw-elements/dist/js/**/*.js'
],
theme: {
extend: {},
},
plugins: [
require('tw-elements/dist/plugin'),
require("daisyui"),
],
}

View File

@@ -1,16 +1,59 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title> <title>{% block title %}Welcome!{% endblock %}</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text><text y=%221.3em%22 x=%220.2em%22 font-size=%2276%22 fill=%22%23fff%22>sf</text></svg>"> <link rel="icon"
href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
{% block stylesheets %} {% block stylesheets %}
{{ encore_entry_link_tags('app') }}
{{ encore_entry_link_tags('app') }}
{% endblock %} {% endblock %}
</head>
<body>
{% block javascripts %} <div class="w-full bg-green-600 h-16">
</div>
<div class="max-w-7xl flex">
<div x-data="{ activeItem: { main: null, sub: null } }" class="block w-1/5 bg-gray-700 w-56 flex flex-col justify-center pl-8">
<div class="py-4">
<button @click="activeItem.main = activeItem.main === 'mangas' ? null : 'mangas'" class="w-full text-left">
<span :class="{'text-green-600 bg-gray-800': activeItem.main === 'mangas'}">Mangas</span>
</button>
<div x-show="activeItem.main === 'mangas'" class="pl-6">
<button @click="activeItem.sub = 'add-new'" class="py-4 block w-full text-left hover:text-green-600">
<span :class="{'text-green-600': activeItem.sub === 'add-new'}">Add New</span>
</button>
<button @click="activeItem.sub = 'import'" class="py-4 block w-full text-left hover:text-green-600">
<span :class="{'text-green-600': activeItem.sub === 'import'}">Import</span>
</button>
</div>
</div>
<button @click="activeItem.main = 'calendar'" class="pb-4 block w-full text-left hover:text-green-600">
<span :class="{'text-green-600': activeItem.main === 'calendar'}">Calendar</span>
</button>
<button @click="activeItem.main = 'settings'" class="pb-4 block w-full text-left hover:text-green-600">
<span :class="{'text-green-600': activeItem.main === 'settings'}">Settings</span>
</button>
</div>
{# {% include 'menu/base_menu.html.twig' %} #}
<main class="mx-auto flex">
<div class="p-4">
{% block body %}
{# {{ wo_render_breadcrumbs() }}#}
{% endblock %} {% endblock %}
</head> </div>
<body> </main>
{% block body %}{% endblock %} </div>
</body> {% block javascripts %}
{{ encore_entry_script_tags('app') }}
<script src="https://kit.fontawesome.com/42e345444d.js" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.3/dist/cdn.min.js"></script>
{{ encore_entry_script_tags('app') }}
{% endblock %}
</body>
</html> </html>

View File

@@ -0,0 +1,19 @@
{% extends 'base.html.twig' %}
{% block title %}Liste des mangas{% endblock %}
{% block body %}
<h1>Liste des mangas</h1>
<ul>
{% for manga in mangas %}
<li>
<a href="{{ path('manga_show', { 'mangaSlug': manga.slug }) }}">
{{ manga.title }}
</a>
</li>
{% else %}
<li>Aucun manga trouvé.</li>
{% endfor %}
</ul>
{% endblock %}

View File

@@ -0,0 +1,35 @@
{% extends 'base.html.twig' %}
{% block title %}{{ manga.title }} - Chapitre {{ chapter.number }}{% endblock %}
{% block body %}
<h1 class="text-center text-3xl my-4">{{ manga.title }} - Chapitre {{ chapter.number }}</h1>
<div class="flex justify-center my-4">
{% if currentPage.number > 1 %}
<a href="{{ path('read_chapter_page', { 'mangaSlug': manga.slug, 'chapterNumber': chapter.number, 'pageNumber': currentPage.number - 1 }) }}" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 mr-4">&laquo; Précédent</a>
{% endif %}
{% if currentPage.number < pages|length %}
<a href="{{ path('read_chapter_page', { 'mangaSlug': manga.slug, 'chapterNumber': chapter.number, 'pageNumber': currentPage.number + 1 }) }}" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">Suivant &raquo;</a>
{% endif %}
</div>
<div class="page-container flex justify-center">
{% if currentPage.number < pages|length %}
<a href="{{ path('read_chapter_page', {'mangaSlug': manga.slug, 'chapterNumber': chapter.number, 'pageNumber': currentPage.number + 1}) }}">
<img src="{{ asset(currentPage.imageLocalUrl) }}" alt="Page {{ currentPage.number }}" class="shadow-lg">
</a>
{% else %}
<img src="{{ asset(currentPage.imageLocalUrl) }}" alt="Page {{ currentPage.number }}" class="shadow-lg">
{% endif %}
</div>
<div class="flex justify-center my-4">
{% if currentPage.number > 1 %}
<a href="{{ path('read_chapter_page', { 'mangaSlug': manga.slug, 'chapterNumber': chapter.number, 'pageNumber': currentPage.number - 1 }) }}" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 mr-4">&laquo; Précédent</a>
{% endif %}
{% if currentPage.number < pages|length %}
<a href="{{ path('read_chapter_page', { 'mangaSlug': manga.slug, 'chapterNumber': chapter.number, 'pageNumber': currentPage.number + 1 }) }}" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">Suivant &raquo;</a>
{% endif %}
</div>
{% endblock %}

View File

@@ -0,0 +1,67 @@
{% extends 'base.html.twig' %}
{% block title %}Chapitres de {{ manga.title }}{% endblock %}
{% block body %}
<div class="container mx-auto px-4">
<h1 class="text-4xl font-bold mb-8">Chapitres de {{ manga.title }}</h1>
<ul class="list-disc pl-5">
{% for chapter in manga.chapters|sort((a, b) => a.number <=> b.number) %}
<li class="my-2">
<a class="text-blue-600 hover:text-blue-800" href="{{ path('read_chapter_page', { 'mangaSlug': manga.slug, 'chapterNumber': chapter.number, 'pageNumber': 1 }) }}">
Chapitre : {{ chapter.number }}
</a>
<a class="text-blue-600 hover:text-blue-800" href="{{ path('download_chapter', {'mangaSlug': manga.slug, 'chapterNumber': chapter.number}) }}"><i class="fas fa-save"></i></a>
</li>
{% else %}
<li>Aucun chapitre trouvé.</li>
{% endfor %}
</ul>
<h2 class="text-2xl font-semibold mb-4">Scrapper un chapitre</h2>
<form id="scrape-form" action="{{ path('manga_scrape') }}" method="post" class="space-y-4">
<input type="hidden" name="mangaSlug" value="{{ manga.slug }}">
<div>
<label for="chapterNumber" class="block mb-1">Numéro de chapitre :</label>
<input type="number" name="chapterNumber" id="chapterNumber" class="border border-gray-300 p-2 rounded">
</div>
<div>
<label for="availableChapters" class="block mb-1">Chapitres disponibles :</label>
<select id="availableChapters" class="border border-gray-300 p-2 rounded">
<option value="" selected disabled>Choisissez un chapitre</option>
{% for chapter in availableChapters %}
<option value="{{ chapter.number }}">{{ chapter.number }}</option>
{% endfor %}
</select>
</div>
<div class="flex items-center space-x-2">
<input type="checkbox" name="scrapeFromChapter" id="scrapeFromChapter" class="rounded">
<label for="scrapeFromChapter">Depuis ce chapitre :</label>
</div>
<input type="submit" value="Scrapper" class="button bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded">
</form>
</div>
{% block javascripts %}
{{ parent() }}
<script>
document.getElementById('scrape-form').addEventListener('submit', function(event) {
const chapterNumberInput = document.getElementById('chapterNumber');
const availableChaptersSelect = document.getElementById('availableChapters');
if (availableChaptersSelect.value) {
chapterNumberInput.value = availableChaptersSelect.value;
}
});
document.getElementById('scrapeFromChapter').addEventListener('change', function(event) {
const form = document.getElementById('scrape-form');
if (event.target.checked) {
form.action = "{{ path('manga_scrape_from_chapter') }}";
} else {
form.action = "{{ path('manga_scrape') }}";
}
});
</script>
{% endblock %}
{% endblock %}

View File

@@ -0,0 +1,10 @@
<!-- Menu latéral -->
<header class="fixed top-0 left-0 z-10 w-full bg-blue-600 p-4 md:hidden">
<button id="hamburger-button" class="text-white">
<i class="fas fa-bars"></i>
</button>
</header>
<aside id="menu" class="fixed top-0 left-0 z-10 h-full w-64 bg-gray-800 text-white p-4 hidden md:block">
{{ render(controller('App\\Controller\\MenuController::menu')) }}
</aside>

View File

@@ -0,0 +1,35 @@
<div class="fixed top-0 left-0 h-screen w-64 bg-gray-100 p-6">
<h2 class="text-xl font-bold mb-4">Menu</h2>
<form>
<div class="form-group">
<label for="manga-select">Choisissez un manga :</label>
<select id="manga-select" class="form-control w-full">
<option value="" selected disabled>Sélectionnez un manga</option>
{% for manga in availableManga %}
<option value="{{ path('manga_show', { 'mangaSlug': manga.slug }) }}">{{ manga.name }}</option>
{% endfor %}
</select>
</div>
</form>
<div>
<ul>
{% for manga in mangas %}
<li class="my-2">
<a href="{{ path('manga_show', { 'mangaSlug': manga.slug }) }}" class="text-blue-600 hover:text-blue-800">
{{ manga.title }}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
{% block javascripts %}
<script>
const mangaSelect = document.getElementById('manga-select');
mangaSelect.addEventListener('change', () => {
const selectedUrl = mangaSelect.options[mangaSelect.selectedIndex].value;
window.open(selectedUrl, '_top');
});
</script>
{% endblock %}

79
webpack.config.js Normal file
View File

@@ -0,0 +1,79 @@
const Encore = require('@symfony/webpack-encore');
// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
// directory where compiled assets will be stored
.setOutputPath('public/build/')
// public path used by the web server to access the output path
.setPublicPath('/build')
// only needed for CDN's or subdirectory deploy
//.setManifestKeyPrefix('build/')
/*
* ENTRY CONFIG
*
* Each entry will result in one JavaScript file (e.g. app.js)
* and one CSS file (e.g. app.css) if your JavaScript imports CSS.
*/
.addEntry('app', './assets/app.js')
.addEntry('alpine', 'alpinejs')
// enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
.enableStimulusBridge('./assets/controllers.json')
// When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
.splitEntryChunks()
// will require an extra script tag for runtime.js
// but, you probably want this, unless you're building a single-page app
.enableSingleRuntimeChunk()
/*
* FEATURE CONFIG
*
* Enable & configure other features below. For a full
* list of features, see:
* https://symfony.com/doc/current/frontend.html#adding-more-features
*/
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
// configure Babel
// .configureBabel((config) => {
// config.plugins.push('@babel/a-babel-plugin');
// })
// enables and configure @babel/preset-env polyfills
.configureBabelPresetEnv((config) => {
config.useBuiltIns = 'usage';
config.corejs = '3.23';
})
// enables Sass/SCSS support
.enableSassLoader()
// uncomment if you use TypeScript
//.enableTypeScriptLoader()
// uncomment if you use React
//.enableReactPreset()
// uncomment to get integrity="..." attributes on your script & link tags
// requires WebpackEncoreBundle 1.4 or higher
//.enableIntegrityHashes(Encore.isProduction())
// uncomment if you're having problems with a jQuery plugin
//.autoProvidejQuery()
.enablePostCssLoader()
;
module.exports = Encore.getWebpackConfig();