Compare commits

...

26 Commits

Author SHA1 Message Date
e85ae5ac95 wip: frankenphp 2025-05-23 21:55:41 -05:00
794189d70a wip: franenphp in worker mode 2025-05-23 20:38:22 -05:00
34d9029b7c chore: quicker healthchecks on prod containers 2025-05-23 15:44:53 -05:00
168bf04550 chore: speeds up startup healthchecks 2025-05-23 15:40:56 -05:00
81eb2d1f62 chore: small code cleanup 2025-05-23 14:56:24 -05:00
f5102b859f fix: adds php opcache 2025-05-23 14:56:06 -05:00
a9c6abe06b feat: download option cache on search 2025-05-22 20:48:08 -05:00
764fef37e5 fix: passes nginx config into app container 2025-05-22 12:33:20 -05:00
565481aa5a fix: uses new base image for app 2025-05-21 23:52:04 -05:00
64b7d4c963 fix: example compose 2025-05-21 16:40:51 -05:00
9eb7079ea6 fix: local compose file 2025-05-21 16:39:40 -05:00
bd92480958 fix: nginx conf, missing app_env 2025-05-21 16:38:12 -05:00
079a7e2cb5 fix: creates custom images for each container 2025-05-20 23:36:55 -05:00
295f68cb92 feat: uses php-fpm & nginx instead of php-apache 2025-05-20 20:38:36 -05:00
a2a1154a22 fix: updates docker version in example 2025-05-20 15:19:11 -05:00
3074b2d5f1 feat: download movie to dedicated directory 2025-05-19 22:28:00 -05:00
4638f3765a chore: remove unused imports 2025-05-19 20:38:07 -05:00
70189b95e1 fix: movie_folder download preference not saving when unchecked 2025-05-19 20:37:10 -05:00
c47b1fc23f fix: uses actual app container for dev 2025-05-19 16:36:37 -05:00
f39e307bc4 fix: adds download preference to form 2025-05-19 16:36:01 -05:00
3c965aa1ec fix: refactors getting user's media preferences 2025-05-19 16:16:54 -05:00
bd4ce76177 fix: renames preferences routes 2025-05-19 15:34:19 -05:00
fd0853d6f0 fix: adds 'type' to Preference 2025-05-19 15:33:55 -05:00
53ad80c90b fix: sets all media preferences to 'n/a' by default 2025-05-19 13:49:28 -05:00
fb47cf9d6b fix: adds redis to example compose.yml 2025-05-19 13:05:50 -05:00
eac586d946 chore: cleanup 2025-05-18 23:15:29 -05:00
39 changed files with 631 additions and 210 deletions

5
.env
View File

@@ -36,3 +36,8 @@ MERCURE_JWT_SECRET="!ChangeThisMercureHubJWTSecretKey!"
# MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
###< symfony/messenger ###
REDIS_HOST=redis://redis
MOVIES_PATH=/var/download/movies
TVSHOWS_PATH=/var/download/tvshows

View File

@@ -1,10 +1,29 @@
FROM registry.caldwell.digital/library/php:8.4-apache
FROM dunglas/frankenphp
RUN apt-get update && \
apt-get install libldap2-dev -y && \
rm -rf /var/lib/apt/lists/* && \
docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ && \
docker-php-ext-install ldap
ENV SERVER_NAME=":80"
ENV CADDY_GLOBAL_OPTIONS="auto_https off"
ENV APP_RUNTIME="Runtime\\FrankenPhpSymfony\\Runtime"
RUN install-php-extensions \
pdo_mysql \
gd \
intl \
zip \
opcache
#RUN apk add --no-cache \
# php84-opcache \
# php84-pdo_mysql \
# php84-simplexml
#
#USER nobody
#
#COPY --chmod=0775 ./bash/entrypoint.sh /usr/local/bin/
#COPY --chmod=0755 ./bash/nginx.conf /etc/nginx/conf.d/site.conf
#COPY --chmod=0755 ./docker/app/supervisord.conf /etc/supervisor/conf.d/async-queue.conf
HEALTHCHECK --interval=3s --timeout=3s --retries=10 CMD [ "php", "/app/bin/console", "startup:status" ]
#
#ENTRYPOINT [ "/usr/local/bin/entrypoint.sh" ]
#
#WORKDIR /var/www
COPY ./bash/vhost.conf /etc/apache2/sites-enabled/vhost.conf
RUN rm /etc/apache2/sites-enabled/000-default.conf

View File

@@ -7,5 +7,5 @@ RUN apt-get update && \
docker-php-ext-install ldap
COPY --chown=www-data:www-data . /var/www
COPY ./bash/vhost.conf /etc/apache2/sites-enabled/vhost.conf
COPY bash/nginx.conf /etc/apache2/sites-enabled/vhost.conf
RUN rm /etc/apache2/sites-enabled/000-default.conf

View File

@@ -2,5 +2,5 @@ dev.caldwell.digital:443
tls /etc/ssl/wildcard.crt /etc/ssl/wildcard.pem
reverse_proxy php:80
reverse_proxy app:80

View File

@@ -1,18 +1,12 @@
#!/bin/bash
#!/bin/sh
# Sleep for a second to ensure DB is awake and ready
SLEEP_TIME=$(shuf -i 2-5 -n 1)
SLEEP_TIME=$(shuf -i 2-4 -n 1)
echo "> Sleeping for ${SLEEP_TIME} seconds to wait for the database"
echo "> If there are errors after the migration runs, it's possible another container (scheduler, worker, etc.) already ran the migrations"
sleep $SLEEP_TIME
# Provision database
php /var/www/bin/console doctrine:migrations:migrate --no-interaction
php /var/www/bin/console db:seed
# Start Apache in the foreground
echo "Starting Apache..."
exec apachectl -D FOREGROUND
exec "$@"
/usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf

32
bash/nginx.conf Executable file
View File

@@ -0,0 +1,32 @@
server {
listen 80;
listen [::]:80;
server_name localhost;
root /var/www/public;
location /hub/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://mercure/;
}
location / {
# try to serve file directly, fallback to index.php
try_files $uri /index.php$is_args$args;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
internal;
}
}

View File

@@ -1,23 +0,0 @@
<VirtualHost *:80>
ServerName localhost
DocumentRoot /var/www/public
DirectoryIndex /index.php
<LocationMatch "/hub/">
ProxyPass http://mercure:80/
ProxyPassReverse http://mercure:80/
</LocationMatch>
<Directory /var/www/public>
AllowOverride None
Order Allow,Deny
Allow from All
FallbackResource /index.php
</Directory>
<Directory /var/www/public/bundles>
FallbackResource disabled
</Directory>
</VirtualHost>

View File

@@ -12,6 +12,26 @@ services:
- $PWD/bash/caddy:/etc/caddy
- $PWD/bash/certs:/etc/ssl
app:
build: .
restart: unless-stopped
environment:
FRANKENPHP_CONFIG: "worker /app/public/index.php"
volumes:
- $PWD:/app
tty: true
depends_on:
database:
condition: service_healthy
worker:
build: .
restart: unless-stopped
volumes:
- $PWD:/app
tty: true
command: php /app/bin/console messenger:consume async -vv
redis:
image: redis:latest
volumes:
@@ -19,25 +39,6 @@ services:
command: redis-server --maxmemory 512MB
restart: unless-stopped
php:
build: .
volumes:
- ./:/var/www
worker:
build: .
volumes:
- ./:/var/www
- ./var/download:/var/download
command: php ./bin/console messenger:consume async -vvv --time-limit=3600
scheduler:
build: .
volumes:
- ./:/var/www
- ./var/download:/var/download
command: php ./bin/console messenger:consume scheduler_monitor -vv --time-limit=3600
mercure:
image: dunglas/mercure
restart: unless-stopped
@@ -67,6 +68,11 @@ services:
MYSQL_USERNAME: app
MYSQL_PASSWORD: password
MYSQL_ROOT_PASSWORD: password
healthcheck:
test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
interval: 5s
timeout: 5s
retries: 10
adminer:
image: adminer

View File

@@ -22,6 +22,7 @@
"p3k/emoji-detector": "^1.2",
"php-tmdb/api": "^4.1",
"predis/predis": "^2.4",
"runtime/frankenphp-symfony": "^0.2.0",
"symfony/asset": "7.2.*",
"symfony/console": "7.2.*",
"symfony/doctrine-messenger": "7.2.*",
@@ -89,7 +90,7 @@
"post-update-cmd": [
"@auto-scripts"
],
"sym": "docker compose exec php ./bin/console"
"sym": "docker compose exec app ./bin/console"
},
"conflict": {
"symfony/symfony": "*"

54
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "33f1579a34e7ada02bb4738a9b39f493",
"content-hash": "c4ad1f54b8dd44fb55097f631c945460",
"packages": [
{
"name": "1tomany/rich-bundle",
@@ -3300,6 +3300,58 @@
},
"time": "2021-10-29T13:26:27+00:00"
},
{
"name": "runtime/frankenphp-symfony",
"version": "0.2.0",
"source": {
"type": "git",
"url": "https://github.com/php-runtime/frankenphp-symfony.git",
"reference": "56822c3631d9522a3136a4c33082d006bdfe4bad"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-runtime/frankenphp-symfony/zipball/56822c3631d9522a3136a4c33082d006bdfe4bad",
"reference": "56822c3631d9522a3136a4c33082d006bdfe4bad",
"shasum": ""
},
"require": {
"php": ">=8.1",
"symfony/dependency-injection": "^5.4 || ^6.0 || ^7.0",
"symfony/http-kernel": "^5.4 || ^6.0 || ^7.0",
"symfony/runtime": "^5.4 || ^6.0 || ^7.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5"
},
"type": "library",
"autoload": {
"psr-4": {
"Runtime\\FrankenPhpSymfony\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Kévin Dunglas",
"email": "kevin@dunglas.dev"
}
],
"description": "FrankenPHP runtime for Symfony",
"support": {
"issues": "https://github.com/php-runtime/frankenphp-symfony/issues",
"source": "https://github.com/php-runtime/frankenphp-symfony/tree/0.2.0"
},
"funding": [
{
"url": "https://github.com/nyholm",
"type": "github"
}
],
"time": "2023-12-12T12:06:11+00:00"
},
{
"name": "symfony/asset",
"version": "v7.2.0",

View File

@@ -29,6 +29,7 @@ framework:
'App\Monitor\Action\Command\MonitorTvSeasonCommand': async
'App\Monitor\Action\Command\MonitorTvShowCommand': async
'App\Monitor\Action\Command\MonitorMovieCommand': async
'App\Torrentio\Action\Command\GetTvShowOptionsCommand': async
# when@test:
# framework:

View File

@@ -7,7 +7,7 @@ parameters:
# Media
media.default_movies_dir: movies
media.default_tvshows_dir: tvshows
media.movies_path: '/var/download/%env(default:media.default_movies_dir:MOVIES_PATH)%'
media.movies_path: '%env(default:media.default_movies_dir:MOVIES_PATH)%'
media.tvshows_path: '/var/download/%env(default:media.default_tvshows_dir:TVSHOWS_PATH)%'
# Mercure

View File

@@ -1,13 +1,21 @@
services:
php:
image: registry.caldwell.digital/home/torsearch/app:${TAG}
web:
image: code.caldwell.digital/home/torsearch/web:latest
ports:
- "8001:80"
- '8001:80'
volumes:
- $PWD/bash/nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
app:
condition: service_healthy
app:
image: code.caldwell.digital/home/torsearch/app:${TAG}
deploy:
replicas: 2
worker:
image: registry.caldwell.digital/home/torsearch/app:${TAG}
image: code.caldwell.digital/home/torsearch/app:${TAG}
volumes:
- /mnt/media/downloads:/var/download
command: php ./bin/console messenger:consume async -v --time-limit=3600 --limit=10
@@ -15,7 +23,7 @@ services:
replicas: 2
scheduler:
image: registry.caldwell.digital/home/torsearch/app:${TAG}
image: code.caldwell.digital/home/torsearch/app:${TAG}
volumes:
- /mnt/media/downloads:/var/download
command: php ./bin/console messenger:consume scheduler_monitor -vv --time-limit=3600

View File

@@ -1,16 +1,17 @@
FROM registry.caldwell.digital/library/php:8.4-apache
FROM dunglas/frankenphp
RUN apt-get update && \
apt-get install libldap2-dev -y && \
rm -rf /var/lib/apt/lists/* && \
docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ && \
docker-php-ext-install ldap
ENV FRANKENPHP_CONFIG="worker /app/public/index.php"
ENV SERVER_NAME=":80"
ENV CADDY_GLOBAL_OPTIONS="auto_https off"
ENV APP_RUNTIME="Runtime\\FrankenPhpSymfony\\Runtime"
COPY --chown=www-data:www-data . /var/www
COPY --chmod=0775 ./bash/entrypoint.sh /usr/local/bin/
COPY ./bash/vhost.conf /etc/apache2/sites-enabled/vhost.conf
RUN rm /etc/apache2/sites-enabled/000-default.conf
RUN install-php-extensions \
pdo_mysql \
gd \
intl \
zip \
opcache
HEALTHCHECK --interval=5s --timeout=5s --retries=5 CMD [ "php", "/var/www/bin/console", "startup:status" ]
COPY . /app
ENTRYPOINT [ "/usr/local/bin/entrypoint.sh" ]
HEALTHCHECK --interval=3s --timeout=3s --retries=10 CMD [ "php", "/app/bin/console", "startup:status" ]

View File

@@ -0,0 +1,16 @@
FROM dunglas/frankenphp
ENV SERVER_NAME=":80"
ENV CADDY_GLOBAL_OPTIONS="auto_https off"
ENV APP_RUNTIME="Runtime\\FrankenPhpSymfony\\Runtime"
RUN install-php-extensions \
pdo_mysql \
gd \
intl \
zip \
opcache
COPY . /app
ENTRYPOINT [ "php", "/app/bin/console", "messenger:consume", "schedule_monitor", "-vv" ]

View File

@@ -1,12 +1,16 @@
FROM registry.caldwell.digital/library/php:8.4-apache
FROM dunglas/frankenphp
RUN apt-get update && \
apt-get install libldap2-dev -y && \
rm -rf /var/lib/apt/lists/* && \
docker-php-ext-configure ldap --with-libdir=lib/x86_64-linux-gnu/ && \
docker-php-ext-install ldap
ENV SERVER_NAME=":80"
ENV CADDY_GLOBAL_OPTIONS="auto_https off"
ENV APP_RUNTIME="Runtime\\FrankenPhpSymfony\\Runtime"
COPY --chown=www-data:www-data . /var/www
RUN install-php-extensions \
pdo_mysql \
gd \
intl \
zip \
opcache \
COPY ./bash/vhost.conf /etc/apache2/sites-enabled/vhost.conf
RUN rm /etc/apache2/sites-enabled/000-default.conf
COPY . /app
ENTRYPOINT [ "php", "/app/bin/console", "messenger:consume", "async", "-vv" ]

View File

@@ -0,0 +1,9 @@
[program:messenger-consume]
command=php /var/www/bin/console messenger:consume async --time-limit=3600
user=nobody
numprocs=2
startsecs=0
autostart=true
autorestart=true
startretries=10
process_name=%(program_name)s_%(process_num)02d

View File

@@ -5,6 +5,7 @@
# used to generate the Mercure URL behind the scenes.
APP_URL="https://torsearch.idocode.io"
APP_SECRET="70169beadfbc8101c393cbfbba27a313"
APP_ENV=prod
# Use the DATABASE_URL below to use the MariaDB container
# provided in the example.compose.yml file, or remove this

View File

@@ -1,32 +1,36 @@
services:
# This container runs the actual web app in a php:8.4-apache
# base container. If not running behind a reverse proxy,
# inject your SSL certificates into this container
# The "entrypoint" into the application. This reverse proxy
# proxies traffic back to their respective services. If not
# running behind a reverse proxy inject your SSL certificates
# into this container.
# This container runs the actual web app in a php:8.4-fpm
# base container.
app:
image: code.caldwell.digital/home/torsearch:0.14.5-app
image: code.caldwell.digital/home/torsearch-app:latest
ports:
- "8006:80"
- '8006:80'
env_file:
- .env
depends_on:
database:
condition: service_healthy
# Downloads happen asynchronously in this container. Replicate
# this container to run multiple downloads simultaneously.
# Downloads happen in this container. Replicate this
# container to run multiple downloads simultaneously.
# Map your "movies" folder to /var/download/movies
# Map your TV shows folder to /var/download/tvshows
# Map your "TV shows" folder to /var/download/tvshows
# If your folders are on another machine, use an NFS volume.
# This container runs a Symfony worker process.
# See: https://symfony.com/doc/current/messenger.html
worker:
image: code.caldwell.digital/home/torsearch:0.14.5-worker
image: code.caldwell.digital/home/torsearch-worker:latest
volumes:
- ./downloads/movies:/var/download/movies
- ./downloads/tvshows:/var/download/tvshows
command: php ./bin/console messenger:consume async -v --time-limit=3600 --limit=10
- /mnt/media/downloads/movies:/var/download/movies
- /mnt/media/downloads/tvshows:/var/download/tvshows
command: --time-limit=3600 --limit=10
env_file:
- .env
restart: always
depends_on:
app:
condition: service_healthy
@@ -37,12 +41,12 @@ services:
# This container runs a Symfony worker process.
# See: https://symfony.com/doc/current/messenger.html
scheduler:
image: code.caldwell.digital/home/torsearch:0.14.5-worker
image: code.caldwell.digital/home/torsearch-scheduler:latest
volumes:
- ./downloads:/var/download
command: php ./bin/console messenger:consume scheduler_monitor -vv --time-limit=3600
env_file:
- .env
restart: always
depends_on:
app:
condition: service_healthy
@@ -79,9 +83,19 @@ services:
MYSQL_ROOT_PASSWORD: password
healthcheck:
test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
timeout: 10s
interval: 5s
timeout: 5s
retries: 10
redis:
image: redis:latest
volumes:
- redis_data:/data
command: redis-server --maxmemory 512MB
restart: unless-stopped
# **Optional**
# Provides a simple method of viewing the database
adminer:
image: adminer
ports:
@@ -91,3 +105,4 @@ volumes:
mysql:
mercure_config:
mercure_data:
redis_data:

View File

@@ -0,0 +1,35 @@
<?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 Version20250519193350 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(<<<'SQL'
ALTER TABLE preference ADD type VARCHAR(255) DEFAULT NULL
SQL);
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql(<<<'SQL'
ALTER TABLE preference DROP type
SQL);
}
}

View File

@@ -53,6 +53,7 @@ class SeedDatabaseCommand extends Command
->setName($preference['name'])
->setDescription($preference['description'])
->setEnabled($preference['enabled'])
->setType($preference['type'])
);
}
@@ -66,26 +67,37 @@ class SeedDatabaseCommand extends Command
'id' => 'codec',
'name' => 'Codec',
'description' => null,
'enabled' => true
'enabled' => true,
'type' => 'media',
],
[
'id' => 'resolution',
'name' => 'Resolution',
'description' => null,
'enabled' => true
'enabled' => true,
'type' => 'media',
],
[
'id' => 'language',
'name' => 'Language',
'description' => null,
'enabled' => true
'enabled' => true,
'type' => 'media',
],
[
'id' => 'provider',
'name' => 'Provider',
'description' => null,
'enabled' => true
]
'enabled' => true,
'type' => 'media',
],
[
'id' => 'movie_folder',
'name' => 'Create new folder for Movies',
'description' => 'When downloading a movie, store it in a new folder in your base \'movies\' folder. (e.g.: .../movies/Inception/Inception.2160p.h265.mkv)',
'enabled' => true,
'type' => 'download'
],
];
}

View File

@@ -6,18 +6,20 @@ use App\Search\Action\Handler\GetMediaInfoHandler;
use App\Search\Action\Handler\SearchHandler;
use App\Search\Action\Input\GetMediaInfoInput;
use App\Search\Action\Input\SearchInput;
use Carbon\Carbon;
use App\Tmdb\TmdbResult;
use App\Torrentio\Action\Command\GetMovieOptionsCommand;
use App\Torrentio\Action\Command\GetTvShowOptionsCommand;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
final class SearchController extends AbstractController
{
public function __construct(
private SearchHandler $searchHandler,
private GetMediaInfoHandler $getMediaInfoHandler,
private MessageBusInterface $bus,
) {}
#[Route('/search', name: 'app_search', methods: ['GET'])]
@@ -36,6 +38,8 @@ final class SearchController extends AbstractController
GetMediaInfoInput $input,
): Response {
$result = $this->getMediaInfoHandler->handle($input->toCommand());
$this->warmDownloadOptionCache($result->media);
return $this->render('search/result.html.twig', [
'results' => $result,
'filter' => [
@@ -48,4 +52,32 @@ final class SearchController extends AbstractController
]
]);
}
private function warmDownloadOptionCache(TmdbResult $result)
{
if ($result->mediaType === 'tvshows') {
// dispatches a job to get the download options
// for each episode and load them in cache
foreach ($result->episodes as $season => $episodes) {
// Only do the first 2 seasons, so we reduce
// getting rate-limited by Torrentio
if ($season > 2) {
return;
}
foreach ($episodes as $episode) {
$this->bus->dispatch(new GetTvShowOptionsCommand(
tmdbId: $result->tmdbId,
imdbId: $result->imdbId,
season: $season,
episode: $episode['episode_number'],
));
}
}
} elseif ($result->mediaType === 'movies') {
$this->bus->dispatch(new GetMovieOptionsCommand(
$result->tmdbId,
$result->imdbId,
));
}
}
}

View File

@@ -37,8 +37,6 @@ readonly class DownloadMediaHandler implements HandlerInterface
$download = $this->downloadRepository->find($command->downloadId);
}
dump($download);
try {
$this->downloadRepository->updateStatus($download->getId(), 'In Progress');

View File

@@ -10,11 +10,11 @@ use App\Message\DownloadTvShowMessage;
interface DownloaderInterface
{
/**
* @param string $baseDir
* @param string $mediaType
* @param string $title
* @param string $url
* @return void
* Downloads the requested file.
*/
public function download(string $baseDir, string $title, string $url, ?int $downloadId): void;
public function download(string $mediaType, string $title, string $url, ?int $downloadId): void;
}

View File

@@ -3,6 +3,7 @@
namespace App\Download\Downloader;
use App\Download\Framework\Entity\Download;
use App\Monitor\Service\MediaFiles;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
@@ -11,25 +12,26 @@ class ProcessDownloader implements DownloaderInterface
{
public function __construct(
private EntityManagerInterface $entityManager,
private MediaFiles $mediaFiles,
) {}
/**
* @inheritDoc
*/
public function download(string $baseDir, string $title, string $url, ?int $downloadId): void
public function download(string $mediaType, string $title, string $url, ?int $downloadId): void
{
/** @var Download $downloadEntity */
$downloadEntity = $this->entityManager->getRepository(Download::class)->find($downloadId);
$downloadEntity->setProgress(0);
$this->entityManager->flush();
$process = new Process([
'/bin/sh',
'/var/www/bash/app/wget_download.sh',
$baseDir,
$title,
$downloadPreferences = $downloadEntity->getUser()->getDownloadPreferences();
$path = $this->getDownloadPath($mediaType, $title, $downloadPreferences);
$process = (new Process([
'wget',
$url
]);
]))->setWorkingDirectory($path);
$process->setTimeout(1800); // 30 min
$process->setIdleTimeout(600); // 10 min
@@ -61,4 +63,20 @@ class ProcessDownloader implements DownloaderInterface
$this->entityManager->flush();
}
public function getDownloadPath(string $mediaType, string $title, array $downloadPreferences): string
{
if ($mediaType === 'movies') {
if ((bool) $downloadPreferences['movie_folder']->getPreferenceValue() === true) {
return $this->mediaFiles->createMovieDirectory($title);
}
return $this->mediaFiles->getMoviesPath();
}
if ($mediaType === 'tvshows') {
return $this->mediaFiles->createTvShowDirectory($title);
}
throw new \Exception("There is no download path for media type: $mediaType");
}
}

View File

@@ -56,4 +56,4 @@ class ApiController extends AbstractController
return $this->json(['status' => 200, 'message' => 'Added to Queue']);
}
}
}

View File

@@ -17,8 +17,6 @@ class ApiController extends AbstractController
public function __construct(
#[Autowire(service: 'twig')]
private readonly Environment $renderer,
private readonly HubInterface $hub,
private readonly Security $security,
) {}
#[Route('/api/monitor', name: 'api_monitor', methods: ['POST'])]
@@ -28,12 +26,12 @@ class ApiController extends AbstractController
HubInterface $hub,
) {
$command = $input->toCommand();
$command->userId = $this->security->getUser()->getId();
$command->userId = $this->getUser()->getId();
$response = $handler->handle($command);
$hub->publish(new Update(
'alerts',
$this->renderer->render('Alert.stream.html.twig', [
$this->renderer->render('broadcast/Alert.stream.html.twig', [
'alert_id' => uniqid(),
'title' => 'Success',
'message' => "New monitor added for {$input->title}",

View File

@@ -32,6 +32,17 @@ class MediaFiles
$this->filesystem = $filesystem;
}
public function getPathByType(string $mediaType): string
{
if ('movies' === $mediaType) {
return $this->moviesPath;
} elseif ('tvshows' === $mediaType) {
return $this->tvShowsPath;
}
throw new \Exception(sprintf('A path for media type %s does not exist.', $mediaType));
}
public function getMoviesPath(): string
{
return $this->moviesPath;
@@ -83,4 +94,35 @@ class MediaFiles
return Map::from($results);
}
public function createMovieDirectory(string $path): string
{
$path = $this->moviesPath . DIRECTORY_SEPARATOR . $path;
if (false === $this->filesystem->exists($path)) {
$this->filesystem->mkdir($path);
}
return $path;
}
public function createTvShowDirectory(string $path): string
{
$path = $this->tvShowsPath . DIRECTORY_SEPARATOR . $path;
if (false === $this->filesystem->exists($path)) {
$this->filesystem->mkdir($path);
}
return $path;
}
public function createDirectory(string $path): string
{
if (false === $this->filesystem->exists($path)) {
$this->filesystem->mkdir($path);
}
return $path;
}
}

View File

@@ -4,20 +4,15 @@ namespace App\Torrentio\Client;
use App\Torrentio\Client\Rule\DownloadOptionFilter\Resolution;
use App\Torrentio\Client\Rule\RuleEngine;
use App\Torrentio\MediaResult;
use App\Torrentio\Result\ResultFactory;
use Carbon\Carbon;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
/**
* ToDo: Fix
*/
class Torrentio
{
private string $baseUrl = 'https://torrentio.strem.fun/providers%253Dyts%252Ceztv%252Crarbg%252C1337x%252Cthepiratebay%252Ckickasstorrents%252Ctorrentgalaxy%252Cmagnetdl%252Chorriblesubs%252Cnyaasi%7Csort%253Dqualitysize%7Cqualityfilter%253D480p%252Cscr%252Ccam%7Crealdebrid={realDebridKey}/stream/movie/{imdbCode}.json';
// private string $baseUrl = 'https://torrentio.strem.fun/providers=yts,eztv,rarbg,1337x,thepiratebay,kickasstorrents,torrentgalaxy,magnetdl,horriblesubs|sort=qualitysize|qualityfilter=480p,cam,unknown|debridoptions=nodownloadlinks|realdebrid=QYYBR7OSQ4VEFKWASDEZ2B4VO67KHUJY6IWOT7HHA7ATXO7QCYDQ/stream/{imdbCode}.json';
private string $searchUrl;
@@ -44,26 +39,6 @@ class Torrentio
return $this->parse($results, $filter);
}
public function searchBySeriesSeason(MediaResult $series): MediaResult
{
$imdbCode = $series->imdbId;
// foreach ($series->episodes as $season => $episodes) {
// foreach ($episodes as $key => $episode) {
// $cacheKey = "torrentio.$series->imdbId.$season.{$episode['episode_number']}";
// $downloadOptions = $this->cache->get($cacheKey, function (ItemInterface $item) use ($imdbCode, $season, $episode) {
// $item->expiresAt(new \DateTimeImmutable("today 11:59 pm"));
// $response = file_get_contents(str_replace('{imdbCode}', "$imdbCode:$season:{$episode['episode_number']}", $this->searchUrl));
// return json_decode(
// $response,
// true
// );
// });
// $series->episodes[$season][$key]['download_options'] = $this->parse($downloadOptions, []);
// }
// }
return $series;
}
public function fetchEpisodeResults(string $imdbId, int $season, int $episode): array
{
$cacheKey = "torrentio.$imdbId.$season.$episode";

View File

@@ -0,0 +1,13 @@
<?php
namespace App\User\Action\Command;
use OneToMany\RichBundle\Contract\CommandInterface;
/** @implements CommandInterface<SaveUserMediaPreferencesCommand> */
class SaveUserDownloadPreferencesCommand implements CommandInterface
{
public function __construct(
public string $movie_folder,
) {}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\User\Action\Handler;
use App\User\Action\Command\SaveUserMediaPreferencesCommand;
use App\User\Action\Result\SaveUserDownloadPreferencesResult;
use App\User\Action\Result\SaveUserMediaPreferencesResult;
use App\User\Framework\Entity\User;
use App\User\Framework\Entity\UserPreference;
use App\User\Framework\Repository\PreferencesRepository;
use Doctrine\ORM\EntityManagerInterface;
use OneToMany\RichBundle\Contract\CommandInterface as C;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface as R;
use Symfony\Bundle\SecurityBundle\Security;
/** @implements HandlerInterface<SaveUserMediaPreferencesCommand> */
class SaveUserDownloadPreferencesHandler implements HandlerInterface
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly PreferencesRepository $preferenceRepository,
private readonly Security $token,
) {}
public function handle(C $command): R
{
/** @var User $user */
$user = $this->token->getUser();
foreach ($command as $preference => $value) {
if ($user->hasUserPreference($preference)) {
$user->updateUserPreference($preference, $value);
$this->entityManager->flush();
continue;
}
$preference = $this->preferenceRepository->find($preference);
$user->addUserPreference(
(new UserPreference())
->setUser($user)
->setPreference($preference)
->setPreferenceValue($value)
);
}
$this->entityManager->flush();
return new SaveUserDownloadPreferencesResult($user->getDownloadPreferences());
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\User\Action\Input;
use App\User\Action\Command\SaveUserDownloadPreferencesCommand;
use OneToMany\RichBundle\Attribute\SourceRequest;
use OneToMany\RichBundle\Attribute\SourceSecurity;
use OneToMany\RichBundle\Contract\CommandInterface as C;
use OneToMany\RichBundle\Contract\InputInterface;
/** @implements InputInterface<SaveUserDownloadPreferencesInput, SaveUserDownloadPreferencesCommand> */
class SaveUserDownloadPreferencesInput implements InputInterface
{
public function __construct(
#[SourceSecurity]
public mixed $userId,
#[SourceRequest('movie_folder', nullify: true)]
public bool $movieFolder,
) {}
public function toCommand(): C
{
return new SaveUserDownloadPreferencesCommand(
$this->movieFolder,
);
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace App\User\Action\Result;
use Doctrine\Common\Collections\Collection;
use OneToMany\RichBundle\Contract\ResultInterface;
/** @implements ResultInterface */
class SaveUserDownloadPreferencesResult implements ResultInterface
{
public function __construct(
public array $downloadPreferences,
) {}
}

View File

@@ -2,10 +2,8 @@
namespace App\User\Framework\Controller\Web;
use App\User\Action\Handler\RegisterUserHandler;
use App\User\Framework\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

View File

@@ -4,17 +4,14 @@ declare(strict_types=1);
namespace App\User\Framework\Controller\Web;
use Aimeos\Map;
use App\User\Action\Handler\SaveUserDownloadPreferencesHandler;
use App\User\Action\Handler\SaveUserMediaPreferencesHandler;
use App\User\Action\Input\SaveUserDownloadPreferencesInput;
use App\User\Action\Input\SaveUserMediaPreferencesInput;
use App\User\Framework\Entity\User;
use App\User\Framework\Entity\UserPreference;
use App\User\Framework\Repository\PreferencesRepository;
use App\Util\CountryCodes;
use App\Util\CountryLanguages;
use App\Util\ProviderList;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\HubInterface;
@@ -26,22 +23,14 @@ class PreferencesController extends AbstractController
public function __construct(
private readonly PreferencesRepository $preferencesRepository,
private readonly SaveUserMediaPreferencesHandler $saveUserMediaPreferencesHandler,
private readonly Security $security,
private readonly HubInterface $hub,
private readonly SaveUserDownloadPreferencesHandler $saveUserDownloadPreferencesHandler,
) {}
#[Route('/media/preferences', 'app_media_preferences', methods: ['GET'])]
#[Route('/user/preferences', 'app_user_preferences', methods: ['GET'])]
public function mediaPreferences(): Response
{
$enabledPreferences = $this->preferencesRepository->findEnabled();
if ($this->security->getUser()->getUserPreferences()->count() !== count($enabledPreferences)) {
$this->setUserPreferences($this->security->getUser(), $enabledPreferences);
}
$userPreferences = $this->security->getUser()->getUserPreferences()->toArray();
$userPreferences = Map::from($userPreferences)
->rekey(fn($preference) => $preference->getPreference()->getId());
$mediaPreferences = $this->getUser()->getMediaPreferences();
$downloadPreferences = $this->getUser()->getDownloadPreferences();
$languages = CountryLanguages::$languages;
sort($languages);
@@ -51,19 +40,21 @@ class PreferencesController extends AbstractController
'preferences' => $this->preferencesRepository->findEnabled(),
'languages' => $languages,
'providers' => ProviderList::$providers,
'userPreferences' => $userPreferences->toArray(),
'mediaPreferences' => $mediaPreferences,
'downloadPreferences' => $downloadPreferences,
]
);
}
#[Route('/media/preferences', 'app_save_media_preferences', methods: ['POST'])]
#[Route('/user/preferences/media', 'app_save_media_preferences', methods: ['POST'])]
public function saveMediaPreferences(
Request $request,
SaveUserMediaPreferencesInput $input,
): Response
{
$userPreferences = $this->saveUserMediaPreferencesHandler->handle($input->toCommand())->userPreferences;
$userPreferences = Map::from($userPreferences)->rekey(fn($preference) => $preference->getPreference()->getId());
$this->saveUserMediaPreferencesHandler->handle($input->toCommand());
$mediaPreferences = $this->getUser()->getMediaPreferences();
$downloadPreferences = $this->getUser()->getDownloadPreferences();
$languages = CountryLanguages::$languages;
sort($languages);
@@ -83,22 +74,42 @@ class PreferencesController extends AbstractController
'preferences' => $this->preferencesRepository->findEnabled(),
'languages' => $languages,
'providers' => ProviderList::$providers,
'userPreferences' => $userPreferences->toArray(),
'mediaPreferences' => $mediaPreferences,
'downloadPreferences' => $downloadPreferences,
]
);
}
private function setUserPreferences(User $user, array $preferences): void
#[Route('/user/preferences/download', 'app_save_download_preferences', methods: ['POST'])]
public function saveDownloadPreferences(
Request $request,
SaveUserDownloadPreferencesInput $input,
): Response
{
foreach ($preferences as $preference) {
if (false === $user->hasUserPreference($preference->getId())) {
$user->addUserPreference((new UserPreference())
->setUser($user)
->setPreference($preference)
->setPreferenceValue(null)
);
}
}
$this->preferencesRepository->getEntityManager()->flush();
$downloadPreferences = $this->saveUserDownloadPreferencesHandler->handle($input->toCommand())->downloadPreferences;
$mediaPreferences = $this->getUser()->getMediaPreferences();
$languages = CountryLanguages::$languages;
sort($languages);
$this->hub->publish(new Update(
$request->getSession()->get('mercure_alert_topic'),
$this->renderView('broadcast/Alert.stream.html.twig', [
'alert_id' => uniqid(),
'title' => 'Success',
'message' => 'Your download preferences have been saved.',
])
));
return $this->render(
'user/preferences.html.twig',
[
'preferences' => $this->preferencesRepository->findEnabled(),
'languages' => $languages,
'providers' => ProviderList::$providers,
'mediaPreferences' => $mediaPreferences,
'downloadPreferences' => $downloadPreferences,
]
);
}
}

View File

@@ -14,6 +14,9 @@ class Preference
#[ORM\Column]
private ?string $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $type = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $name = null;
@@ -57,6 +60,17 @@ class Preference
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(string $type): static
{
$this->type = $type;
return $this;
}
public function getDescription(): ?string
{
return $this->description;

View File

@@ -204,7 +204,7 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
return $this;
}
public function getUserPreferenceValues()
public function getUserPreferenceValues(string $type = 'all'): array
{
return Map::from($this->userPreferences)
->rekey(fn(UserPreference $userPreference) => $userPreference->getPreference()->getId())
@@ -213,7 +213,6 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
return $userPreference->getPreferenceValue();
}
foreach ($userPreference->getPreference()->getPreferenceOptions() as $preferenceOption) {
// dd((int) $userPreference->getPreferenceValue(), $preferenceOption->getId(), $preferenceOption->getValue());
if ($preferenceOption->getId() === (int) $userPreference->getPreferenceValue()) {
return $preferenceOption->getValue();
}
@@ -273,6 +272,24 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
return $this->downloads;
}
public function getMediaPreferences()
{
return Map::from($this->userPreferences)
->rekey(fn(UserPreference $userPreference) => $userPreference->getPreference()->getId())
->filter(fn(UserPreference $userPreference) => $userPreference->getPreference()->getType() === 'media')
->toArray()
;
}
public function getDownloadPreferences()
{
return Map::from($this->userPreferences)
->rekey(fn(UserPreference $userPreference) => $userPreference->getPreference()->getId())
->filter(fn(UserPreference $userPreference) => $userPreference->getPreference()->getType() === 'download')
->toArray()
;
}
/**
* @return Collection<int, Download>
*/

View File

@@ -21,7 +21,7 @@
</li>
<li>
<a href="{{ path('app_media_preferences') }}"
<a href="{{ path('app_user_preferences') }}"
class="block rounded-lg px-4 py-2 text-sm font-medium text-gray-50 hover:bg-gray-100 hover:text-stone-700">
Preferences
</a>

View File

@@ -3,55 +3,78 @@
{% block h2 %}Preferences{% endblock %}
{% block body %}
<div class="p-4 flex flex-col">
<twig:Card title="Choose your preferences">
<p class="text-gray-50 mb-2">Define a set of filters to apply to your media download option results.</p>
<form id="media_preferences" class="flex flex-col max-w-64" name="media_preferences" method="post" action="{{ path('app_media_preferences') }}">
<div class="p-4 flex flex-row gap-2">
<twig:Card title="Media Preferences" class="w-full">
<p class="text-gray-50 mb-2">Define a filter to be pre-applied to your download options.</p>
<form id="media_preferences" class="flex flex-col max-w-64" name="media_preferences" method="post" action="{{ path('app_save_media_preferences') }}">
<label class="text-gray-50" for="resolution">Resolution</label>
<select class="p-1.5 rounded-md mb-2" name="resolution" id="resolution" value="{{ userPreferences['resolution'].getPreferenceValue() }}">
{% for pref in userPreferences['resolution'].getPreference().getPreferenceOptions() %}
<select class="p-1.5 rounded-md mb-2" name="resolution" id="resolution" value="{{ mediaPreferences['resolution'].getPreferenceValue() }}">
<option class="text-gray-800"
value=""
{{ mediaPreferences['resolution'] is null ? "selected" }}
>n/a</option>
{% for pref in mediaPreferences['resolution'].getPreference().getPreferenceOptions() %}
<option class="text-gray-800"
value="{{ pref.id }}"
{{ pref.id == userPreferences['resolution'].getPreferenceValue() ? "selected" }}
{{ pref.id == mediaPreferences['resolution'].getPreferenceValue() ? "selected" }}
>{{ pref.name }}</option>
{% endfor %}
</select>
<label class="text-gray-50" for="codec">Codec</label>
<select class="p-1.5 rounded-md mb-2" name="codec" id="codec" value="{{ userPreferences['codec'].getPreferenceValue() }}">
{% for pref in userPreferences['codec'].getPreference().getPreferenceOptions() %}
<select class="p-1.5 rounded-md mb-2" name="codec" id="codec" value="{{ mediaPreferences['codec'].getPreferenceValue() }}">
<option class="text-gray-800"
value=""
{{ mediaPreferences['codec'].getPreferenceValue() is null ? "selected" }}
>n/a</option>
{% for pref in mediaPreferences['codec'].getPreference().getPreferenceOptions() %}
<option class="text-gray-800"
value="{{ pref.id }}"
{{ pref.id == userPreferences['codec'].getPreferenceValue() ? "selected" }}
{{ pref.id == mediaPreferences['codec'].getPreferenceValue() ? "selected" }}
>{{ pref.name }}</option>
{% endfor %}
</select>
<label class="text-gray-50" for="provider">Provider</label>
<select class="p-1.5 rounded-md mb-2" name="provider" id="provider" value="{{ userPreferences['provider'].getPreferenceValue() }}">
<option class="text-gray-800" value=""
{{ "" == userPreferences['provider'].getPreferenceValue() ? "selected" }}
<select class="p-1.5 rounded-md mb-2" name="provider" id="provider" value="{{ mediaPreferences['provider'].getPreferenceValue() }}">
<option class="text-gray-800"
value=""
{{ "" == mediaPreferences['provider'].getPreferenceValue() ? "selected" }}
>n/a</option>
{% for provider in providers %}
<option class="text-gray-800"
value="{{ provider }}"
{{ provider == userPreferences['provider'].getPreferenceValue() ? "selected" }}
{{ provider == mediaPreferences['provider'].getPreferenceValue() ? "selected" }}
>{{ provider }}</option>
{% endfor %}
</select>
<label class="text-gray-50" for="language">Language</label>
<select class="p-1.5 rounded-md mb-2" name="language" id="language" value="{{ userPreferences['language'].getPreferenceValue() }}">
<select class="p-1.5 rounded-md mb-2" name="language" id="language" value="{{ mediaPreferences['language'].getPreferenceValue() }}">
<option class="text-gray-800"
value=""
{{ mediaPreferences['language'].getPreferenceValue() is null ? "selected" }}
>n/a</option>
{% for language in languages %}
<option class="text-gray-800"
value="{{ language }}"
{{ language == userPreferences['language'].getPreferenceValue() ? "selected" }}
{{ language == mediaPreferences['language'].getPreferenceValue() ? "selected" }}
>{{ language }}</option>
{% endfor %}
</select>
<button class="px-1.5 py-1 max-w-20 rounded-md bg-green-600 text-white" type="submit">Submit</button>
</form>
</twig:Card>
<twig:Card title="Download Preferences" class="w-full">
<p class="text-gray-50 mb-2">Change how your downloads are stored.</p>
<form id="download_preferences" class="flex flex-col" name="download_preferences" method="post" action="{{ path('app_save_download_preferences') }}">
<div class="flex flex-row gap-2 mb-2">
<input type="hidden" name="movie_folder" id="movie_folder_hidden" value="0" />
<input type="checkbox" name="movie_folder" id="movie_folder" value="1" {{ downloadPreferences['movie_folder'].getPreferenceValue() == true ? 'checked' }} />
<label class="text-gray-50" for="movie_folder">Store movies in a new directory?</label>
</div>
<button class="px-1.5 py-1 max-w-20 rounded-md bg-green-600 text-white" type="submit">Submit</button>
</form>
</twig:Card>