Compare commits
No commits in common. "main" and "v0.2.0" have entirely different histories.
283 changed files with 5031 additions and 20105 deletions
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -23,6 +23,3 @@ yarn-error.log
|
|||
/.nova
|
||||
/.vscode
|
||||
/.zed
|
||||
/coverage-report*
|
||||
/coverage.xml
|
||||
/.claude
|
||||
|
|
|
|||
3
.prettierignore
Normal file
3
.prettierignore
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
resources/js/components/ui/*
|
||||
resources/js/ziggy.js
|
||||
resources/views/mail/*
|
||||
19
.prettierrc
Normal file
19
.prettierrc
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"singleAttributePerLine": false,
|
||||
"htmlWhitespaceSensitivity": "css",
|
||||
"printWidth": 150,
|
||||
"plugins": ["prettier-plugin-organize-imports", "prettier-plugin-tailwindcss"],
|
||||
"tailwindFunctions": ["clsx", "cn"],
|
||||
"tailwindStylesheet": "resources/css/app.css",
|
||||
"tabWidth": 4,
|
||||
"overrides": [
|
||||
{
|
||||
"files": "**/*.yml",
|
||||
"options": {
|
||||
"tabWidth": 2
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
169
Dockerfile
169
Dockerfile
|
|
@ -1,127 +1,66 @@
|
|||
# Production Dockerfile with FrankenPHP
|
||||
FROM dunglas/frankenphp:latest-php8.3-alpine
|
||||
# Multi-stage build for Laravel with React frontend
|
||||
FROM node:22-alpine AS frontend-builder
|
||||
|
||||
# Install system dependencies
|
||||
RUN apk add --no-cache \
|
||||
nodejs \
|
||||
npm \
|
||||
git \
|
||||
mysql-client
|
||||
|
||||
# Install PHP extensions
|
||||
RUN install-php-extensions \
|
||||
pdo_mysql \
|
||||
opcache \
|
||||
zip \
|
||||
gd \
|
||||
intl \
|
||||
bcmath \
|
||||
redis \
|
||||
pcntl
|
||||
|
||||
# Install Composer
|
||||
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Set fixed production environment variables
|
||||
ENV APP_ENV=production \
|
||||
APP_DEBUG=false \
|
||||
DB_CONNECTION=mysql \
|
||||
DB_HOST=db \
|
||||
DB_PORT=3306 \
|
||||
SESSION_DRIVER=redis \
|
||||
CACHE_STORE=redis \
|
||||
QUEUE_CONNECTION=redis \
|
||||
LOG_CHANNEL=stack \
|
||||
LOG_LEVEL=error
|
||||
|
||||
# Copy application code first
|
||||
COPY package*.json ./
|
||||
RUN npm install --only=production
|
||||
COPY . .
|
||||
|
||||
# Install PHP dependencies (production only)
|
||||
RUN composer install --no-dev --no-interaction --optimize-autoloader
|
||||
|
||||
# Install ALL Node dependencies (including dev for building)
|
||||
RUN npm ci
|
||||
|
||||
# Build frontend assets
|
||||
RUN npm run build
|
||||
|
||||
# Remove node_modules after build to save space
|
||||
RUN rm -rf node_modules
|
||||
FROM php:8.4-fpm-alpine
|
||||
|
||||
# Laravel optimizations
|
||||
RUN php artisan config:cache \
|
||||
&& php artisan route:cache \
|
||||
&& php artisan view:cache \
|
||||
&& composer dump-autoload --optimize
|
||||
# Install system dependencies and PHP extensions
|
||||
RUN apk add --no-cache \
|
||||
git \
|
||||
curl \
|
||||
libpng-dev \
|
||||
oniguruma-dev \
|
||||
libxml2-dev \
|
||||
zip \
|
||||
unzip \
|
||||
autoconf \
|
||||
gcc \
|
||||
g++ \
|
||||
make \
|
||||
gettext \
|
||||
&& docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd \
|
||||
&& pecl install redis \
|
||||
&& docker-php-ext-enable redis
|
||||
|
||||
# Install Composer
|
||||
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /var/www/html
|
||||
|
||||
# Copy composer files
|
||||
COPY composer*.json ./
|
||||
|
||||
# Copy application files (needed for artisan in composer scripts)
|
||||
COPY . .
|
||||
|
||||
# Install dependencies
|
||||
RUN composer install --no-dev --optimize-autoloader --no-interaction --ignore-platform-reqs
|
||||
|
||||
# Copy production environment file and generate APP_KEY
|
||||
COPY docker/build/laravel.env .env
|
||||
RUN php artisan key:generate
|
||||
|
||||
# Copy built frontend assets
|
||||
COPY --from=frontend-builder /app/public/build /var/www/html/public/build
|
||||
|
||||
# Set permissions
|
||||
RUN chown -R www-data:www-data /app/storage /app/bootstrap/cache
|
||||
RUN chown -R www-data:www-data /var/www/html \
|
||||
&& chmod -R 755 /var/www/html/storage \
|
||||
&& chmod -R 755 /var/www/html/bootstrap/cache
|
||||
|
||||
# Configure Caddy
|
||||
RUN cat > /etc/caddy/Caddyfile <<EOF
|
||||
{
|
||||
frankenphp
|
||||
order php_server before file_server
|
||||
}
|
||||
# Create entrypoint script and health check scripts
|
||||
COPY docker/build/entrypoint.sh /entrypoint.sh
|
||||
COPY docker/build/wait-for-db.php /docker/wait-for-db.php
|
||||
COPY docker/build/wait-for-redis.php /docker/wait-for-redis.php
|
||||
RUN chmod +x /entrypoint.sh /docker/wait-for-db.php /docker/wait-for-redis.php
|
||||
|
||||
:8000 {
|
||||
root * /app/public
|
||||
|
||||
php_server {
|
||||
index index.php
|
||||
}
|
||||
|
||||
encode gzip
|
||||
|
||||
file_server
|
||||
|
||||
header {
|
||||
X-Frame-Options "SAMEORIGIN"
|
||||
X-Content-Type-Options "nosniff"
|
||||
X-XSS-Protection "1; mode=block"
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8000
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD curl -f http://localhost:8000/up || exit 1
|
||||
|
||||
# Create startup script for production
|
||||
RUN cat > /start-prod.sh <<'EOF'
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Wait for database to be ready
|
||||
echo "Waiting for database..."
|
||||
for i in $(seq 1 30); do
|
||||
if mysqladmin ping -h "$DB_HOST" -u "$DB_USERNAME" -p"$DB_PASSWORD" --silent 2>/dev/null; then
|
||||
echo "Database is ready!"
|
||||
break
|
||||
fi
|
||||
echo "Waiting for database... ($i/30)"
|
||||
sleep 2
|
||||
done
|
||||
|
||||
# Run migrations
|
||||
echo "Running migrations..."
|
||||
php artisan migrate --force || echo "Migrations failed or already up-to-date"
|
||||
|
||||
# Start Horizon in the background
|
||||
php artisan horizon &
|
||||
|
||||
# Start FrankenPHP
|
||||
exec frankenphp run --config /etc/caddy/Caddyfile
|
||||
EOF
|
||||
|
||||
RUN chmod +x /start-prod.sh
|
||||
|
||||
# Start with our script
|
||||
CMD ["/start-prod.sh"]
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
CMD ["web"]
|
||||
|
|
|
|||
127
Dockerfile.dev
127
Dockerfile.dev
|
|
@ -1,127 +0,0 @@
|
|||
# Development Dockerfile with FrankenPHP
|
||||
FROM dunglas/frankenphp:latest-php8.3-alpine
|
||||
|
||||
# Install system dependencies + development tools
|
||||
RUN apk add --no-cache \
|
||||
nodejs \
|
||||
npm \
|
||||
git \
|
||||
mysql-client \
|
||||
vim \
|
||||
bash \
|
||||
nano
|
||||
|
||||
# Install PHP extensions including xdebug for development
|
||||
RUN install-php-extensions \
|
||||
pdo_mysql \
|
||||
opcache \
|
||||
zip \
|
||||
gd \
|
||||
intl \
|
||||
bcmath \
|
||||
redis \
|
||||
pcntl \
|
||||
xdebug
|
||||
|
||||
# Install Composer
|
||||
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Configure PHP for development
|
||||
RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
|
||||
|
||||
# Configure Xdebug (disabled by default to reduce noise)
|
||||
RUN echo "xdebug.mode=off" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
|
||||
&& echo ";xdebug.mode=debug" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
|
||||
&& echo ";xdebug.client_host=host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
|
||||
&& echo ";xdebug.start_with_request=yes" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
|
||||
|
||||
# Configure Caddy for development (simpler, no worker mode)
|
||||
RUN cat > /etc/caddy/Caddyfile <<EOF
|
||||
{
|
||||
frankenphp
|
||||
order php_server before file_server
|
||||
}
|
||||
|
||||
:8000 {
|
||||
root * /app/public
|
||||
|
||||
php_server {
|
||||
index index.php
|
||||
}
|
||||
|
||||
encode gzip
|
||||
|
||||
file_server
|
||||
|
||||
# Less strict headers for development
|
||||
header {
|
||||
X-Frame-Options "SAMEORIGIN"
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
# Install Node development dependencies globally
|
||||
RUN npm install -g nodemon
|
||||
|
||||
# Create startup script for development
|
||||
RUN cat > /start.sh <<'EOF'
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Create .env file if it doesn't exist
|
||||
if [ ! -f ".env" ]; then
|
||||
echo "Creating .env file from .env.example..."
|
||||
cp .env.example .env
|
||||
fi
|
||||
|
||||
# Install dependencies if volumes are empty
|
||||
if [ ! -f "vendor/autoload.php" ]; then
|
||||
echo "Installing composer dependencies..."
|
||||
composer install
|
||||
fi
|
||||
|
||||
# Always reinstall node_modules in container to get correct native binaries for Alpine/musl
|
||||
echo "Installing npm dependencies..."
|
||||
rm -rf node_modules 2>/dev/null || true
|
||||
rm -rf /app/.npm 2>/dev/null || true
|
||||
npm install --cache /tmp/.npm
|
||||
|
||||
# Clear Laravel caches
|
||||
php artisan config:clear || true
|
||||
php artisan cache:clear || true
|
||||
|
||||
# Wait for database and run migrations
|
||||
echo "Waiting for database..."
|
||||
sleep 5
|
||||
php artisan migrate --force || echo "Migration failed or not needed"
|
||||
|
||||
# Run seeders
|
||||
echo "Running seeders..."
|
||||
php artisan db:seed --force || echo "Seeding skipped or already done"
|
||||
|
||||
# Generate app key if not set
|
||||
if [ -z "$APP_KEY" ] || [ "$APP_KEY" = "base64:YOUR_KEY_HERE" ]; then
|
||||
echo "Generating application key..."
|
||||
php artisan key:generate
|
||||
fi
|
||||
|
||||
# Start Vite dev server in background
|
||||
npm run dev &
|
||||
|
||||
# Start Horizon (queue worker) in background
|
||||
php artisan horizon &
|
||||
|
||||
# Start FrankenPHP
|
||||
exec frankenphp run --config /etc/caddy/Caddyfile
|
||||
EOF
|
||||
|
||||
RUN chmod +x /start.sh
|
||||
|
||||
# Expose ports
|
||||
EXPOSE 8000 5173
|
||||
|
||||
# Use the startup script
|
||||
CMD ["/start.sh"]
|
||||
241
Jenkinsfile
vendored
241
Jenkinsfile
vendored
|
|
@ -1,241 +0,0 @@
|
|||
pipeline {
|
||||
agent any
|
||||
|
||||
environment {
|
||||
APP_ENV = 'testing'
|
||||
DB_CONNECTION = 'mysql'
|
||||
DB_HOST = 'mysql'
|
||||
DB_PORT = '3306'
|
||||
DB_DATABASE = 'ffr_testing'
|
||||
DB_USERNAME = 'ffr_user'
|
||||
DB_PASSWORD = 'ffr_password'
|
||||
CACHE_STORE = 'array'
|
||||
SESSION_DRIVER = 'array'
|
||||
QUEUE_CONNECTION = 'sync'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
checkout scm
|
||||
}
|
||||
}
|
||||
|
||||
stage('Setup Environment') {
|
||||
steps {
|
||||
script {
|
||||
sh '''
|
||||
echo "Setting up environment for testing..."
|
||||
cp .env.example .env.testing
|
||||
echo "APP_ENV=testing" >> .env.testing
|
||||
echo "DB_CONNECTION=${DB_CONNECTION}" >> .env.testing
|
||||
echo "DB_HOST=${DB_HOST}" >> .env.testing
|
||||
echo "DB_PORT=${DB_PORT}" >> .env.testing
|
||||
echo "DB_DATABASE=${DB_DATABASE}" >> .env.testing
|
||||
echo "DB_USERNAME=${DB_USERNAME}" >> .env.testing
|
||||
echo "DB_PASSWORD=${DB_PASSWORD}" >> .env.testing
|
||||
echo "CACHE_STORE=${CACHE_STORE}" >> .env.testing
|
||||
echo "SESSION_DRIVER=${SESSION_DRIVER}" >> .env.testing
|
||||
echo "QUEUE_CONNECTION=${QUEUE_CONNECTION}" >> .env.testing
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Install Dependencies') {
|
||||
parallel {
|
||||
stage('PHP Dependencies') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Installing PHP dependencies..."
|
||||
composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Node Dependencies') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Installing Node.js dependencies..."
|
||||
npm ci
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Generate Application Key') {
|
||||
steps {
|
||||
sh '''
|
||||
php artisan key:generate --env=testing --force
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Database Setup') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Setting up test database..."
|
||||
php artisan migrate:fresh --env=testing --force
|
||||
php artisan config:clear --env=testing
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Code Quality Checks') {
|
||||
parallel {
|
||||
stage('PHP Syntax Check') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Checking PHP syntax..."
|
||||
find . -name "*.php" -not -path "./vendor/*" -not -path "./node_modules/*" -exec php -l {} \\;
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('PHPStan Analysis') {
|
||||
steps {
|
||||
script {
|
||||
try {
|
||||
sh '''
|
||||
if [ -f "phpstan.neon" ]; then
|
||||
echo "Running PHPStan static analysis..."
|
||||
./vendor/bin/phpstan analyse --no-progress --error-format=table
|
||||
else
|
||||
echo "PHPStan configuration not found, skipping static analysis"
|
||||
fi
|
||||
'''
|
||||
} catch (Exception e) {
|
||||
unstable(message: "PHPStan found issues")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stage('Security Audit') {
|
||||
steps {
|
||||
script {
|
||||
try {
|
||||
sh '''
|
||||
echo "Running security audit..."
|
||||
composer audit
|
||||
'''
|
||||
} catch (Exception e) {
|
||||
unstable(message: "Security vulnerabilities found")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Unit Tests') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Running Unit Tests..."
|
||||
php artisan test tests/Unit/ --env=testing --stop-on-failure
|
||||
'''
|
||||
}
|
||||
post {
|
||||
always {
|
||||
publishTestResults testResultsPattern: 'tests/Unit/results/*.xml'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Feature Tests') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Running Feature Tests..."
|
||||
php artisan test tests/Feature/ --env=testing --stop-on-failure
|
||||
'''
|
||||
}
|
||||
post {
|
||||
always {
|
||||
publishTestResults testResultsPattern: 'tests/Feature/results/*.xml'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Full Regression Test Suite') {
|
||||
steps {
|
||||
sh '''
|
||||
echo "Running comprehensive regression test suite..."
|
||||
chmod +x ./run-regression-tests.sh
|
||||
./run-regression-tests.sh
|
||||
'''
|
||||
}
|
||||
post {
|
||||
always {
|
||||
// Archive test results
|
||||
archiveArtifacts artifacts: 'tests/reports/**/*', allowEmptyArchive: true
|
||||
|
||||
// Publish coverage reports if available
|
||||
publishHTML([
|
||||
allowMissing: false,
|
||||
alwaysLinkToLastBuild: true,
|
||||
keepAll: true,
|
||||
reportDir: 'coverage',
|
||||
reportFiles: 'index.html',
|
||||
reportName: 'Coverage Report'
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Performance Tests') {
|
||||
steps {
|
||||
script {
|
||||
try {
|
||||
sh '''
|
||||
echo "Running performance tests..."
|
||||
|
||||
# Test memory usage
|
||||
php -d memory_limit=256M artisan test tests/Feature/DatabaseIntegrationTest.php --env=testing
|
||||
|
||||
# Test response times for API endpoints
|
||||
time php artisan test tests/Feature/ApiEndpointRegressionTest.php --env=testing
|
||||
'''
|
||||
} catch (Exception e) {
|
||||
unstable(message: "Performance tests indicated potential issues")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build Assets') {
|
||||
when {
|
||||
anyOf {
|
||||
branch 'main'
|
||||
branch 'develop'
|
||||
}
|
||||
}
|
||||
steps {
|
||||
sh '''
|
||||
echo "Building production assets..."
|
||||
npm run build
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
// Clean up
|
||||
sh '''
|
||||
echo "Cleaning up..."
|
||||
rm -f .env.testing
|
||||
'''
|
||||
}
|
||||
success {
|
||||
echo '✅ All regression tests passed successfully!'
|
||||
// Notify success (customize as needed)
|
||||
// slackSend channel: '#dev-team', color: 'good', message: "Regression tests passed for ${env.JOB_NAME} - ${env.BUILD_NUMBER}"
|
||||
}
|
||||
failure {
|
||||
echo '❌ Regression tests failed!'
|
||||
// Notify failure (customize as needed)
|
||||
// slackSend channel: '#dev-team', color: 'danger', message: "Regression tests failed for ${env.JOB_NAME} - ${env.BUILD_NUMBER}"
|
||||
}
|
||||
unstable {
|
||||
echo '⚠️ Tests completed with warnings'
|
||||
}
|
||||
}
|
||||
}
|
||||
191
README.md
191
README.md
|
|
@ -1,128 +1,141 @@
|
|||
# FFR (Feed to Fediverse Router)
|
||||
# Fedi Feed Router
|
||||
|
||||
A Laravel-based application for routing RSS/Atom feeds to Fediverse platforms like Lemmy. Built with Laravel, Livewire, and FrankenPHP for a modern, single-container deployment.
|
||||
<div align="center">
|
||||
<img src="public/images/ffr-logo-600.png" alt="FFR Logo" width="200">
|
||||
</div>
|
||||
|
||||
`ffr` is a self-hosted tool for routing content from RSS/Atom feeds to the fediverse.
|
||||
|
||||
It watches feeds, matches entries based on keywords or rules, and publishes them to platforms like Lemmy, Mastodon, or anything ActivityPub-compatible.
|
||||
|
||||
## Features
|
||||
|
||||
- **Feed aggregation** - Fetch articles from multiple RSS/Atom feeds
|
||||
- **Fediverse publishing** - Automatically post to Lemmy communities
|
||||
- **Route configuration** - Map feeds to specific channels with keywords
|
||||
- **Approval workflow** - Optional manual approval before publishing
|
||||
- **Queue processing** - Background job handling with Laravel Horizon
|
||||
- **Single container deployment** - Simplified hosting with FrankenPHP
|
||||
- Keyword-based routing from any RSS/Atom feed
|
||||
- Publish to Lemmy, Mastodon, or other fediverse services
|
||||
- YAML or JSON route configs
|
||||
- CLI and/or daemon mode
|
||||
- Self-hosted, privacy-first, no SaaS dependencies
|
||||
|
||||
## Self-hosting
|
||||
|
||||
The production image is available at `codeberg.org/lvl0/ffr:latest`.
|
||||
## Docker Deployment
|
||||
|
||||
### docker-compose.yml
|
||||
### Building the Image
|
||||
|
||||
```bash
|
||||
docker build -t your-registry/lemmy-poster:latest .
|
||||
docker push your-registry/lemmy-poster:latest
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
Create a `docker-compose.yml` file:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
image: codeberg.org/lvl0/ffr:latest
|
||||
container_name: ffr_app
|
||||
restart: always
|
||||
app-web:
|
||||
image: your-registry/lemmy-poster:latest
|
||||
command: ["web"]
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
APP_KEY: "${APP_KEY}"
|
||||
APP_URL: "${APP_URL}"
|
||||
DB_DATABASE: "${DB_DATABASE}"
|
||||
DB_USERNAME: "${DB_USERNAME}"
|
||||
DB_PASSWORD: "${DB_PASSWORD}"
|
||||
REDIS_HOST: redis
|
||||
REDIS_PORT: 6379
|
||||
volumes:
|
||||
- app_storage:/app/storage
|
||||
- DB_DATABASE=${DB_DATABASE}
|
||||
- DB_USERNAME=${DB_USERNAME}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- LEMMY_INSTANCE=${LEMMY_INSTANCE}
|
||||
- LEMMY_USERNAME=${LEMMY_USERNAME}
|
||||
- LEMMY_PASSWORD=${LEMMY_PASSWORD}
|
||||
- LEMMY_COMMUNITY=${LEMMY_COMMUNITY}
|
||||
depends_on:
|
||||
- db
|
||||
- redis
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:8000/up"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
- mysql
|
||||
volumes:
|
||||
- storage_data:/var/www/html/storage/app
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
image: mariadb:11
|
||||
container_name: ffr_db
|
||||
restart: always
|
||||
app-queue:
|
||||
image: your-registry/lemmy-poster:latest
|
||||
command: ["queue"]
|
||||
environment:
|
||||
MYSQL_DATABASE: "${DB_DATABASE}"
|
||||
MYSQL_USER: "${DB_USERNAME}"
|
||||
MYSQL_PASSWORD: "${DB_PASSWORD}"
|
||||
MYSQL_ROOT_PASSWORD: "${DB_ROOT_PASSWORD}"
|
||||
- DB_DATABASE=${DB_DATABASE}
|
||||
- DB_USERNAME=${DB_USERNAME}
|
||||
- DB_PASSWORD=${DB_PASSWORD}
|
||||
- LEMMY_INSTANCE=${LEMMY_INSTANCE}
|
||||
- LEMMY_USERNAME=${LEMMY_USERNAME}
|
||||
- LEMMY_PASSWORD=${LEMMY_PASSWORD}
|
||||
- LEMMY_COMMUNITY=${LEMMY_COMMUNITY}
|
||||
depends_on:
|
||||
- mysql
|
||||
volumes:
|
||||
- db_data:/var/lib/mysql
|
||||
- storage_data:/var/www/html/storage/app
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: ffr_redis
|
||||
restart: always
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
command: --host-cache-size=0 --innodb-use-native-aio=0 --sql-mode=STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION --log-error-verbosity=1
|
||||
environment:
|
||||
- MYSQL_DATABASE=${DB_DATABASE}
|
||||
- MYSQL_USER=${DB_USERNAME}
|
||||
- MYSQL_PASSWORD=${DB_PASSWORD}
|
||||
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
|
||||
- TZ=UTC
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
- mysql_data:/var/lib/mysql
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
db_data:
|
||||
redis_data:
|
||||
app_storage:
|
||||
mysql_data:
|
||||
storage_data:
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Required | Description |
|
||||
|----------|----------|-------------|
|
||||
| `APP_KEY` | Yes | Encryption key. Generate with: `echo "base64:$(openssl rand -base64 32)"` |
|
||||
| `APP_URL` | Yes | Your domain (e.g., `https://ffr.example.com`) |
|
||||
| `DB_DATABASE` | Yes | Database name |
|
||||
| `DB_USERNAME` | Yes | Database user |
|
||||
| `DB_PASSWORD` | Yes | Database password |
|
||||
| `DB_ROOT_PASSWORD` | Yes | MariaDB root password |
|
||||
Create a `.env` file with:
|
||||
|
||||
## Development
|
||||
```env
|
||||
# Database Settings
|
||||
DB_DATABASE=lemmy_poster
|
||||
DB_USERNAME=lemmy_user
|
||||
DB_PASSWORD=your-password
|
||||
|
||||
### NixOS / Nix
|
||||
|
||||
```bash
|
||||
git clone https://codeberg.org/lvl0/ffr.git
|
||||
cd ffr
|
||||
nix-shell
|
||||
# Lemmy Settings
|
||||
LEMMY_INSTANCE=your-lemmy-instance.com
|
||||
LEMMY_USERNAME=your-lemmy-username
|
||||
LEMMY_PASSWORD=your-lemmy-password
|
||||
LEMMY_COMMUNITY=your-target-community
|
||||
```
|
||||
|
||||
The shell will display available commands and optionally start the containers for you.
|
||||
### Deployment
|
||||
|
||||
#### Available Commands
|
||||
1. Build and push the image to your registry
|
||||
2. Copy the docker-compose.yml to your server
|
||||
3. Create the .env file with your environment variables
|
||||
4. Run: `docker compose up -d`
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `dev-up` | Start development environment |
|
||||
| `dev-down` | Stop development environment |
|
||||
| `dev-restart` | Restart containers |
|
||||
| `dev-logs` | Follow app logs |
|
||||
| `dev-logs-db` | Follow database logs |
|
||||
| `dev-shell` | Enter app container |
|
||||
| `dev-artisan <cmd>` | Run artisan commands |
|
||||
| `prod-build [tag]` | Build and push prod image (default: latest) |
|
||||
The application will automatically:
|
||||
- Wait for the database to be ready
|
||||
- Run database migrations on first startup
|
||||
- Start the queue worker after migrations complete
|
||||
- Handle race conditions between web and queue containers
|
||||
|
||||
#### Services
|
||||
### Initial Setup
|
||||
|
||||
| Service | URL |
|
||||
|---------|-----|
|
||||
| App | http://localhost:8000 |
|
||||
| Vite | http://localhost:5173 |
|
||||
| MariaDB | localhost:3307 |
|
||||
| Redis | localhost:6380 |
|
||||
After deployment, the article refresh will run every hour. To trigger the initial article fetch manually:
|
||||
|
||||
### Other Platforms
|
||||
```bash
|
||||
docker compose exec app-web php artisan article:refresh
|
||||
```
|
||||
|
||||
Contributions welcome for development setup instructions on other platforms.
|
||||
The application will then automatically:
|
||||
- Fetch new articles every hour
|
||||
- Publish valid articles every 5 minutes
|
||||
- Sync community posts every 10 minutes
|
||||
|
||||
## License
|
||||
The web interface will be available on port 8000.
|
||||
|
||||
This project is open-source software licensed under the [AGPL-3.0 license](LICENSE).
|
||||
### Architecture
|
||||
|
||||
## Support
|
||||
The application uses a multi-container setup:
|
||||
- **app-web**: Serves the Laravel web interface and handles HTTP requests
|
||||
- **app-queue**: Processes background jobs (article fetching, Lemmy posting)
|
||||
- **mysql**: Database storage for articles, logs, and application data
|
||||
|
||||
For issues and questions, please use [Codeberg Issues](https://codeberg.org/lvl0/ffr/issues).
|
||||
Both app containers use the same Docker image but with different commands (`web` or `queue`). Environment variables are passed from your `.env` file to configure database access and Lemmy integration.
|
||||
|
|
|
|||
18
app/Events/ArticleReadyToPublish.php
Normal file
18
app/Events/ArticleReadyToPublish.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
namespace App\Events;
|
||||
|
||||
use App\Models\Article;
|
||||
use Illuminate\Broadcasting\InteractsWithSockets;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class ArticleReadyToPublish
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
|
||||
public function __construct(public Article $article)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
namespace App\Events;
|
||||
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\LogLevelEnum;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Throwable;
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Facades;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
|
||||
class LogSaver extends Facade
|
||||
{
|
||||
protected static function getFacadeAccessor()
|
||||
{
|
||||
return \App\Services\Log\LogSaver::class;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Resources\ArticleResource;
|
||||
use App\Models\Article;
|
||||
use App\Models\Setting;
|
||||
use App\Jobs\ArticleDiscoveryJob;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
|
||||
class ArticlesController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display a listing of articles
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$perPage = min($request->get('per_page', 15), 100); // Max 100 items per page
|
||||
$articles = Article::with(['feed', 'articlePublication'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate($perPage);
|
||||
|
||||
$publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();
|
||||
|
||||
return $this->sendResponse([
|
||||
'articles' => ArticleResource::collection($articles->items()),
|
||||
'pagination' => [
|
||||
'current_page' => $articles->currentPage(),
|
||||
'last_page' => $articles->lastPage(),
|
||||
'per_page' => $articles->perPage(),
|
||||
'total' => $articles->total(),
|
||||
'from' => $articles->firstItem(),
|
||||
'to' => $articles->lastItem(),
|
||||
],
|
||||
'settings' => [
|
||||
'publishing_approvals_enabled' => $publishingApprovalsEnabled,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Approve an article
|
||||
*/
|
||||
public function approve(Article $article): JsonResponse
|
||||
{
|
||||
try {
|
||||
$article->approve('manual');
|
||||
|
||||
return $this->sendResponse(
|
||||
new ArticleResource($article->fresh(['feed', 'articlePublication'])),
|
||||
'Article approved and queued for publishing.'
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return $this->sendError('Failed to approve article: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject an article
|
||||
*/
|
||||
public function reject(Article $article): JsonResponse
|
||||
{
|
||||
try {
|
||||
$article->reject('manual');
|
||||
|
||||
return $this->sendResponse(
|
||||
new ArticleResource($article->fresh(['feed', 'articlePublication'])),
|
||||
'Article rejected.'
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return $this->sendError('Failed to reject article: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually refresh articles from all active feeds
|
||||
*/
|
||||
public function refresh(): JsonResponse
|
||||
{
|
||||
try {
|
||||
ArticleDiscoveryJob::dispatch();
|
||||
|
||||
return $this->sendResponse(
|
||||
null,
|
||||
'Article refresh started. New articles will appear shortly.'
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return $this->sendError('Failed to start article refresh: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AuthController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Login user and create token
|
||||
*/
|
||||
public function login(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$request->validate([
|
||||
'email' => 'required|email',
|
||||
'password' => 'required',
|
||||
]);
|
||||
|
||||
$user = User::where('email', $request->email)->first();
|
||||
|
||||
if (!$user || !Hash::check($request->password, $user->password)) {
|
||||
return $this->sendError('Invalid credentials', [], 401);
|
||||
}
|
||||
|
||||
$token = $user->createToken('api-token')->plainTextToken;
|
||||
|
||||
return $this->sendResponse([
|
||||
'user' => [
|
||||
'id' => $user->id,
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
],
|
||||
'token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
], 'Login successful');
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Login failed: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new user
|
||||
*/
|
||||
public function register(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|string|email|max:255|unique:users',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $validated['name'],
|
||||
'email' => $validated['email'],
|
||||
'password' => Hash::make($validated['password']),
|
||||
]);
|
||||
|
||||
$token = $user->createToken('api-token')->plainTextToken;
|
||||
|
||||
return $this->sendResponse([
|
||||
'user' => [
|
||||
'id' => $user->id,
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
],
|
||||
'token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
], 'Registration successful', 201);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Registration failed: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout user (revoke token)
|
||||
*/
|
||||
public function logout(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$request->user()->currentAccessToken()->delete();
|
||||
|
||||
return $this->sendResponse(null, 'Logged out successfully');
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Logout failed: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current authenticated user
|
||||
*/
|
||||
public function me(Request $request): JsonResponse
|
||||
{
|
||||
return $this->sendResponse([
|
||||
'user' => [
|
||||
'id' => $request->user()->id,
|
||||
'name' => $request->user()->name,
|
||||
'email' => $request->user()->email,
|
||||
],
|
||||
], 'User retrieved successfully');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class BaseController extends Controller
|
||||
{
|
||||
/**
|
||||
* Success response method
|
||||
*/
|
||||
public function sendResponse(mixed $result, string $message = 'Success', int $code = 200): JsonResponse
|
||||
{
|
||||
$response = [
|
||||
'success' => true,
|
||||
'data' => $result,
|
||||
'message' => $message,
|
||||
];
|
||||
|
||||
return response()->json($response, $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Error response method
|
||||
*/
|
||||
public function sendError(string $error, array $errorMessages = [], int $code = 400): JsonResponse
|
||||
{
|
||||
$response = [
|
||||
'success' => false,
|
||||
'message' => $error,
|
||||
];
|
||||
|
||||
if (!empty($errorMessages)) {
|
||||
$response['errors'] = $errorMessages;
|
||||
}
|
||||
|
||||
return response()->json($response, $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validation error response method
|
||||
*/
|
||||
public function sendValidationError(array $errors): JsonResponse
|
||||
{
|
||||
return $this->sendError('Validation failed', $errors, 422);
|
||||
}
|
||||
|
||||
/**
|
||||
* Not found response method
|
||||
*/
|
||||
public function sendNotFound(string $message = 'Resource not found'): JsonResponse
|
||||
{
|
||||
return $this->sendError($message, [], 404);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unauthorized response method
|
||||
*/
|
||||
public function sendUnauthorized(string $message = 'Unauthorized'): JsonResponse
|
||||
{
|
||||
return $this->sendError($message, [], 401);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Feed;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Services\DashboardStatsService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class DashboardController extends BaseController
|
||||
{
|
||||
public function __construct(
|
||||
private DashboardStatsService $dashboardStatsService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get dashboard statistics
|
||||
*/
|
||||
public function stats(Request $request): JsonResponse
|
||||
{
|
||||
$period = $request->get('period', 'today');
|
||||
|
||||
try {
|
||||
// Get article stats from service
|
||||
$articleStats = $this->dashboardStatsService->getStats($period);
|
||||
|
||||
// Get system stats
|
||||
$systemStats = $this->dashboardStatsService->getSystemStats();
|
||||
|
||||
// Get available periods
|
||||
$availablePeriods = $this->dashboardStatsService->getAvailablePeriods();
|
||||
|
||||
return $this->sendResponse([
|
||||
'article_stats' => $articleStats,
|
||||
'system_stats' => $systemStats,
|
||||
'available_periods' => $availablePeriods,
|
||||
'current_period' => $period,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
throw $e;
|
||||
return $this->sendError('Failed to fetch dashboard stats: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Requests\StoreFeedRequest;
|
||||
use App\Http\Requests\UpdateFeedRequest;
|
||||
use App\Http\Resources\FeedResource;
|
||||
use App\Models\Feed;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class FeedsController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display a listing of feeds
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$perPage = min($request->get('per_page', 15), 100);
|
||||
|
||||
$feeds = Feed::with(['language'])
|
||||
->withCount('articles')
|
||||
->orderBy('is_active', 'desc')
|
||||
->orderBy('name')
|
||||
->paginate($perPage);
|
||||
|
||||
return $this->sendResponse([
|
||||
'feeds' => FeedResource::collection($feeds->items()),
|
||||
'pagination' => [
|
||||
'current_page' => $feeds->currentPage(),
|
||||
'last_page' => $feeds->lastPage(),
|
||||
'per_page' => $feeds->perPage(),
|
||||
'total' => $feeds->total(),
|
||||
'from' => $feeds->firstItem(),
|
||||
'to' => $feeds->lastItem(),
|
||||
]
|
||||
], 'Feeds retrieved successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created feed
|
||||
*/
|
||||
public function store(StoreFeedRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
$validated['is_active'] = $validated['is_active'] ?? true;
|
||||
|
||||
// Map provider to URL and set type
|
||||
$providers = [
|
||||
'vrt' => new \App\Services\Parsers\VrtHomepageParserAdapter(),
|
||||
'belga' => new \App\Services\Parsers\BelgaHomepageParserAdapter(),
|
||||
];
|
||||
|
||||
$adapter = $providers[$validated['provider']];
|
||||
$validated['url'] = $adapter->getHomepageUrl();
|
||||
$validated['type'] = 'website';
|
||||
|
||||
$feed = Feed::create($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
new FeedResource($feed),
|
||||
'Feed created successfully!',
|
||||
201
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to create feed: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified feed
|
||||
*/
|
||||
public function show(Feed $feed): JsonResponse
|
||||
{
|
||||
return $this->sendResponse(
|
||||
new FeedResource($feed),
|
||||
'Feed retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified feed
|
||||
*/
|
||||
public function update(UpdateFeedRequest $request, Feed $feed): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
$validated['is_active'] = $validated['is_active'] ?? $feed->is_active;
|
||||
|
||||
$feed->update($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
new FeedResource($feed->fresh()),
|
||||
'Feed updated successfully!'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to update feed: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified feed
|
||||
*/
|
||||
public function destroy(Feed $feed): JsonResponse
|
||||
{
|
||||
try {
|
||||
$feed->delete();
|
||||
|
||||
return $this->sendResponse(
|
||||
null,
|
||||
'Feed deleted successfully!'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to delete feed: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle feed active status
|
||||
*/
|
||||
public function toggle(Feed $feed): JsonResponse
|
||||
{
|
||||
try {
|
||||
$newStatus = !$feed->is_active;
|
||||
$feed->update(['is_active' => $newStatus]);
|
||||
|
||||
$status = $newStatus ? 'activated' : 'deactivated';
|
||||
|
||||
return $this->sendResponse(
|
||||
new FeedResource($feed->fresh()),
|
||||
"Feed {$status} successfully!"
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to toggle feed status: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Models\Feed;
|
||||
use App\Models\Keyword;
|
||||
use App\Models\PlatformChannel;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class KeywordsController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display keywords for a specific route
|
||||
*/
|
||||
public function index(Feed $feed, PlatformChannel $channel): JsonResponse
|
||||
{
|
||||
$keywords = Keyword::where('feed_id', $feed->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->orderBy('keyword')
|
||||
->get();
|
||||
|
||||
return $this->sendResponse(
|
||||
$keywords->toArray(),
|
||||
'Keywords retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a new keyword for a route
|
||||
*/
|
||||
public function store(Request $request, Feed $feed, PlatformChannel $channel): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'keyword' => 'required|string|max:255',
|
||||
'is_active' => 'boolean',
|
||||
]);
|
||||
|
||||
$validated['feed_id'] = $feed->id;
|
||||
$validated['platform_channel_id'] = $channel->id;
|
||||
$validated['is_active'] = $validated['is_active'] ?? true;
|
||||
|
||||
// Check if keyword already exists for this route
|
||||
$existingKeyword = Keyword::where('feed_id', $feed->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->where('keyword', $validated['keyword'])
|
||||
->first();
|
||||
|
||||
if ($existingKeyword) {
|
||||
return $this->sendError('Keyword already exists for this route.', [], 409);
|
||||
}
|
||||
|
||||
$keyword = Keyword::create($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
$keyword->toArray(),
|
||||
'Keyword created successfully!',
|
||||
201
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to create keyword: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a keyword's status
|
||||
*/
|
||||
public function update(Request $request, Feed $feed, PlatformChannel $channel, Keyword $keyword): JsonResponse
|
||||
{
|
||||
try {
|
||||
// Verify the keyword belongs to this route
|
||||
if ($keyword->feed_id !== $feed->id || $keyword->platform_channel_id !== $channel->id) {
|
||||
return $this->sendNotFound('Keyword not found for this route.');
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'is_active' => 'boolean',
|
||||
]);
|
||||
|
||||
$keyword->update($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
$keyword->fresh()->toArray(),
|
||||
'Keyword updated successfully!'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to update keyword: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a keyword from a route
|
||||
*/
|
||||
public function destroy(Feed $feed, PlatformChannel $channel, Keyword $keyword): JsonResponse
|
||||
{
|
||||
try {
|
||||
// Verify the keyword belongs to this route
|
||||
if ($keyword->feed_id !== $feed->id || $keyword->platform_channel_id !== $channel->id) {
|
||||
return $this->sendNotFound('Keyword not found for this route.');
|
||||
}
|
||||
|
||||
$keyword->delete();
|
||||
|
||||
return $this->sendResponse(
|
||||
null,
|
||||
'Keyword deleted successfully!'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to delete keyword: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle keyword active status
|
||||
*/
|
||||
public function toggle(Feed $feed, PlatformChannel $channel, Keyword $keyword): JsonResponse
|
||||
{
|
||||
try {
|
||||
// Verify the keyword belongs to this route
|
||||
if ($keyword->feed_id !== $feed->id || $keyword->platform_channel_id !== $channel->id) {
|
||||
return $this->sendNotFound('Keyword not found for this route.');
|
||||
}
|
||||
|
||||
$newStatus = !$keyword->is_active;
|
||||
$keyword->update(['is_active' => $newStatus]);
|
||||
|
||||
$status = $newStatus ? 'activated' : 'deactivated';
|
||||
|
||||
return $this->sendResponse(
|
||||
$keyword->fresh()->toArray(),
|
||||
"Keyword {$status} successfully!"
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to toggle keyword status: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Models\Log;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class LogsController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display a listing of logs
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
// Clamp per_page between 1 and 100 and ensure integer
|
||||
$perPage = (int) $request->query('per_page', 20);
|
||||
if ($perPage < 1) {
|
||||
$perPage = 20;
|
||||
}
|
||||
$perPage = min($perPage, 100);
|
||||
|
||||
$level = $request->query('level');
|
||||
|
||||
// Stable ordering: created_at desc, then id desc for deterministic results
|
||||
$query = Log::orderBy('created_at', 'desc')
|
||||
->orderBy('id', 'desc');
|
||||
|
||||
// Exclude known system/console noise that may appear during test bootstrap
|
||||
$query->where('message', '!=', 'No active feeds found. Article discovery skipped.');
|
||||
|
||||
if ($level) {
|
||||
$query->where('level', $level);
|
||||
}
|
||||
|
||||
$logs = $query->paginate($perPage);
|
||||
|
||||
return $this->sendResponse([
|
||||
'logs' => $logs->items(),
|
||||
'pagination' => [
|
||||
'current_page' => $logs->currentPage(),
|
||||
// Ensure last_page is at least 1 to satisfy empty dataset expectation
|
||||
'last_page' => max(1, $logs->lastPage()),
|
||||
'per_page' => $logs->perPage(),
|
||||
'total' => $logs->total(),
|
||||
'from' => $logs->firstItem(),
|
||||
'to' => $logs->lastItem(),
|
||||
],
|
||||
], 'Logs retrieved successfully.');
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to retrieve logs: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,388 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Requests\StoreFeedRequest;
|
||||
use App\Http\Resources\FeedResource;
|
||||
use App\Http\Resources\PlatformAccountResource;
|
||||
use App\Http\Resources\PlatformChannelResource;
|
||||
use App\Http\Resources\RouteResource;
|
||||
use App\Jobs\ArticleDiscoveryJob;
|
||||
use App\Models\Feed;
|
||||
use App\Models\Language;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Models\Route;
|
||||
use App\Models\Setting;
|
||||
use App\Services\Auth\LemmyAuthService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class OnboardingController extends BaseController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LemmyAuthService $lemmyAuthService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get onboarding status - whether user needs onboarding
|
||||
*/
|
||||
public function status(): JsonResponse
|
||||
{
|
||||
$hasPlatformAccount = PlatformAccount::where('is_active', true)->exists();
|
||||
$hasFeed = Feed::where('is_active', true)->exists();
|
||||
$hasChannel = PlatformChannel::where('is_active', true)->exists();
|
||||
$hasRoute = Route::where('is_active', true)->exists();
|
||||
|
||||
// Check if onboarding was explicitly skipped or completed
|
||||
$onboardingSkipped = Setting::where('key', 'onboarding_skipped')->value('value') === 'true';
|
||||
$onboardingCompleted = Setting::where('key', 'onboarding_completed')->exists();
|
||||
|
||||
// User needs onboarding if:
|
||||
// 1. They haven't completed or skipped onboarding AND
|
||||
// 2. They don't have all required components
|
||||
$hasAllComponents = $hasPlatformAccount && $hasFeed && $hasChannel && $hasRoute;
|
||||
$needsOnboarding = !$onboardingCompleted && !$onboardingSkipped && !$hasAllComponents;
|
||||
|
||||
// Determine current step
|
||||
$currentStep = null;
|
||||
if ($needsOnboarding) {
|
||||
if (!$hasPlatformAccount) {
|
||||
$currentStep = 'platform';
|
||||
} elseif (!$hasFeed) {
|
||||
$currentStep = 'feed';
|
||||
} elseif (!$hasChannel) {
|
||||
$currentStep = 'channel';
|
||||
} elseif (!$hasRoute) {
|
||||
$currentStep = 'route';
|
||||
}
|
||||
}
|
||||
|
||||
return $this->sendResponse([
|
||||
'needs_onboarding' => $needsOnboarding,
|
||||
'current_step' => $currentStep,
|
||||
'has_platform_account' => $hasPlatformAccount,
|
||||
'has_feed' => $hasFeed,
|
||||
'has_channel' => $hasChannel,
|
||||
'has_route' => $hasRoute,
|
||||
'onboarding_skipped' => $onboardingSkipped,
|
||||
'onboarding_completed' => $onboardingCompleted,
|
||||
'missing_components' => !$hasAllComponents && $onboardingCompleted,
|
||||
], 'Onboarding status retrieved successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get onboarding options (languages, platform instances)
|
||||
*/
|
||||
public function options(): JsonResponse
|
||||
{
|
||||
$languages = Language::where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get(['id', 'short_code', 'name', 'native_name', 'is_active']);
|
||||
|
||||
$platformInstances = PlatformInstance::where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get(['id', 'platform', 'url', 'name', 'description', 'is_active']);
|
||||
|
||||
// Get existing feeds and channels for route creation
|
||||
$feeds = Feed::where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get(['id', 'name', 'url', 'type']);
|
||||
|
||||
$platformChannels = PlatformChannel::where('is_active', true)
|
||||
->with(['platformInstance:id,name,url'])
|
||||
->orderBy('name')
|
||||
->get(['id', 'platform_instance_id', 'name', 'display_name', 'description']);
|
||||
|
||||
// Get feed providers from config
|
||||
$feedProviders = collect(config('feed.providers', []))
|
||||
->filter(fn($provider) => $provider['is_active'])
|
||||
->values();
|
||||
|
||||
return $this->sendResponse([
|
||||
'languages' => $languages,
|
||||
'platform_instances' => $platformInstances,
|
||||
'feeds' => $feeds,
|
||||
'platform_channels' => $platformChannels,
|
||||
'feed_providers' => $feedProviders,
|
||||
], 'Onboarding options retrieved successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create platform account for onboarding
|
||||
*/
|
||||
public function createPlatform(Request $request): JsonResponse
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'instance_url' => 'required|string|max:255|regex:/^[a-zA-Z0-9]([a-zA-Z0-9\-\.]*[a-zA-Z0-9])?$/',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'required|string|min:6',
|
||||
'platform' => 'required|in:lemmy',
|
||||
], [
|
||||
'instance_url.regex' => 'Please enter a valid domain name (e.g., lemmy.world, belgae.social)'
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
throw new ValidationException($validator);
|
||||
}
|
||||
|
||||
$validated = $validator->validated();
|
||||
|
||||
// Normalize the instance URL - prepend https:// if needed
|
||||
$instanceDomain = $validated['instance_url'];
|
||||
$fullInstanceUrl = 'https://' . $instanceDomain;
|
||||
|
||||
try {
|
||||
// Create or get platform instance
|
||||
$platformInstance = PlatformInstance::firstOrCreate([
|
||||
'url' => $fullInstanceUrl,
|
||||
'platform' => $validated['platform'],
|
||||
], [
|
||||
'name' => ucfirst($instanceDomain),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Authenticate with Lemmy API using the full URL
|
||||
$authResponse = $this->lemmyAuthService->authenticate(
|
||||
$fullInstanceUrl,
|
||||
$validated['username'],
|
||||
$validated['password']
|
||||
);
|
||||
|
||||
// Create platform account with the current schema
|
||||
$platformAccount = PlatformAccount::create([
|
||||
'platform' => $validated['platform'],
|
||||
'instance_url' => $fullInstanceUrl,
|
||||
'username' => $validated['username'],
|
||||
'password' => $validated['password'],
|
||||
'settings' => [
|
||||
'display_name' => $authResponse['person_view']['person']['display_name'] ?? null,
|
||||
'description' => $authResponse['person_view']['person']['bio'] ?? null,
|
||||
'person_id' => $authResponse['person_view']['person']['id'] ?? null,
|
||||
'platform_instance_id' => $platformInstance->id,
|
||||
'api_token' => $authResponse['jwt'] ?? null, // Store JWT in settings for now
|
||||
],
|
||||
'is_active' => true,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformAccountResource($platformAccount),
|
||||
'Platform account created successfully.'
|
||||
);
|
||||
|
||||
} catch (\App\Exceptions\PlatformAuthException $e) {
|
||||
// Check if it's a rate limit error
|
||||
if (str_contains($e->getMessage(), 'Rate limited by')) {
|
||||
return $this->sendError($e->getMessage(), [], 429);
|
||||
}
|
||||
|
||||
return $this->sendError('Invalid username or password. Please check your credentials and try again.', [], 422);
|
||||
} catch (\Exception $e) {
|
||||
|
||||
$message = 'Unable to connect to the Lemmy instance. Please check the URL and try again.';
|
||||
|
||||
// If it's a network/connection issue, provide a more specific message
|
||||
if (str_contains(strtolower($e->getMessage()), 'connection') ||
|
||||
str_contains(strtolower($e->getMessage()), 'network') ||
|
||||
str_contains(strtolower($e->getMessage()), 'timeout')) {
|
||||
$message = 'Connection failed. Please check the instance URL and your internet connection.';
|
||||
}
|
||||
|
||||
return $this->sendError($message, [], 422);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create feed for onboarding
|
||||
*/
|
||||
public function createFeed(Request $request): JsonResponse
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'name' => 'required|string|max:255',
|
||||
'provider' => 'required|in:belga,vrt',
|
||||
'language_id' => 'required|exists:languages,id',
|
||||
'description' => 'nullable|string|max:1000',
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
throw new ValidationException($validator);
|
||||
}
|
||||
|
||||
$validated = $validator->validated();
|
||||
|
||||
// Map provider to preset URL and type as required by onboarding tests
|
||||
$provider = $validated['provider'];
|
||||
$url = null;
|
||||
$type = 'website';
|
||||
if ($provider === 'vrt') {
|
||||
$url = 'https://www.vrt.be/vrtnws/en/';
|
||||
} elseif ($provider === 'belga') {
|
||||
$url = 'https://www.belganewsagency.eu/';
|
||||
}
|
||||
|
||||
$feed = Feed::firstOrCreate(
|
||||
['url' => $url],
|
||||
[
|
||||
'name' => $validated['name'],
|
||||
'type' => $type,
|
||||
'provider' => $provider,
|
||||
'language_id' => $validated['language_id'],
|
||||
'description' => $validated['description'] ?? null,
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
return $this->sendResponse(
|
||||
new FeedResource($feed->load('language')),
|
||||
'Feed created successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create channel for onboarding
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function createChannel(Request $request): JsonResponse
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'name' => 'required|string|max:255',
|
||||
'platform_instance_id' => 'required|exists:platform_instances,id',
|
||||
'language_id' => 'required|exists:languages,id',
|
||||
'description' => 'nullable|string|max:1000',
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
throw new ValidationException($validator);
|
||||
}
|
||||
|
||||
$validated = $validator->validated();
|
||||
|
||||
// Get the platform instance to check for active accounts
|
||||
$platformInstance = PlatformInstance::findOrFail($validated['platform_instance_id']);
|
||||
|
||||
// Check if there are active platform accounts for this instance
|
||||
$activeAccounts = PlatformAccount::where('instance_url', $platformInstance->url)
|
||||
->where('is_active', true)
|
||||
->get();
|
||||
|
||||
if ($activeAccounts->isEmpty()) {
|
||||
return $this->sendError(
|
||||
'Cannot create channel: No active platform accounts found for this instance. Please create a platform account first.',
|
||||
[],
|
||||
422
|
||||
);
|
||||
}
|
||||
|
||||
$channel = PlatformChannel::create([
|
||||
'platform_instance_id' => $validated['platform_instance_id'],
|
||||
'channel_id' => $validated['name'], // For Lemmy, this is the community name
|
||||
'name' => $validated['name'],
|
||||
'display_name' => ucfirst($validated['name']),
|
||||
'description' => $validated['description'] ?? null,
|
||||
'language_id' => $validated['language_id'],
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Automatically attach the first active account to the channel
|
||||
$firstAccount = $activeAccounts->first();
|
||||
$channel->platformAccounts()->attach($firstAccount->id, [
|
||||
'is_active' => true,
|
||||
'priority' => 1,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($channel->load(['platformInstance', 'language', 'platformAccounts'])),
|
||||
'Channel created successfully and linked to platform account.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create route for onboarding
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function createRoute(Request $request): JsonResponse
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'feed_id' => 'required|exists:feeds,id',
|
||||
'platform_channel_id' => 'required|exists:platform_channels,id',
|
||||
'priority' => 'nullable|integer|min:1|max:100',
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
throw new ValidationException($validator);
|
||||
}
|
||||
|
||||
$validated = $validator->validated();
|
||||
|
||||
$route = Route::create([
|
||||
'feed_id' => $validated['feed_id'],
|
||||
'platform_channel_id' => $validated['platform_channel_id'],
|
||||
'priority' => $validated['priority'] ?? 50,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Trigger article discovery when the first route is created during onboarding
|
||||
// This ensures articles start being fetched immediately after setup
|
||||
ArticleDiscoveryJob::dispatch();
|
||||
|
||||
return $this->sendResponse(
|
||||
new RouteResource($route->load(['feed', 'platformChannel'])),
|
||||
'Route created successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark onboarding as complete
|
||||
*/
|
||||
public function complete(): JsonResponse
|
||||
{
|
||||
// Track that onboarding has been completed with a timestamp
|
||||
Setting::updateOrCreate(
|
||||
['key' => 'onboarding_completed'],
|
||||
['value' => now()->toIso8601String()]
|
||||
);
|
||||
|
||||
return $this->sendResponse(
|
||||
['completed' => true],
|
||||
'Onboarding completed successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip onboarding - user can access the app without completing setup
|
||||
*/
|
||||
public function skip(): JsonResponse
|
||||
{
|
||||
Setting::updateOrCreate(
|
||||
['key' => 'onboarding_skipped'],
|
||||
['value' => 'true']
|
||||
);
|
||||
|
||||
return $this->sendResponse(
|
||||
['skipped' => true],
|
||||
'Onboarding skipped successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset onboarding skip status - force user back to onboarding
|
||||
*/
|
||||
public function resetSkip(): JsonResponse
|
||||
{
|
||||
Setting::where('key', 'onboarding_skipped')->delete();
|
||||
// Also reset completion status to allow re-onboarding
|
||||
Setting::where('key', 'onboarding_completed')->delete();
|
||||
|
||||
return $this->sendResponse(
|
||||
['reset' => true],
|
||||
'Onboarding status reset successfully.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\PlatformEnum;
|
||||
use App\Http\Resources\PlatformAccountResource;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformInstance;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PlatformAccountsController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display a listing of platform accounts
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$accounts = PlatformAccount::orderBy('platform')
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
|
||||
return $this->sendResponse(
|
||||
PlatformAccountResource::collection($accounts),
|
||||
'Platform accounts retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created platform account
|
||||
*/
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'platform' => 'required|in:lemmy,mastodon,reddit',
|
||||
'instance_url' => 'required|url',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'required|string',
|
||||
'settings' => 'nullable|array',
|
||||
]);
|
||||
|
||||
// Create or find platform instance
|
||||
$platformEnum = PlatformEnum::from($validated['platform']);
|
||||
$instance = PlatformInstance::firstOrCreate([
|
||||
'platform' => $platformEnum,
|
||||
'url' => $validated['instance_url'],
|
||||
], [
|
||||
'name' => parse_url($validated['instance_url'], PHP_URL_HOST),
|
||||
'description' => ucfirst($validated['platform']) . ' instance',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$account = PlatformAccount::create($validated);
|
||||
|
||||
// If this is the first account for this platform, make it active
|
||||
if (!PlatformAccount::where('platform', $validated['platform'])
|
||||
->where('is_active', true)
|
||||
->exists()) {
|
||||
$account->setAsActive();
|
||||
}
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformAccountResource($account),
|
||||
'Platform account created successfully!',
|
||||
201
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to create platform account: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified platform account
|
||||
*/
|
||||
public function show(PlatformAccount $platformAccount): JsonResponse
|
||||
{
|
||||
return $this->sendResponse(
|
||||
new PlatformAccountResource($platformAccount),
|
||||
'Platform account retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified platform account
|
||||
*/
|
||||
public function update(Request $request, PlatformAccount $platformAccount): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'instance_url' => 'required|url',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'nullable|string',
|
||||
'settings' => 'nullable|array',
|
||||
]);
|
||||
|
||||
// Don't update password if not provided
|
||||
if (empty($validated['password'])) {
|
||||
unset($validated['password']);
|
||||
}
|
||||
|
||||
$platformAccount->update($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformAccountResource($platformAccount->fresh()),
|
||||
'Platform account updated successfully!'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to update platform account: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified platform account
|
||||
*/
|
||||
public function destroy(PlatformAccount $platformAccount): JsonResponse
|
||||
{
|
||||
try {
|
||||
$platformAccount->delete();
|
||||
|
||||
return $this->sendResponse(
|
||||
null,
|
||||
'Platform account deleted successfully!'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to delete platform account: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set platform account as active
|
||||
*/
|
||||
public function setActive(PlatformAccount $platformAccount): JsonResponse
|
||||
{
|
||||
try {
|
||||
$platformAccount->setAsActive();
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformAccountResource($platformAccount->fresh()),
|
||||
"Set {$platformAccount->username}@{$platformAccount->instance_url} as active for {$platformAccount->platform->value}!"
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to set platform account as active: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,249 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Resources\PlatformChannelResource;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\PlatformAccount;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class PlatformChannelsController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display a listing of platform channels
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$channels = PlatformChannel::with(['platformInstance', 'platformAccounts'])
|
||||
->orderBy('is_active', 'desc')
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return $this->sendResponse(
|
||||
PlatformChannelResource::collection($channels),
|
||||
'Platform channels retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created platform channel
|
||||
*/
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'platform_instance_id' => 'required|exists:platform_instances,id',
|
||||
'channel_id' => 'required|string|max:255',
|
||||
'name' => 'required|string|max:255',
|
||||
'display_name' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'boolean',
|
||||
]);
|
||||
|
||||
$validated['is_active'] = $validated['is_active'] ?? true;
|
||||
|
||||
// Get the platform instance to check for active accounts
|
||||
$platformInstance = \App\Models\PlatformInstance::findOrFail($validated['platform_instance_id']);
|
||||
|
||||
// Check if there are active platform accounts for this instance
|
||||
$activeAccounts = PlatformAccount::where('instance_url', $platformInstance->url)
|
||||
->where('is_active', true)
|
||||
->get();
|
||||
|
||||
if ($activeAccounts->isEmpty()) {
|
||||
return $this->sendError(
|
||||
'Cannot create channel: No active platform accounts found for this instance. Please create a platform account first.',
|
||||
[],
|
||||
422
|
||||
);
|
||||
}
|
||||
|
||||
$channel = PlatformChannel::create($validated);
|
||||
|
||||
// Automatically attach the first active account to the channel
|
||||
$firstAccount = $activeAccounts->first();
|
||||
$channel->platformAccounts()->attach($firstAccount->id, [
|
||||
'is_active' => true,
|
||||
'priority' => 1,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($channel->load(['platformInstance', 'platformAccounts'])),
|
||||
'Platform channel created successfully and linked to platform account!',
|
||||
201
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to create platform channel: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified platform channel
|
||||
*/
|
||||
public function show(PlatformChannel $platformChannel): JsonResponse
|
||||
{
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($platformChannel->load('platformInstance')),
|
||||
'Platform channel retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified platform channel
|
||||
*/
|
||||
public function update(Request $request, PlatformChannel $platformChannel): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'display_name' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'boolean',
|
||||
]);
|
||||
|
||||
$platformChannel->update($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($platformChannel->fresh(['platformInstance'])),
|
||||
'Platform channel updated successfully!'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to update platform channel: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified platform channel
|
||||
*/
|
||||
public function destroy(PlatformChannel $platformChannel): JsonResponse
|
||||
{
|
||||
try {
|
||||
$platformChannel->delete();
|
||||
|
||||
return $this->sendResponse(
|
||||
null,
|
||||
'Platform channel deleted successfully!'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to delete platform channel: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle platform channel active status
|
||||
*/
|
||||
public function toggle(PlatformChannel $channel): JsonResponse
|
||||
{
|
||||
try {
|
||||
$newStatus = !$channel->is_active;
|
||||
$channel->update(['is_active' => $newStatus]);
|
||||
|
||||
$status = $newStatus ? 'activated' : 'deactivated';
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($channel->fresh(['platformInstance', 'platformAccounts'])),
|
||||
"Platform channel {$status} successfully!"
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to toggle platform channel status: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach a platform account to a channel
|
||||
*/
|
||||
public function attachAccount(PlatformChannel $channel, Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'platform_account_id' => 'required|exists:platform_accounts,id',
|
||||
'is_active' => 'boolean',
|
||||
'priority' => 'nullable|integer|min:1|max:100',
|
||||
]);
|
||||
|
||||
$platformAccount = PlatformAccount::findOrFail($validated['platform_account_id']);
|
||||
|
||||
// Check if account is already attached
|
||||
if ($channel->platformAccounts()->where('platform_account_id', $platformAccount->id)->exists()) {
|
||||
return $this->sendError('Platform account is already attached to this channel.', [], 422);
|
||||
}
|
||||
|
||||
$channel->platformAccounts()->attach($platformAccount->id, [
|
||||
'is_active' => $validated['is_active'] ?? true,
|
||||
'priority' => $validated['priority'] ?? 1,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($channel->fresh(['platformInstance', 'platformAccounts'])),
|
||||
'Platform account attached to channel successfully!'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to attach platform account: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detach a platform account from a channel
|
||||
*/
|
||||
public function detachAccount(PlatformChannel $channel, PlatformAccount $account): JsonResponse
|
||||
{
|
||||
try {
|
||||
if (!$channel->platformAccounts()->where('platform_account_id', $account->id)->exists()) {
|
||||
return $this->sendError('Platform account is not attached to this channel.', [], 422);
|
||||
}
|
||||
|
||||
$channel->platformAccounts()->detach($account->id);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($channel->fresh(['platformInstance', 'platformAccounts'])),
|
||||
'Platform account detached from channel successfully!'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to detach platform account: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update platform account-channel relationship settings
|
||||
*/
|
||||
public function updateAccountRelation(PlatformChannel $channel, PlatformAccount $account, Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'is_active' => 'boolean',
|
||||
'priority' => 'nullable|integer|min:1|max:100',
|
||||
]);
|
||||
|
||||
if (!$channel->platformAccounts()->where('platform_account_id', $account->id)->exists()) {
|
||||
return $this->sendError('Platform account is not attached to this channel.', [], 422);
|
||||
}
|
||||
|
||||
$channel->platformAccounts()->updateExistingPivot($account->id, [
|
||||
'is_active' => $validated['is_active'] ?? true,
|
||||
'priority' => $validated['priority'] ?? 1,
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return $this->sendResponse(
|
||||
new PlatformChannelResource($channel->fresh(['platformInstance', 'platformAccounts'])),
|
||||
'Platform account-channel relationship updated successfully!'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to update platform account relationship: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,174 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Resources\RouteResource;
|
||||
use App\Models\Feed;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\Route;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class RoutingController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display a listing of routing configurations
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$routes = Route::with(['feed', 'platformChannel', 'keywords'])
|
||||
->orderBy('is_active', 'desc')
|
||||
->orderBy('priority', 'asc')
|
||||
->get();
|
||||
|
||||
return $this->sendResponse(
|
||||
RouteResource::collection($routes),
|
||||
'Routing configurations retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created routing configuration
|
||||
*/
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'feed_id' => 'required|exists:feeds,id',
|
||||
'platform_channel_id' => 'required|exists:platform_channels,id',
|
||||
'is_active' => 'boolean',
|
||||
'priority' => 'nullable|integer|min:0',
|
||||
]);
|
||||
|
||||
$validated['is_active'] = $validated['is_active'] ?? true;
|
||||
$validated['priority'] = $validated['priority'] ?? 0;
|
||||
|
||||
$route = Route::create($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
new RouteResource($route->load(['feed', 'platformChannel', 'keywords'])),
|
||||
'Routing configuration created successfully!',
|
||||
201
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to create routing configuration: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified routing configuration
|
||||
*/
|
||||
public function show(Feed $feed, PlatformChannel $channel): JsonResponse
|
||||
{
|
||||
$route = $this->findRoute($feed, $channel);
|
||||
|
||||
if (!$route) {
|
||||
return $this->sendNotFound('Routing configuration not found.');
|
||||
}
|
||||
|
||||
$route->load(['feed', 'platformChannel', 'keywords']);
|
||||
|
||||
return $this->sendResponse(
|
||||
new RouteResource($route),
|
||||
'Routing configuration retrieved successfully.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified routing configuration
|
||||
*/
|
||||
public function update(Request $request, Feed $feed, PlatformChannel $channel): JsonResponse
|
||||
{
|
||||
try {
|
||||
$route = $this->findRoute($feed, $channel);
|
||||
|
||||
if (!$route) {
|
||||
return $this->sendNotFound('Routing configuration not found.');
|
||||
}
|
||||
|
||||
$validated = $request->validate([
|
||||
'is_active' => 'boolean',
|
||||
'priority' => 'nullable|integer|min:0',
|
||||
]);
|
||||
|
||||
Route::where('feed_id', $feed->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->update($validated);
|
||||
|
||||
return $this->sendResponse(
|
||||
new RouteResource($route->fresh(['feed', 'platformChannel', 'keywords'])),
|
||||
'Routing configuration updated successfully!'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to update routing configuration: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified routing configuration
|
||||
*/
|
||||
public function destroy(Feed $feed, PlatformChannel $channel): JsonResponse
|
||||
{
|
||||
try {
|
||||
$route = $this->findRoute($feed, $channel);
|
||||
|
||||
if (!$route) {
|
||||
return $this->sendNotFound('Routing configuration not found.');
|
||||
}
|
||||
|
||||
Route::where('feed_id', $feed->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->delete();
|
||||
|
||||
return $this->sendResponse(
|
||||
null,
|
||||
'Routing configuration deleted successfully!'
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to delete routing configuration: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle routing configuration active status
|
||||
*/
|
||||
public function toggle(Feed $feed, PlatformChannel $channel): JsonResponse
|
||||
{
|
||||
try {
|
||||
$route = $this->findRoute($feed, $channel);
|
||||
|
||||
if (!$route) {
|
||||
return $this->sendNotFound('Routing configuration not found.');
|
||||
}
|
||||
|
||||
$newStatus = !$route->is_active;
|
||||
Route::where('feed_id', $feed->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->update(['is_active' => $newStatus]);
|
||||
|
||||
$status = $newStatus ? 'activated' : 'deactivated';
|
||||
|
||||
return $this->sendResponse(
|
||||
new RouteResource($route->fresh(['feed', 'platformChannel', 'keywords'])),
|
||||
"Routing configuration {$status} successfully!"
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to toggle routing configuration status: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a route by feed and channel
|
||||
*/
|
||||
private function findRoute(Feed $feed, PlatformChannel $channel): ?Route
|
||||
{
|
||||
return Route::where('feed_id', $feed->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->first();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class SettingsController extends BaseController
|
||||
{
|
||||
/**
|
||||
* Display current settings
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
try {
|
||||
$settings = [
|
||||
'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
|
||||
'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
|
||||
];
|
||||
|
||||
return $this->sendResponse($settings, 'Settings retrieved successfully.');
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to retrieve settings: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update settings
|
||||
*/
|
||||
public function update(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'article_processing_enabled' => 'boolean',
|
||||
'enable_publishing_approvals' => 'boolean',
|
||||
]);
|
||||
|
||||
if (isset($validated['article_processing_enabled'])) {
|
||||
Setting::setArticleProcessingEnabled($validated['article_processing_enabled']);
|
||||
}
|
||||
|
||||
if (isset($validated['enable_publishing_approvals'])) {
|
||||
Setting::setPublishingApprovalsEnabled($validated['enable_publishing_approvals']);
|
||||
}
|
||||
|
||||
$updatedSettings = [
|
||||
'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
|
||||
'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
|
||||
];
|
||||
|
||||
return $this->sendResponse(
|
||||
$updatedSettings,
|
||||
'Settings updated successfully.'
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->sendValidationError($e->errors());
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to update settings: ' . $e->getMessage(), [], 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
37
app/Http/Controllers/ArticlesController.php
Normal file
37
app/Http/Controllers/ArticlesController.php
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ArticlesController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request): View
|
||||
{
|
||||
$articles = Article::with('articlePublication')
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(15);
|
||||
|
||||
$publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();
|
||||
|
||||
return view('pages.articles.index', compact('articles', 'publishingApprovalsEnabled'));
|
||||
}
|
||||
|
||||
public function approve(Article $article): RedirectResponse
|
||||
{
|
||||
$article->approve('manual');
|
||||
|
||||
return redirect()->back()->with('success', 'Article approved and queued for publishing.');
|
||||
}
|
||||
|
||||
public function reject(Article $article): RedirectResponse
|
||||
{
|
||||
$article->reject('manual');
|
||||
|
||||
return redirect()->back()->with('success', 'Article rejected.');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Auth\LoginRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AuthenticatedSessionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the login view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming authentication request.
|
||||
*/
|
||||
public function store(LoginRequest $request): RedirectResponse
|
||||
{
|
||||
$request->authenticate();
|
||||
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->intended(route('dashboard', absolute: false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy an authenticated session.
|
||||
*/
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
Auth::guard('web')->logout();
|
||||
|
||||
$request->session()->invalidate();
|
||||
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect('/');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ConfirmablePasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show the confirm password view.
|
||||
*/
|
||||
public function show(): View
|
||||
{
|
||||
return view('auth.confirm-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm the user's password.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if (! Auth::guard('web')->validate([
|
||||
'email' => $request->user()->email,
|
||||
'password' => $request->password,
|
||||
])) {
|
||||
throw ValidationException::withMessages([
|
||||
'password' => __('auth.password'),
|
||||
]);
|
||||
}
|
||||
|
||||
$request->session()->put('auth.password_confirmed_at', time());
|
||||
|
||||
return redirect()->intended(route('dashboard', absolute: false));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class EmailVerificationNotificationController extends Controller
|
||||
{
|
||||
/**
|
||||
* Send a new email verification notification.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
return redirect()->intended(route('dashboard', absolute: false));
|
||||
}
|
||||
|
||||
$request->user()->sendEmailVerificationNotification();
|
||||
|
||||
return back()->with('status', 'verification-link-sent');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class EmailVerificationPromptController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the email verification prompt.
|
||||
*/
|
||||
public function __invoke(Request $request): RedirectResponse|View
|
||||
{
|
||||
return $request->user()->hasVerifiedEmail()
|
||||
? redirect()->intended(route('dashboard', absolute: false))
|
||||
: view('auth.verify-email');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Events\PasswordReset;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rules;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class NewPasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the password reset view.
|
||||
*/
|
||||
public function create(Request $request): View
|
||||
{
|
||||
return view('auth.reset-password', ['request' => $request]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming new password request.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'token' => ['required'],
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required', 'confirmed', Rules\Password::defaults()],
|
||||
]);
|
||||
|
||||
// Here we will attempt to reset the user's password. If it is successful we
|
||||
// will update the password on an actual user model and persist it to the
|
||||
// database. Otherwise we will parse the error and return the response.
|
||||
$status = Password::reset(
|
||||
$request->only('email', 'password', 'password_confirmation', 'token'),
|
||||
function (User $user) use ($request) {
|
||||
$user->forceFill([
|
||||
'password' => Hash::make($request->password),
|
||||
'remember_token' => Str::random(60),
|
||||
])->save();
|
||||
|
||||
event(new PasswordReset($user));
|
||||
}
|
||||
);
|
||||
|
||||
// If the password was successfully reset, we will redirect the user back to
|
||||
// the application's home authenticated view. If there is an error we can
|
||||
// redirect them back to where they came from with their error message.
|
||||
return $status == Password::PASSWORD_RESET
|
||||
? redirect()->route('login')->with('status', __($status))
|
||||
: back()->withInput($request->only('email'))
|
||||
->withErrors(['email' => __($status)]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class PasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Update the user's password.
|
||||
*/
|
||||
public function update(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validateWithBag('updatePassword', [
|
||||
'current_password' => ['required', 'current_password'],
|
||||
'password' => ['required', Password::defaults(), 'confirmed'],
|
||||
]);
|
||||
|
||||
$request->user()->update([
|
||||
'password' => Hash::make($validated['password']),
|
||||
]);
|
||||
|
||||
return back()->with('status', 'password-updated');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class PasswordResetLinkController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the password reset link request view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.forgot-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming password reset link request.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
]);
|
||||
|
||||
// We will send the password reset link to this user. Once we have attempted
|
||||
// to send the link, we will examine the response then see the message we
|
||||
// need to show to the user. Finally, we'll send out a proper response.
|
||||
$status = Password::sendResetLink(
|
||||
$request->only('email')
|
||||
);
|
||||
|
||||
return $status == Password::RESET_LINK_SENT
|
||||
? back()->with('status', __($status))
|
||||
: back()->withInput($request->only('email'))
|
||||
->withErrors(['email' => __($status)]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class RegisteredUserController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the registration view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming registration request.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
|
||||
'password' => ['required', 'confirmed', Rules\Password::defaults()],
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'password' => Hash::make($request->password),
|
||||
]);
|
||||
|
||||
event(new Registered($user));
|
||||
|
||||
Auth::login($user);
|
||||
|
||||
return redirect(route('dashboard', absolute: false));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Auth\Events\Verified;
|
||||
use Illuminate\Foundation\Auth\EmailVerificationRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class VerifyEmailController extends Controller
|
||||
{
|
||||
/**
|
||||
* Mark the authenticated user's email address as verified.
|
||||
*/
|
||||
public function __invoke(EmailVerificationRequest $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
|
||||
}
|
||||
|
||||
if ($request->user()->markEmailAsVerified()) {
|
||||
event(new Verified($request->user()));
|
||||
}
|
||||
|
||||
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
|
||||
}
|
||||
}
|
||||
81
app/Http/Controllers/FeedsController.php
Normal file
81
app/Http/Controllers/FeedsController.php
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Feed;
|
||||
use App\Http\Requests\StoreFeedRequest;
|
||||
use App\Http\Requests\UpdateFeedRequest;
|
||||
use App\Services\OnboardingRedirectService;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class FeedsController extends Controller
|
||||
{
|
||||
public function index(): View
|
||||
{
|
||||
$feeds = Feed::orderBy('is_active', 'desc')
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return view('pages.feeds.index', compact('feeds'));
|
||||
}
|
||||
|
||||
public function create(): View
|
||||
{
|
||||
return view('pages.feeds.create');
|
||||
}
|
||||
|
||||
public function store(StoreFeedRequest $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
$validated['is_active'] = $validated['is_active'] ?? true;
|
||||
|
||||
Feed::create($validated);
|
||||
|
||||
return OnboardingRedirectService::handleRedirect(
|
||||
$request,
|
||||
'feeds.index',
|
||||
'Feed created successfully!'
|
||||
);
|
||||
}
|
||||
|
||||
public function show(Feed $feed): View
|
||||
{
|
||||
return view('pages.feeds.show', compact('feed'));
|
||||
}
|
||||
|
||||
public function edit(Feed $feed): View
|
||||
{
|
||||
return view('pages.feeds.edit', compact('feed'));
|
||||
}
|
||||
|
||||
public function update(UpdateFeedRequest $request, Feed $feed): RedirectResponse
|
||||
{
|
||||
$validated = $request->validated();
|
||||
$validated['is_active'] = $validated['is_active'] ?? $feed->is_active;
|
||||
|
||||
$feed->update($validated);
|
||||
|
||||
return redirect()->route('feeds.index')
|
||||
->with('success', 'Feed updated successfully!');
|
||||
}
|
||||
|
||||
public function destroy(Feed $feed): RedirectResponse
|
||||
{
|
||||
$feed->delete();
|
||||
|
||||
return redirect()->route('feeds.index')
|
||||
->with('success', 'Feed deleted successfully!');
|
||||
}
|
||||
|
||||
public function toggle(Feed $feed): RedirectResponse
|
||||
{
|
||||
$newStatus = !$feed->is_active;
|
||||
$feed->update(['is_active' => $newStatus]);
|
||||
|
||||
$status = $newStatus ? 'activated' : 'deactivated';
|
||||
|
||||
return redirect()->route('feeds.index')
|
||||
->with('success', "Feed {$status} successfully!");
|
||||
}
|
||||
}
|
||||
17
app/Http/Controllers/LogsController.php
Normal file
17
app/Http/Controllers/LogsController.php
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Log;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class LogsController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request): View
|
||||
{
|
||||
$logs = Log::orderBy('created_at', 'desc')->paginate(50);
|
||||
|
||||
return view('pages.logs.index', compact('logs'));
|
||||
}
|
||||
}
|
||||
114
app/Http/Controllers/OnboardingController.php
Normal file
114
app/Http/Controllers/OnboardingController.php
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Feed;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Services\SystemStatusService;
|
||||
use App\Services\DashboardStatsService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class OnboardingController extends Controller
|
||||
{
|
||||
public function index(Request $request): View|RedirectResponse
|
||||
{
|
||||
// Check if user needs onboarding
|
||||
if (!$this->needsOnboarding()) {
|
||||
$systemStatus = resolve(SystemStatusService::class)->getSystemStatus();
|
||||
$statsService = resolve(DashboardStatsService::class);
|
||||
|
||||
$period = $request->get('period', 'today');
|
||||
$stats = $statsService->getStats($period);
|
||||
$systemStats = $statsService->getSystemStats();
|
||||
$availablePeriods = $statsService->getAvailablePeriods();
|
||||
|
||||
return view('pages.dashboard', compact(
|
||||
'systemStatus',
|
||||
'stats',
|
||||
'systemStats',
|
||||
'availablePeriods',
|
||||
'period'
|
||||
));
|
||||
}
|
||||
|
||||
return view('onboarding.welcome');
|
||||
}
|
||||
|
||||
public function platform(): View|RedirectResponse
|
||||
{
|
||||
if (!$this->needsOnboarding()) {
|
||||
return redirect()->route('feeds.index');
|
||||
}
|
||||
|
||||
return view('onboarding.platform');
|
||||
}
|
||||
|
||||
public function feed(): View|RedirectResponse
|
||||
{
|
||||
if (!$this->needsOnboarding()) {
|
||||
return redirect()->route('feeds.index');
|
||||
}
|
||||
|
||||
if (!$this->hasPlatformAccount()) {
|
||||
return redirect()->route('onboarding.platform');
|
||||
}
|
||||
|
||||
return view('onboarding.feed');
|
||||
}
|
||||
|
||||
public function channel(): View|RedirectResponse
|
||||
{
|
||||
if (!$this->needsOnboarding()) {
|
||||
return redirect()->route('feeds.index');
|
||||
}
|
||||
|
||||
if (!$this->hasPlatformAccount()) {
|
||||
return redirect()->route('onboarding.platform');
|
||||
}
|
||||
|
||||
if (!$this->hasFeed()) {
|
||||
return redirect()->route('onboarding.feed');
|
||||
}
|
||||
|
||||
return view('onboarding.channel');
|
||||
}
|
||||
|
||||
public function complete(): View|RedirectResponse
|
||||
{
|
||||
if (!$this->needsOnboarding()) {
|
||||
return redirect()->route('feeds.index');
|
||||
}
|
||||
|
||||
if (!$this->hasPlatformAccount() || !$this->hasFeed() || !$this->hasChannel()) {
|
||||
return redirect()->route('onboarding.index');
|
||||
}
|
||||
|
||||
$systemStatus = resolve(SystemStatusService::class)->getSystemStatus();
|
||||
|
||||
return view('onboarding.complete', compact('systemStatus'));
|
||||
}
|
||||
|
||||
private function needsOnboarding(): bool
|
||||
{
|
||||
return !$this->hasPlatformAccount() || !$this->hasFeed() || !$this->hasChannel();
|
||||
}
|
||||
|
||||
private function hasPlatformAccount(): bool
|
||||
{
|
||||
return PlatformAccount::where('is_active', true)->exists();
|
||||
}
|
||||
|
||||
private function hasFeed(): bool
|
||||
{
|
||||
return Feed::where('is_active', true)->exists();
|
||||
}
|
||||
|
||||
private function hasChannel(): bool
|
||||
{
|
||||
return PlatformChannel::where('is_active', true)->exists();
|
||||
}
|
||||
}
|
||||
106
app/Http/Controllers/PlatformAccountsController.php
Normal file
106
app/Http/Controllers/PlatformAccountsController.php
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Enums\PlatformEnum;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Support\Facades\View as ViewFacade;
|
||||
|
||||
class PlatformAccountsController extends Controller
|
||||
{
|
||||
public function index(): View
|
||||
{
|
||||
$accounts = PlatformAccount::orderBy('platform')->orderBy('created_at', 'desc')->get();
|
||||
|
||||
return view('pages.platforms.index', compact('accounts'));
|
||||
}
|
||||
|
||||
public function create(): View
|
||||
{
|
||||
return ViewFacade::make('pages.platforms.create');
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'platform' => 'required|in:lemmy,mastodon,reddit',
|
||||
'instance_url' => 'required|url',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'required|string',
|
||||
'settings' => 'nullable|array',
|
||||
]);
|
||||
|
||||
// Create or find platform instance
|
||||
$platformEnum = PlatformEnum::from($validated['platform']);
|
||||
$instance = PlatformInstance::firstOrCreate([
|
||||
'platform' => $platformEnum,
|
||||
'url' => $validated['instance_url'],
|
||||
], [
|
||||
'name' => parse_url($validated['instance_url'], PHP_URL_HOST),
|
||||
'description' => ucfirst($validated['platform']) . ' instance',
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$account = PlatformAccount::create($validated);
|
||||
|
||||
// If this is the first account for this platform, make it active
|
||||
if (! PlatformAccount::where('platform', $validated['platform'])->where('is_active', true)->exists()) {
|
||||
$account->setAsActive();
|
||||
}
|
||||
|
||||
// Check if there's a redirect_to parameter for onboarding flow
|
||||
$redirectTo = $request->input('redirect_to');
|
||||
if ($redirectTo) {
|
||||
return redirect($redirectTo)
|
||||
->with('success', 'Platform account created successfully!');
|
||||
}
|
||||
|
||||
return redirect()->route('platforms.index')
|
||||
->with('success', 'Platform account created successfully!');
|
||||
}
|
||||
|
||||
public function edit(PlatformAccount $platformAccount): View
|
||||
{
|
||||
return ViewFacade::make('pages.platforms.edit', compact('platformAccount'));
|
||||
}
|
||||
|
||||
public function update(Request $request, PlatformAccount $platformAccount): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'instance_url' => 'required|url',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'nullable|string',
|
||||
'settings' => 'nullable|array',
|
||||
]);
|
||||
|
||||
// Don't update password if not provided
|
||||
if (empty($validated['password'])) {
|
||||
unset($validated['password']);
|
||||
}
|
||||
|
||||
$platformAccount->update($validated);
|
||||
|
||||
return redirect()->route('platforms.index')
|
||||
->with('success', 'Platform account updated successfully!');
|
||||
}
|
||||
|
||||
public function destroy(PlatformAccount $platformAccount): RedirectResponse
|
||||
{
|
||||
$platformAccount->delete();
|
||||
|
||||
return redirect()->route('platforms.index')
|
||||
->with('success', 'Platform account deleted successfully!');
|
||||
}
|
||||
|
||||
public function setActive(PlatformAccount $platformAccount): RedirectResponse
|
||||
{
|
||||
$platformAccount->setAsActive();
|
||||
|
||||
return redirect()->route('platforms.index')
|
||||
->with('success', "Set $platformAccount->username@$platformAccount->instance_url as active for {$platformAccount->platform->value}!");
|
||||
}
|
||||
}
|
||||
116
app/Http/Controllers/PlatformChannelsController.php
Normal file
116
app/Http/Controllers/PlatformChannelsController.php
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\PlatformInstance;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Support\Facades\View as ViewFacade;
|
||||
|
||||
class PlatformChannelsController extends Controller
|
||||
{
|
||||
public function index(): View
|
||||
{
|
||||
$channels = PlatformChannel::with('platformInstance')
|
||||
->orderBy('platform_instance_id')
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return ViewFacade::make('pages.channels.index', compact('channels'));
|
||||
}
|
||||
|
||||
public function create(): View
|
||||
{
|
||||
$instances = PlatformInstance::where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return ViewFacade::make('pages.channels.create', compact('instances'));
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'platform_instance_id' => 'required|exists:platform_instances,id',
|
||||
'name' => 'required|string|max:255',
|
||||
'display_name' => 'nullable|string|max:255',
|
||||
'channel_id' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'language_id' => 'required|exists:languages,id',
|
||||
'is_active' => 'boolean',
|
||||
]);
|
||||
|
||||
// Default is_active to true if not provided
|
||||
$validated['is_active'] = $validated['is_active'] ?? true;
|
||||
|
||||
// Set display_name to name if not provided
|
||||
$validated['display_name'] = $validated['display_name'] ?? $validated['name'];
|
||||
|
||||
PlatformChannel::create($validated);
|
||||
|
||||
// Check if there's a redirect_to parameter for onboarding flow
|
||||
$redirectTo = $request->input('redirect_to');
|
||||
if ($redirectTo) {
|
||||
return redirect($redirectTo)
|
||||
->with('success', 'Channel created successfully!');
|
||||
}
|
||||
|
||||
return redirect()->route('channels.index')
|
||||
->with('success', 'Channel created successfully!');
|
||||
}
|
||||
|
||||
public function show(PlatformChannel $channel): View
|
||||
{
|
||||
$channel->load(['platformInstance', 'feeds']);
|
||||
|
||||
return ViewFacade::make('pages.channels.show', compact('channel'));
|
||||
}
|
||||
|
||||
public function edit(PlatformChannel $channel): View
|
||||
{
|
||||
$instances = PlatformInstance::where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return ViewFacade::make('pages.channels.edit', compact('channel', 'instances'));
|
||||
}
|
||||
|
||||
public function update(Request $request, PlatformChannel $channel): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'platform_instance_id' => 'required|exists:platform_instances,id',
|
||||
'name' => 'required|string|max:255',
|
||||
'display_name' => 'nullable|string|max:255',
|
||||
'channel_id' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'language_id' => 'required|exists:languages,id',
|
||||
'is_active' => 'boolean',
|
||||
]);
|
||||
|
||||
$channel->update($validated);
|
||||
|
||||
return redirect()->route('channels.index')
|
||||
->with('success', 'Channel updated successfully!');
|
||||
}
|
||||
|
||||
public function destroy(PlatformChannel $channel): RedirectResponse
|
||||
{
|
||||
$channel->delete();
|
||||
|
||||
return redirect()->route('channels.index')
|
||||
->with('success', 'Channel deleted successfully!');
|
||||
}
|
||||
|
||||
public function toggle(PlatformChannel $channel): RedirectResponse
|
||||
{
|
||||
$newStatus = !$channel->is_active;
|
||||
$channel->update(['is_active' => $newStatus]);
|
||||
|
||||
$status = $newStatus ? 'activated' : 'deactivated';
|
||||
|
||||
return redirect()->route('channels.index')
|
||||
->with('success', "Channel {$status} successfully!");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\ProfileUpdateRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Redirect;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the user's profile form.
|
||||
*/
|
||||
public function edit(Request $request): View
|
||||
{
|
||||
return view('profile.edit', [
|
||||
'user' => $request->user(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's profile information.
|
||||
*/
|
||||
public function update(ProfileUpdateRequest $request): RedirectResponse
|
||||
{
|
||||
$request->user()->fill($request->validated());
|
||||
|
||||
if ($request->user()->isDirty('email')) {
|
||||
$request->user()->email_verified_at = null;
|
||||
}
|
||||
|
||||
$request->user()->save();
|
||||
|
||||
return Redirect::route('profile.edit')->with('status', 'profile-updated');
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the user's account.
|
||||
*/
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validateWithBag('userDeletion', [
|
||||
'password' => ['required', 'current_password'],
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
Auth::logout();
|
||||
|
||||
$user->delete();
|
||||
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return Redirect::to('/');
|
||||
}
|
||||
}
|
||||
173
app/Http/Controllers/RoutingController.php
Normal file
173
app/Http/Controllers/RoutingController.php
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Feed;
|
||||
use App\Models\Route;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Services\RoutingValidationService;
|
||||
use App\Exceptions\RoutingMismatchException;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class RoutingController extends Controller
|
||||
{
|
||||
public function index(): View
|
||||
{
|
||||
$feeds = Feed::with(['channels.platformInstance'])
|
||||
->where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
$channels = PlatformChannel::with(['platformInstance', 'feeds'])
|
||||
->where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return view('pages.routing.index', compact('feeds', 'channels'));
|
||||
}
|
||||
|
||||
public function create(): View
|
||||
{
|
||||
$feeds = Feed::where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
$channels = PlatformChannel::with('platformInstance')
|
||||
->where('is_active', true)
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
return view('pages.routing.create', compact('feeds', 'channels'));
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'feed_id' => 'required|exists:feeds,id',
|
||||
'channel_ids' => 'required|array|min:1',
|
||||
'channel_ids.*' => 'exists:platform_channels,id',
|
||||
'priority' => 'integer|min:0|max:100',
|
||||
'filters' => 'nullable|string'
|
||||
]);
|
||||
|
||||
/** @var Feed $feed */
|
||||
$feed = Feed::findOrFail($validated['feed_id']);
|
||||
|
||||
/** @var Collection<int, PlatformChannel> $channels */
|
||||
$channels = PlatformChannel::findMany($validated['channel_ids']);
|
||||
$priority = $validated['priority'] ?? 0;
|
||||
|
||||
try {
|
||||
app(RoutingValidationService::class)->validateLanguageCompatibility($feed, $channels);
|
||||
} catch (RoutingMismatchException $e) {
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->withErrors(['language' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
$filters = $this->parseJsonFilters($validated['filters'] ?? null);
|
||||
|
||||
// Attach channels to feed
|
||||
$syncData = [];
|
||||
foreach ($validated['channel_ids'] as $channelId) {
|
||||
$syncData[$channelId] = [
|
||||
'is_active' => true,
|
||||
'priority' => $priority,
|
||||
'filters' => $filters,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now()
|
||||
];
|
||||
}
|
||||
|
||||
$feed->channels()->syncWithoutDetaching($syncData);
|
||||
|
||||
return redirect()->route('routing.index')
|
||||
->with('success', 'Feed routing created successfully!');
|
||||
}
|
||||
|
||||
public function edit(Feed $feed, PlatformChannel $channel): View
|
||||
{
|
||||
$routing = $feed->channels()
|
||||
->wherePivot('platform_channel_id', $channel->id)
|
||||
->first();
|
||||
|
||||
if (! $routing) {
|
||||
abort(404, 'Routing not found');
|
||||
}
|
||||
|
||||
return view('pages.routing.edit', compact('feed', 'channel', 'routing'));
|
||||
}
|
||||
|
||||
public function update(Request $request, Feed $feed, PlatformChannel $channel): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'is_active' => 'boolean',
|
||||
'priority' => 'integer|min:0|max:100',
|
||||
'filters' => 'nullable|string'
|
||||
]);
|
||||
|
||||
$filters = $this->parseJsonFilters($validated['filters'] ?? null);
|
||||
|
||||
$feed->channels()->updateExistingPivot($channel->id, [
|
||||
'is_active' => $validated['is_active'] ?? true,
|
||||
'priority' => $validated['priority'] ?? 0,
|
||||
'filters' => $filters,
|
||||
'updated_at' => now()
|
||||
]);
|
||||
|
||||
return redirect()->route('routing.index')
|
||||
->with('success', 'Routing updated successfully!');
|
||||
}
|
||||
|
||||
public function destroy(Feed $feed, PlatformChannel $channel): RedirectResponse
|
||||
{
|
||||
$feed->channels()->detach($channel->id);
|
||||
|
||||
return redirect()->route('routing.index')
|
||||
->with('success', 'Routing deleted successfully!');
|
||||
}
|
||||
|
||||
public function toggle(Request $request, Feed $feed, PlatformChannel $channel): RedirectResponse
|
||||
{
|
||||
$routing = Route::where('feed_id', $feed->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->first();
|
||||
|
||||
if (! $routing) {
|
||||
abort(404, 'Routing not found');
|
||||
}
|
||||
|
||||
$newStatus = ! $routing->is_active;
|
||||
|
||||
$feed->channels()->updateExistingPivot($channel->id, [
|
||||
'is_active' => $newStatus,
|
||||
'updated_at' => now()
|
||||
]);
|
||||
|
||||
$status = $newStatus ? 'activated' : 'deactivated';
|
||||
|
||||
return redirect()->route('routing.index')
|
||||
->with('success', "Routing {$status} successfully!");
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function parseJsonFilters(?string $json): ?array
|
||||
{
|
||||
if (empty($json)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decoded = json_decode($json, true);
|
||||
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
39
app/Http/Controllers/SettingsController.php
Normal file
39
app/Http/Controllers/SettingsController.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class SettingsController extends Controller
|
||||
{
|
||||
public function index(): View
|
||||
{
|
||||
$articleProcessingEnabled = Setting::isArticleProcessingEnabled();
|
||||
$publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();
|
||||
|
||||
return view('pages.settings.index', compact('articleProcessingEnabled', 'publishingApprovalsEnabled'));
|
||||
}
|
||||
|
||||
public function update(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'article_processing_enabled' => 'boolean',
|
||||
'enable_publishing_approvals' => 'boolean',
|
||||
]);
|
||||
|
||||
Setting::setArticleProcessingEnabled($request->boolean('article_processing_enabled'));
|
||||
Setting::setPublishingApprovalsEnabled($request->boolean('enable_publishing_approvals'));
|
||||
|
||||
// If redirected from onboarding, go to dashboard
|
||||
if ($request->get('from') === 'onboarding') {
|
||||
return redirect()->route('onboarding.index')
|
||||
->with('success', 'System activated successfully! Welcome to Lemmy Poster.');
|
||||
}
|
||||
|
||||
return redirect()->route('settings.index')
|
||||
->with('success', 'Settings updated successfully.');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\OnboardingService;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EnsureOnboardingComplete
|
||||
{
|
||||
public function __construct(
|
||||
private OnboardingService $onboardingService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* Redirect to onboarding if the user hasn't completed setup.
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if ($this->onboardingService->needsOnboarding()) {
|
||||
return redirect()->route('onboarding');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Middleware;
|
||||
|
||||
class HandleInertiaRequests extends Middleware
|
||||
{
|
||||
/**
|
||||
* The root template that's loaded on the first page visit.
|
||||
*
|
||||
* @see https://inertiajs.com/server-side-setup#root-template
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $rootView = 'app';
|
||||
|
||||
/**
|
||||
* Determines the current asset version.
|
||||
*
|
||||
* @see https://inertiajs.com/asset-versioning
|
||||
*/
|
||||
public function version(Request $request): ?string
|
||||
{
|
||||
return parent::version($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the props that are shared by default.
|
||||
*
|
||||
* @see https://inertiajs.com/shared-data
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function share(Request $request): array
|
||||
{
|
||||
return array_merge(parent::share($request), [
|
||||
//
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\OnboardingService;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RedirectIfOnboardingComplete
|
||||
{
|
||||
public function __construct(
|
||||
private OnboardingService $onboardingService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* Redirect to dashboard if onboarding is already complete.
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (!$this->onboardingService->needsOnboarding()) {
|
||||
return redirect()->route('dashboard');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests\Auth;
|
||||
|
||||
use Illuminate\Auth\Events\Lockout;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class LoginRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to authenticate the request's credentials.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function authenticate(): void
|
||||
{
|
||||
$this->ensureIsNotRateLimited();
|
||||
|
||||
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
|
||||
RateLimiter::hit($this->throttleKey());
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => trans('auth.failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($this->throttleKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the login request is not rate limited.
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
public function ensureIsNotRateLimited(): void
|
||||
{
|
||||
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event(new Lockout($this));
|
||||
|
||||
$seconds = RateLimiter::availableIn($this->throttleKey());
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => trans('auth.throttle', [
|
||||
'seconds' => $seconds,
|
||||
'minutes' => ceil($seconds / 60),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the rate limiting throttle key for the request.
|
||||
*/
|
||||
public function throttleKey(): string
|
||||
{
|
||||
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ProfileUpdateRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => [
|
||||
'required',
|
||||
'string',
|
||||
'lowercase',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique(User::class)->ignore($this->user()->id),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -18,7 +18,8 @@ public function rules(): array
|
|||
{
|
||||
return [
|
||||
'name' => 'required|string|max:255',
|
||||
'provider' => 'required|in:vrt,belga',
|
||||
'url' => 'required|url|unique:feeds,url',
|
||||
'type' => 'required|in:website,rss',
|
||||
'language_id' => 'required|exists:languages,id',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'boolean'
|
||||
|
|
|
|||
|
|
@ -1,26 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ArticlePublicationResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'article_id' => $this->article_id,
|
||||
'status' => $this->status,
|
||||
'published_at' => $this->published_at?->toISOString(),
|
||||
'created_at' => $this->created_at->toISOString(),
|
||||
'updated_at' => $this->updated_at->toISOString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
*/
|
||||
class ArticleResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'feed_id' => $this->feed_id,
|
||||
'url' => $this->url,
|
||||
'title' => $this->title,
|
||||
'description' => $this->description,
|
||||
'is_valid' => $this->is_valid,
|
||||
'is_duplicate' => $this->is_duplicate,
|
||||
'approval_status' => $this->approval_status,
|
||||
'approved_at' => $this->approved_at?->toISOString(),
|
||||
'approved_by' => $this->approved_by,
|
||||
'fetched_at' => $this->fetched_at?->toISOString(),
|
||||
'validated_at' => $this->validated_at?->toISOString(),
|
||||
'is_published' => $this->relationLoaded('articlePublication') && $this->articlePublication !== null,
|
||||
'created_at' => $this->created_at->toISOString(),
|
||||
'updated_at' => $this->updated_at->toISOString(),
|
||||
'feed' => new FeedResource($this->whenLoaded('feed')),
|
||||
'article_publication' => new ArticlePublicationResource($this->whenLoaded('articlePublication')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class FeedResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'url' => $this->url,
|
||||
'type' => $this->type,
|
||||
'provider' => $this->provider,
|
||||
'language_id' => $this->language_id,
|
||||
'is_active' => $this->is_active,
|
||||
'description' => $this->description,
|
||||
'created_at' => $this->created_at->toISOString(),
|
||||
'updated_at' => $this->updated_at->toISOString(),
|
||||
'articles_count' => $this->when(
|
||||
$request->routeIs('api.feeds.*') && isset($this->articles_count),
|
||||
$this->articles_count
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PlatformAccountResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'platform' => $this->platform->value,
|
||||
'instance_url' => $this->instance_url,
|
||||
'username' => $this->username,
|
||||
'settings' => $this->settings,
|
||||
'is_active' => $this->is_active,
|
||||
'last_tested_at' => $this->last_tested_at?->toISOString(),
|
||||
'status' => $this->status,
|
||||
'created_at' => $this->created_at->toISOString(),
|
||||
'updated_at' => $this->updated_at->toISOString(),
|
||||
'channels' => PlatformChannelResource::collection($this->whenLoaded('channels')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PlatformChannelResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'platform_instance_id' => $this->platform_instance_id,
|
||||
'channel_id' => $this->channel_id,
|
||||
'name' => $this->name,
|
||||
'display_name' => $this->display_name,
|
||||
'description' => $this->description,
|
||||
'language_id' => $this->language_id,
|
||||
'is_active' => $this->is_active,
|
||||
'created_at' => $this->created_at->toISOString(),
|
||||
'updated_at' => $this->updated_at->toISOString(),
|
||||
'platform_instance' => new PlatformInstanceResource($this->whenLoaded('platformInstance')),
|
||||
'platform_accounts' => PlatformAccountResource::collection($this->whenLoaded('platformAccounts')),
|
||||
'routes' => RouteResource::collection($this->whenLoaded('routes')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PlatformInstanceResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'url' => $this->url,
|
||||
'description' => $this->description,
|
||||
'is_active' => $this->is_active,
|
||||
'created_at' => $this->created_at->toISOString(),
|
||||
'updated_at' => $this->updated_at->toISOString(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class RouteResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'feed_id' => $this->feed_id,
|
||||
'platform_channel_id' => $this->platform_channel_id,
|
||||
'is_active' => $this->is_active,
|
||||
'priority' => $this->priority,
|
||||
'created_at' => $this->created_at->toISOString(),
|
||||
'updated_at' => $this->updated_at->toISOString(),
|
||||
'feed' => new FeedResource($this->whenLoaded('feed')),
|
||||
'platform_channel' => new PlatformChannelResource($this->whenLoaded('platformChannel')),
|
||||
'keywords' => $this->whenLoaded('keywords', function () {
|
||||
return $this->keywords->map(function ($keyword) {
|
||||
return [
|
||||
'id' => $keyword->id,
|
||||
'keyword' => $keyword->keyword,
|
||||
'is_active' => $keyword->is_active,
|
||||
];
|
||||
});
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -20,17 +20,17 @@ public function __construct(
|
|||
$this->onQueue('feed-discovery');
|
||||
}
|
||||
|
||||
public function handle(LogSaver $logSaver, ArticleFetcher $articleFetcher): void
|
||||
public function handle(): void
|
||||
{
|
||||
$logSaver->info('Starting feed article fetch', null, [
|
||||
LogSaver::info('Starting feed article fetch', null, [
|
||||
'feed_id' => $this->feed->id,
|
||||
'feed_name' => $this->feed->name,
|
||||
'feed_url' => $this->feed->url
|
||||
]);
|
||||
|
||||
$articles = $articleFetcher->getArticlesFromFeed($this->feed);
|
||||
$articles = ArticleFetcher::getArticlesFromFeed($this->feed);
|
||||
|
||||
$logSaver->info('Feed article fetch completed', null, [
|
||||
LogSaver::info('Feed article fetch completed', null, [
|
||||
'feed_id' => $this->feed->id,
|
||||
'feed_name' => $this->feed->name,
|
||||
'articles_count' => $articles->count()
|
||||
|
|
@ -41,11 +41,9 @@ public function handle(LogSaver $logSaver, ArticleFetcher $articleFetcher): void
|
|||
|
||||
public static function dispatchForAllActiveFeeds(): void
|
||||
{
|
||||
$logSaver = app(LogSaver::class);
|
||||
|
||||
Feed::where('is_active', true)
|
||||
->get()
|
||||
->each(function (Feed $feed, $index) use ($logSaver) {
|
||||
->each(function (Feed $feed, $index) {
|
||||
// Space jobs apart to avoid overwhelming feeds
|
||||
$delayMinutes = $index * self::FEED_DISCOVERY_DELAY_MINUTES;
|
||||
|
||||
|
|
@ -53,7 +51,7 @@ public static function dispatchForAllActiveFeeds(): void
|
|||
->delay(now()->addMinutes($delayMinutes))
|
||||
->onQueue('feed-discovery');
|
||||
|
||||
$logSaver->info('Dispatched feed discovery job', null, [
|
||||
LogSaver::info('Dispatched feed discovery job', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_name' => $feed->name,
|
||||
'delay_minutes' => $delayMinutes
|
||||
|
|
|
|||
|
|
@ -16,18 +16,18 @@ public function __construct()
|
|||
$this->onQueue('feed-discovery');
|
||||
}
|
||||
|
||||
public function handle(LogSaver $logSaver): void
|
||||
public function handle(): void
|
||||
{
|
||||
if (!Setting::isArticleProcessingEnabled()) {
|
||||
$logSaver->info('Article processing is disabled. Article discovery skipped.');
|
||||
LogSaver::info('Article processing is disabled. Article discovery skipped.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$logSaver->info('Starting article discovery for all active feeds');
|
||||
LogSaver::info('Starting article discovery for all active feeds');
|
||||
|
||||
ArticleDiscoveryForFeedJob::dispatchForAllActiveFeeds();
|
||||
|
||||
$logSaver->info('Article discovery jobs dispatched for all active feeds');
|
||||
LogSaver::info('Article discovery jobs dispatched for all active feeds');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,69 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Exceptions\PublishException;
|
||||
use App\Models\Article;
|
||||
use App\Services\Article\ArticleFetcher;
|
||||
use App\Services\Publishing\ArticlePublishingService;
|
||||
use Illuminate\Contracts\Queue\ShouldBeUnique;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
class PublishNextArticleJob implements ShouldQueue, ShouldBeUnique
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
/**
|
||||
* The number of seconds after which the job's unique lock will be released.
|
||||
*/
|
||||
public int $uniqueFor = 300;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->onQueue('publishing');
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
* @throws PublishException
|
||||
*/
|
||||
public function handle(ArticleFetcher $articleFetcher, ArticlePublishingService $publishingService): void
|
||||
{
|
||||
// Get the oldest approved article that hasn't been published yet
|
||||
$article = Article::where('approval_status', 'approved')
|
||||
->whereDoesntHave('articlePublication')
|
||||
->oldest('created_at')
|
||||
->first();
|
||||
|
||||
if (! $article) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger()->info('Publishing next article from scheduled job', [
|
||||
'article_id' => $article->id,
|
||||
'title' => $article->title,
|
||||
'url' => $article->url,
|
||||
'created_at' => $article->created_at
|
||||
]);
|
||||
|
||||
// Fetch article data
|
||||
$extractedData = $articleFetcher->fetchArticleData($article);
|
||||
|
||||
try {
|
||||
$publishingService->publishToRoutedChannels($article, $extractedData);
|
||||
|
||||
logger()->info('Successfully published article', [
|
||||
'article_id' => $article->id,
|
||||
'title' => $article->title
|
||||
]);
|
||||
} catch (PublishException $e) {
|
||||
logger()->error('Failed to publish article', [
|
||||
'article_id' => $article->id,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
35
app/Jobs/PublishToLemmyJob.php
Normal file
35
app/Jobs/PublishToLemmyJob.php
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Exceptions\PublishException;
|
||||
use App\Models\Article;
|
||||
use App\Services\Article\ArticleFetcher;
|
||||
use App\Services\Publishing\ArticlePublishingService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
class PublishToLemmyJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public function __construct(
|
||||
private readonly Article $article
|
||||
) {
|
||||
$this->onQueue('lemmy-posts');
|
||||
}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$extractedData = ArticleFetcher::fetchArticleData($this->article);
|
||||
|
||||
/** @var ArticlePublishingService $publishingService */
|
||||
$publishingService = resolve(ArticlePublishingService::class);
|
||||
|
||||
try {
|
||||
$publishingService->publishToRoutedChannels($this->article, $extractedData);
|
||||
} catch (PublishException $e) {
|
||||
$this->fail($e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -22,39 +22,37 @@ class SyncChannelPostsJob implements ShouldQueue, ShouldBeUnique
|
|||
public function __construct(
|
||||
private readonly PlatformChannel $channel
|
||||
) {
|
||||
$this->onQueue('sync');
|
||||
$this->onQueue('lemmy-posts');
|
||||
}
|
||||
|
||||
public static function dispatchForAllActiveChannels(): void
|
||||
{
|
||||
$logSaver = app(LogSaver::class);
|
||||
|
||||
PlatformChannel::with(['platformInstance', 'platformAccounts'])
|
||||
->whereHas('platformInstance', fn ($query) => $query->where('platform', PlatformEnum::LEMMY))
|
||||
->whereHas('platformAccounts', fn ($query) => $query->where('platform_accounts.is_active', true))
|
||||
->where('platform_channels.is_active', true)
|
||||
->whereHas('platformAccounts', fn ($query) => $query->where('is_active', true))
|
||||
->where('is_active', true)
|
||||
->get()
|
||||
->each(function (PlatformChannel $channel) use ($logSaver) {
|
||||
->each(function (PlatformChannel $channel) {
|
||||
self::dispatch($channel);
|
||||
$logSaver->info('Dispatched sync job for channel', $channel);
|
||||
LogSaver::info('Dispatched sync job for channel', $channel);
|
||||
});
|
||||
}
|
||||
|
||||
public function handle(LogSaver $logSaver): void
|
||||
public function handle(): void
|
||||
{
|
||||
$logSaver->info('Starting channel posts sync job', $this->channel);
|
||||
LogSaver::info('Starting channel posts sync job', $this->channel);
|
||||
|
||||
match ($this->channel->platformInstance->platform) {
|
||||
PlatformEnum::LEMMY => $this->syncLemmyChannelPosts($logSaver),
|
||||
PlatformEnum::LEMMY => $this->syncLemmyChannelPosts(),
|
||||
};
|
||||
|
||||
$logSaver->info('Channel posts sync job completed', $this->channel);
|
||||
LogSaver::info('Channel posts sync job completed', $this->channel);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws PlatformAuthException
|
||||
*/
|
||||
private function syncLemmyChannelPosts(LogSaver $logSaver): void
|
||||
private function syncLemmyChannelPosts(): void
|
||||
{
|
||||
try {
|
||||
/** @var Collection<int, PlatformAccount> $accounts */
|
||||
|
|
@ -74,10 +72,10 @@ private function syncLemmyChannelPosts(LogSaver $logSaver): void
|
|||
|
||||
$api->syncChannelPosts($token, $platformChannelId, $this->channel->name);
|
||||
|
||||
$logSaver->info('Channel posts synced successfully', $this->channel);
|
||||
LogSaver::info('Channel posts synced successfully', $this->channel);
|
||||
|
||||
} catch (Exception $e) {
|
||||
$logSaver->error('Failed to sync channel posts', $this->channel, [
|
||||
LogSaver::error('Failed to sync channel posts', $this->channel, [
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
|
||||
|
|
|
|||
|
|
@ -10,29 +10,18 @@ class LogExceptionToDatabase
|
|||
|
||||
public function handle(ExceptionOccurred $event): void
|
||||
{
|
||||
// Truncate the message to prevent database errors
|
||||
$message = strlen($event->message) > 255
|
||||
? substr($event->message, 0, 252) . '...'
|
||||
: $event->message;
|
||||
$log = Log::create([
|
||||
'level' => $event->level,
|
||||
'message' => $event->message,
|
||||
'context' => [
|
||||
'exception_class' => get_class($event->exception),
|
||||
'file' => $event->exception->getFile(),
|
||||
'line' => $event->exception->getLine(),
|
||||
'trace' => $event->exception->getTraceAsString(),
|
||||
...$event->context
|
||||
]
|
||||
]);
|
||||
|
||||
try {
|
||||
$log = Log::create([
|
||||
'level' => $event->level,
|
||||
'message' => $message,
|
||||
'context' => [
|
||||
'exception_class' => get_class($event->exception),
|
||||
'file' => $event->exception->getFile(),
|
||||
'line' => $event->exception->getLine(),
|
||||
'trace' => $event->exception->getTraceAsString(),
|
||||
...$event->context
|
||||
]
|
||||
]);
|
||||
|
||||
ExceptionLogged::dispatch($log);
|
||||
} catch (\Exception $e) {
|
||||
// Prevent infinite recursion by not logging this exception
|
||||
// Optionally log to file or other non-database destination
|
||||
error_log("Failed to log exception to database: " . $e->getMessage());
|
||||
}
|
||||
ExceptionLogged::dispatch($log);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
27
app/Listeners/PublishApprovedArticle.php
Normal file
27
app/Listeners/PublishApprovedArticle.php
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
<?php
|
||||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Events\ArticleApproved;
|
||||
use App\Events\ArticleReadyToPublish;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
|
||||
class PublishApprovedArticle implements ShouldQueue
|
||||
{
|
||||
public string $queue = 'default';
|
||||
|
||||
public function handle(ArticleApproved $event): void
|
||||
{
|
||||
$article = $event->article;
|
||||
|
||||
// Skip if already has publication (prevents duplicate processing)
|
||||
if ($article->articlePublication()->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only publish if the article is valid and approved
|
||||
if ($article->isValid() && $article->isApproved()) {
|
||||
event(new ArticleReadyToPublish($article));
|
||||
}
|
||||
}
|
||||
}
|
||||
39
app/Listeners/PublishArticle.php
Normal file
39
app/Listeners/PublishArticle.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Events\ArticleReadyToPublish;
|
||||
use App\Jobs\PublishToLemmyJob;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
|
||||
class PublishArticle implements ShouldQueue
|
||||
{
|
||||
public string|null $queue = 'lemmy-publish';
|
||||
public int $delay = 300;
|
||||
public int $tries = 3;
|
||||
public int $backoff = 300;
|
||||
|
||||
public function __construct()
|
||||
{}
|
||||
|
||||
public function handle(ArticleReadyToPublish $event): void
|
||||
{
|
||||
$article = $event->article;
|
||||
|
||||
if ($article->articlePublication()->exists()) {
|
||||
logger()->info('Article already published, skipping job dispatch', [
|
||||
'article_id' => $article->id,
|
||||
'url' => $article->url
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
logger()->info('Article queued for publishing to Lemmy', [
|
||||
'article_id' => $article->id,
|
||||
'url' => $article->url
|
||||
]);
|
||||
|
||||
PublishToLemmyJob::dispatch($article);
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@
|
|||
namespace App\Listeners;
|
||||
|
||||
use App\Events\NewArticleFetched;
|
||||
use App\Events\ArticleApproved;
|
||||
use App\Events\ArticleReadyToPublish;
|
||||
use App\Models\Setting;
|
||||
use App\Services\Article\ValidationService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
|
|
@ -12,7 +12,7 @@ class ValidateArticleListener implements ShouldQueue
|
|||
{
|
||||
public string $queue = 'default';
|
||||
|
||||
public function handle(NewArticleFetched $event, ValidationService $validationService): void
|
||||
public function handle(NewArticleFetched $event): void
|
||||
{
|
||||
$article = $event->article;
|
||||
|
||||
|
|
@ -25,7 +25,7 @@ public function handle(NewArticleFetched $event, ValidationService $validationSe
|
|||
return;
|
||||
}
|
||||
|
||||
$article = $validationService->validate($article);
|
||||
$article = ValidationService::validate($article);
|
||||
|
||||
if ($article->isValid()) {
|
||||
// Double-check publication doesn't exist (race condition protection)
|
||||
|
|
@ -37,12 +37,12 @@ public function handle(NewArticleFetched $event, ValidationService $validationSe
|
|||
if (Setting::isPublishingApprovalsEnabled()) {
|
||||
// If approvals are enabled, only proceed if article is approved
|
||||
if ($article->isApproved()) {
|
||||
event(new ArticleApproved($article));
|
||||
event(new ArticleReadyToPublish($article));
|
||||
}
|
||||
// If not approved, article will wait for manual approval
|
||||
} else {
|
||||
// If approvals are disabled, proceed with publishing
|
||||
event(new ArticleApproved($article));
|
||||
event(new ArticleReadyToPublish($article));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,61 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Setting;
|
||||
use App\Jobs\ArticleDiscoveryJob;
|
||||
use Livewire\Component;
|
||||
use Livewire\WithPagination;
|
||||
|
||||
class Articles extends Component
|
||||
{
|
||||
use WithPagination;
|
||||
|
||||
public bool $isRefreshing = false;
|
||||
|
||||
public function approve(int $articleId): void
|
||||
{
|
||||
$article = Article::findOrFail($articleId);
|
||||
$article->approve();
|
||||
|
||||
$this->dispatch('article-updated');
|
||||
}
|
||||
|
||||
public function reject(int $articleId): void
|
||||
{
|
||||
$article = Article::findOrFail($articleId);
|
||||
$article->reject();
|
||||
|
||||
$this->dispatch('article-updated');
|
||||
}
|
||||
|
||||
public function refresh(): void
|
||||
{
|
||||
$this->isRefreshing = true;
|
||||
|
||||
ArticleDiscoveryJob::dispatch();
|
||||
|
||||
// Reset after 10 seconds
|
||||
$this->dispatch('refresh-complete')->self();
|
||||
}
|
||||
|
||||
public function refreshComplete(): void
|
||||
{
|
||||
$this->isRefreshing = false;
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
$articles = Article::with(['feed', 'articlePublication'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(15);
|
||||
|
||||
$approvalsEnabled = Setting::isPublishingApprovalsEnabled();
|
||||
|
||||
return view('livewire.articles', [
|
||||
'articles' => $articles,
|
||||
'approvalsEnabled' => $approvalsEnabled,
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use Livewire\Component;
|
||||
|
||||
class Channels extends Component
|
||||
{
|
||||
public ?int $managingChannelId = null;
|
||||
|
||||
public function toggle(int $channelId): void
|
||||
{
|
||||
$channel = PlatformChannel::findOrFail($channelId);
|
||||
$channel->is_active = !$channel->is_active;
|
||||
$channel->save();
|
||||
}
|
||||
|
||||
public function openAccountModal(int $channelId): void
|
||||
{
|
||||
$this->managingChannelId = $channelId;
|
||||
}
|
||||
|
||||
public function closeAccountModal(): void
|
||||
{
|
||||
$this->managingChannelId = null;
|
||||
}
|
||||
|
||||
public function attachAccount(int $accountId): void
|
||||
{
|
||||
if (!$this->managingChannelId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$channel = PlatformChannel::findOrFail($this->managingChannelId);
|
||||
|
||||
if (!$channel->platformAccounts()->where('platform_account_id', $accountId)->exists()) {
|
||||
$channel->platformAccounts()->attach($accountId, [
|
||||
'is_active' => true,
|
||||
'priority' => 1,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function detachAccount(int $channelId, int $accountId): void
|
||||
{
|
||||
$channel = PlatformChannel::findOrFail($channelId);
|
||||
$channel->platformAccounts()->detach($accountId);
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
$channels = PlatformChannel::with(['platformInstance', 'platformAccounts'])->orderBy('name')->get();
|
||||
$allAccounts = PlatformAccount::where('is_active', true)->get();
|
||||
|
||||
$managingChannel = $this->managingChannelId
|
||||
? PlatformChannel::with('platformAccounts')->find($this->managingChannelId)
|
||||
: null;
|
||||
|
||||
$availableAccounts = $managingChannel
|
||||
? $allAccounts->filter(fn($account) => !$managingChannel->platformAccounts->contains('id', $account->id))
|
||||
: collect();
|
||||
|
||||
return view('livewire.channels', [
|
||||
'channels' => $channels,
|
||||
'managingChannel' => $managingChannel,
|
||||
'availableAccounts' => $availableAccounts,
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Services\DashboardStatsService;
|
||||
use Livewire\Component;
|
||||
|
||||
class Dashboard extends Component
|
||||
{
|
||||
public string $period = 'today';
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
// Default period
|
||||
}
|
||||
|
||||
public function setPeriod(string $period): void
|
||||
{
|
||||
$this->period = $period;
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
$service = app(DashboardStatsService::class);
|
||||
|
||||
$articleStats = $service->getStats($this->period);
|
||||
$systemStats = $service->getSystemStats();
|
||||
$availablePeriods = $service->getAvailablePeriods();
|
||||
|
||||
return view('livewire.dashboard', [
|
||||
'articleStats' => $articleStats,
|
||||
'systemStats' => $systemStats,
|
||||
'availablePeriods' => $availablePeriods,
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Models\Feed;
|
||||
use Livewire\Component;
|
||||
|
||||
class Feeds extends Component
|
||||
{
|
||||
public function toggle(int $feedId): void
|
||||
{
|
||||
$feed = Feed::findOrFail($feedId);
|
||||
$feed->is_active = !$feed->is_active;
|
||||
$feed->save();
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
$feeds = Feed::orderBy('name')->get();
|
||||
|
||||
return view('livewire.feeds', [
|
||||
'feeds' => $feeds,
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,358 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Jobs\ArticleDiscoveryJob;
|
||||
use App\Models\Feed;
|
||||
use App\Models\Language;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Models\Route;
|
||||
use App\Models\Setting;
|
||||
use App\Services\Auth\LemmyAuthService;
|
||||
use App\Services\OnboardingService;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Livewire\Component;
|
||||
|
||||
class Onboarding extends Component
|
||||
{
|
||||
// Step tracking (1-6: welcome, platform, feed, channel, route, complete)
|
||||
public int $step = 1;
|
||||
|
||||
// Platform form
|
||||
public string $instanceUrl = '';
|
||||
public string $username = '';
|
||||
public string $password = '';
|
||||
public ?array $existingAccount = null;
|
||||
|
||||
// Feed form
|
||||
public string $feedName = '';
|
||||
public string $feedProvider = 'vrt';
|
||||
public ?int $feedLanguageId = null;
|
||||
public string $feedDescription = '';
|
||||
|
||||
// Channel form
|
||||
public string $channelName = '';
|
||||
public ?int $platformInstanceId = null;
|
||||
public ?int $channelLanguageId = null;
|
||||
public string $channelDescription = '';
|
||||
|
||||
// Route form
|
||||
public ?int $routeFeedId = null;
|
||||
public ?int $routeChannelId = null;
|
||||
public int $routePriority = 50;
|
||||
|
||||
// State
|
||||
public array $formErrors = [];
|
||||
public bool $isLoading = false;
|
||||
|
||||
protected LemmyAuthService $lemmyAuthService;
|
||||
|
||||
public function boot(LemmyAuthService $lemmyAuthService): void
|
||||
{
|
||||
$this->lemmyAuthService = $lemmyAuthService;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
// Check for existing platform account
|
||||
$account = PlatformAccount::where('is_active', true)->first();
|
||||
if ($account) {
|
||||
$this->existingAccount = [
|
||||
'id' => $account->id,
|
||||
'username' => $account->username,
|
||||
'instance_url' => $account->instance_url,
|
||||
];
|
||||
}
|
||||
|
||||
// Pre-fill feed form if exists
|
||||
$feed = Feed::where('is_active', true)->first();
|
||||
if ($feed) {
|
||||
$this->feedName = $feed->name;
|
||||
$this->feedProvider = $feed->provider ?? 'vrt';
|
||||
$this->feedLanguageId = $feed->language_id;
|
||||
$this->feedDescription = $feed->description ?? '';
|
||||
}
|
||||
|
||||
// Pre-fill channel form if exists
|
||||
$channel = PlatformChannel::where('is_active', true)->first();
|
||||
if ($channel) {
|
||||
$this->channelName = $channel->name;
|
||||
$this->platformInstanceId = $channel->platform_instance_id;
|
||||
$this->channelLanguageId = $channel->language_id;
|
||||
$this->channelDescription = $channel->description ?? '';
|
||||
}
|
||||
|
||||
// Pre-fill route form if exists
|
||||
$route = Route::where('is_active', true)->first();
|
||||
if ($route) {
|
||||
$this->routeFeedId = $route->feed_id;
|
||||
$this->routeChannelId = $route->platform_channel_id;
|
||||
$this->routePriority = $route->priority;
|
||||
}
|
||||
}
|
||||
|
||||
public function goToStep(int $step): void
|
||||
{
|
||||
$this->step = $step;
|
||||
$this->formErrors = [];
|
||||
}
|
||||
|
||||
public function nextStep(): void
|
||||
{
|
||||
$this->step++;
|
||||
$this->formErrors = [];
|
||||
}
|
||||
|
||||
public function previousStep(): void
|
||||
{
|
||||
if ($this->step > 1) {
|
||||
$this->step--;
|
||||
$this->formErrors = [];
|
||||
}
|
||||
}
|
||||
|
||||
public function continueWithExistingAccount(): void
|
||||
{
|
||||
$this->nextStep();
|
||||
}
|
||||
|
||||
public function deleteAccount(): void
|
||||
{
|
||||
if ($this->existingAccount) {
|
||||
PlatformAccount::destroy($this->existingAccount['id']);
|
||||
$this->existingAccount = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function createPlatformAccount(): void
|
||||
{
|
||||
$this->formErrors = [];
|
||||
$this->isLoading = true;
|
||||
|
||||
$this->validate([
|
||||
'instanceUrl' => 'required|string|max:255|regex:/^[a-zA-Z0-9]([a-zA-Z0-9\-\.]*[a-zA-Z0-9])?$/',
|
||||
'username' => 'required|string|max:255',
|
||||
'password' => 'required|string|min:6',
|
||||
], [
|
||||
'instanceUrl.regex' => 'Please enter a valid domain name (e.g., lemmy.world, belgae.social)',
|
||||
]);
|
||||
|
||||
$fullInstanceUrl = 'https://' . $this->instanceUrl;
|
||||
|
||||
try {
|
||||
// Create or get platform instance
|
||||
$platformInstance = PlatformInstance::firstOrCreate([
|
||||
'url' => $fullInstanceUrl,
|
||||
'platform' => 'lemmy',
|
||||
], [
|
||||
'name' => ucfirst($this->instanceUrl),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Authenticate with Lemmy API
|
||||
$authResponse = $this->lemmyAuthService->authenticate(
|
||||
$fullInstanceUrl,
|
||||
$this->username,
|
||||
$this->password
|
||||
);
|
||||
|
||||
// Create platform account
|
||||
$platformAccount = PlatformAccount::create([
|
||||
'platform' => 'lemmy',
|
||||
'instance_url' => $fullInstanceUrl,
|
||||
'username' => $this->username,
|
||||
'password' => Crypt::encryptString($this->password),
|
||||
'settings' => [
|
||||
'display_name' => $authResponse['person_view']['person']['display_name'] ?? null,
|
||||
'description' => $authResponse['person_view']['person']['bio'] ?? null,
|
||||
'person_id' => $authResponse['person_view']['person']['id'] ?? null,
|
||||
'platform_instance_id' => $platformInstance->id,
|
||||
'api_token' => $authResponse['jwt'] ?? null,
|
||||
],
|
||||
'is_active' => true,
|
||||
'status' => 'active',
|
||||
]);
|
||||
|
||||
$this->existingAccount = [
|
||||
'id' => $platformAccount->id,
|
||||
'username' => $platformAccount->username,
|
||||
'instance_url' => $platformAccount->instance_url,
|
||||
];
|
||||
|
||||
$this->nextStep();
|
||||
} catch (\App\Exceptions\PlatformAuthException $e) {
|
||||
$message = $e->getMessage();
|
||||
if (str_contains($message, 'Rate limited by')) {
|
||||
$this->formErrors['general'] = $message;
|
||||
} elseif (str_contains($message, 'Connection failed')) {
|
||||
$this->formErrors['general'] = 'Unable to connect to the Lemmy instance. Please check the URL and try again.';
|
||||
} else {
|
||||
$this->formErrors['general'] = 'Invalid username or password. Please check your credentials and try again.';
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
logger()->error('Lemmy platform account creation failed', [
|
||||
'instance_url' => $fullInstanceUrl,
|
||||
'username' => $this->username,
|
||||
'error' => $e->getMessage(),
|
||||
'class' => get_class($e),
|
||||
]);
|
||||
$this->formErrors['general'] = 'An error occurred while setting up your account. Please try again.';
|
||||
} finally {
|
||||
$this->isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
public function createFeed(): void
|
||||
{
|
||||
$this->formErrors = [];
|
||||
$this->isLoading = true;
|
||||
|
||||
$this->validate([
|
||||
'feedName' => 'required|string|max:255',
|
||||
'feedProvider' => 'required|in:belga,vrt',
|
||||
'feedLanguageId' => 'required|exists:languages,id',
|
||||
'feedDescription' => 'nullable|string|max:1000',
|
||||
]);
|
||||
|
||||
try {
|
||||
// Map provider to URL
|
||||
$url = $this->feedProvider === 'vrt'
|
||||
? 'https://www.vrt.be/vrtnws/en/'
|
||||
: 'https://www.belganewsagency.eu/';
|
||||
|
||||
Feed::firstOrCreate(
|
||||
['url' => $url],
|
||||
[
|
||||
'name' => $this->feedName,
|
||||
'type' => 'website',
|
||||
'provider' => $this->feedProvider,
|
||||
'language_id' => $this->feedLanguageId,
|
||||
'description' => $this->feedDescription ?: null,
|
||||
'is_active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$this->nextStep();
|
||||
} catch (\Exception $e) {
|
||||
$this->formErrors['general'] = 'Failed to create feed. Please try again.';
|
||||
} finally {
|
||||
$this->isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
public function createChannel(): void
|
||||
{
|
||||
$this->formErrors = [];
|
||||
$this->isLoading = true;
|
||||
|
||||
$this->validate([
|
||||
'channelName' => 'required|string|max:255',
|
||||
'platformInstanceId' => 'required|exists:platform_instances,id',
|
||||
'channelLanguageId' => 'required|exists:languages,id',
|
||||
'channelDescription' => 'nullable|string|max:1000',
|
||||
]);
|
||||
|
||||
try {
|
||||
$platformInstance = PlatformInstance::findOrFail($this->platformInstanceId);
|
||||
|
||||
// Check for active platform accounts
|
||||
$activeAccounts = PlatformAccount::where('instance_url', $platformInstance->url)
|
||||
->where('is_active', true)
|
||||
->get();
|
||||
|
||||
if ($activeAccounts->isEmpty()) {
|
||||
$this->formErrors['general'] = 'No active platform accounts found for this instance. Please create a platform account first.';
|
||||
$this->isLoading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
$channel = PlatformChannel::create([
|
||||
'platform_instance_id' => $this->platformInstanceId,
|
||||
'channel_id' => $this->channelName,
|
||||
'name' => $this->channelName,
|
||||
'display_name' => ucfirst($this->channelName),
|
||||
'description' => $this->channelDescription ?: null,
|
||||
'language_id' => $this->channelLanguageId,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Attach first active account
|
||||
$channel->platformAccounts()->attach($activeAccounts->first()->id, [
|
||||
'is_active' => true,
|
||||
'priority' => 1,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$this->nextStep();
|
||||
} catch (\Exception $e) {
|
||||
$this->formErrors['general'] = 'Failed to create channel. Please try again.';
|
||||
} finally {
|
||||
$this->isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
public function createRoute(): void
|
||||
{
|
||||
$this->formErrors = [];
|
||||
$this->isLoading = true;
|
||||
|
||||
$this->validate([
|
||||
'routeFeedId' => 'required|exists:feeds,id',
|
||||
'routeChannelId' => 'required|exists:platform_channels,id',
|
||||
'routePriority' => 'nullable|integer|min:1|max:100',
|
||||
]);
|
||||
|
||||
try {
|
||||
Route::create([
|
||||
'feed_id' => $this->routeFeedId,
|
||||
'platform_channel_id' => $this->routeChannelId,
|
||||
'priority' => $this->routePriority,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Trigger article discovery
|
||||
ArticleDiscoveryJob::dispatch();
|
||||
|
||||
$this->nextStep();
|
||||
} catch (\Exception $e) {
|
||||
$this->formErrors['general'] = 'Failed to create route. Please try again.';
|
||||
} finally {
|
||||
$this->isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
public function completeOnboarding(): void
|
||||
{
|
||||
Setting::updateOrCreate(
|
||||
['key' => 'onboarding_completed'],
|
||||
['value' => now()->toIso8601String()]
|
||||
);
|
||||
|
||||
app(OnboardingService::class)->clearCache();
|
||||
|
||||
$this->redirect(route('dashboard'));
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
$languages = Language::where('is_active', true)->orderBy('name')->get();
|
||||
$platformInstances = PlatformInstance::where('is_active', true)->orderBy('name')->get();
|
||||
$feeds = Feed::where('is_active', true)->orderBy('name')->get();
|
||||
$channels = PlatformChannel::where('is_active', true)->orderBy('name')->get();
|
||||
|
||||
$feedProviders = collect(config('feed.providers', []))
|
||||
->filter(fn($provider) => $provider['is_active'] ?? false)
|
||||
->values();
|
||||
|
||||
return view('livewire.onboarding', [
|
||||
'languages' => $languages,
|
||||
'platformInstances' => $platformInstances,
|
||||
'feeds' => $feeds,
|
||||
'channels' => $channels,
|
||||
'feedProviders' => $feedProviders,
|
||||
])->layout('layouts.onboarding');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,200 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Models\Feed;
|
||||
use App\Models\Keyword;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\Route;
|
||||
use Livewire\Component;
|
||||
|
||||
class Routes extends Component
|
||||
{
|
||||
public bool $showCreateModal = false;
|
||||
public ?int $editingFeedId = null;
|
||||
public ?int $editingChannelId = null;
|
||||
|
||||
// Create form
|
||||
public ?int $newFeedId = null;
|
||||
public ?int $newChannelId = null;
|
||||
public int $newPriority = 50;
|
||||
|
||||
// Edit form
|
||||
public int $editPriority = 50;
|
||||
|
||||
// Keyword management
|
||||
public string $newKeyword = '';
|
||||
public bool $showKeywordInput = false;
|
||||
|
||||
public function openCreateModal(): void
|
||||
{
|
||||
$this->showCreateModal = true;
|
||||
$this->newFeedId = null;
|
||||
$this->newChannelId = null;
|
||||
$this->newPriority = 50;
|
||||
}
|
||||
|
||||
public function closeCreateModal(): void
|
||||
{
|
||||
$this->showCreateModal = false;
|
||||
}
|
||||
|
||||
public function createRoute(): void
|
||||
{
|
||||
$this->validate([
|
||||
'newFeedId' => 'required|exists:feeds,id',
|
||||
'newChannelId' => 'required|exists:platform_channels,id',
|
||||
'newPriority' => 'required|integer|min:0',
|
||||
]);
|
||||
|
||||
$exists = Route::where('feed_id', $this->newFeedId)
|
||||
->where('platform_channel_id', $this->newChannelId)
|
||||
->exists();
|
||||
|
||||
if ($exists) {
|
||||
$this->addError('newFeedId', 'This route already exists.');
|
||||
return;
|
||||
}
|
||||
|
||||
Route::create([
|
||||
'feed_id' => $this->newFeedId,
|
||||
'platform_channel_id' => $this->newChannelId,
|
||||
'priority' => $this->newPriority,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$this->closeCreateModal();
|
||||
}
|
||||
|
||||
public function openEditModal(int $feedId, int $channelId): void
|
||||
{
|
||||
$route = Route::where('feed_id', $feedId)
|
||||
->where('platform_channel_id', $channelId)
|
||||
->firstOrFail();
|
||||
|
||||
$this->editingFeedId = $feedId;
|
||||
$this->editingChannelId = $channelId;
|
||||
$this->editPriority = $route->priority;
|
||||
$this->newKeyword = '';
|
||||
$this->showKeywordInput = false;
|
||||
}
|
||||
|
||||
public function closeEditModal(): void
|
||||
{
|
||||
$this->editingFeedId = null;
|
||||
$this->editingChannelId = null;
|
||||
}
|
||||
|
||||
public function updateRoute(): void
|
||||
{
|
||||
if (!$this->editingFeedId || !$this->editingChannelId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->validate([
|
||||
'editPriority' => 'required|integer|min:0',
|
||||
]);
|
||||
|
||||
Route::where('feed_id', $this->editingFeedId)
|
||||
->where('platform_channel_id', $this->editingChannelId)
|
||||
->update(['priority' => $this->editPriority]);
|
||||
|
||||
$this->closeEditModal();
|
||||
}
|
||||
|
||||
public function toggle(int $feedId, int $channelId): void
|
||||
{
|
||||
$route = Route::where('feed_id', $feedId)
|
||||
->where('platform_channel_id', $channelId)
|
||||
->firstOrFail();
|
||||
|
||||
$route->is_active = !$route->is_active;
|
||||
$route->save();
|
||||
}
|
||||
|
||||
public function delete(int $feedId, int $channelId): void
|
||||
{
|
||||
// Delete associated keywords first
|
||||
Keyword::where('feed_id', $feedId)
|
||||
->where('platform_channel_id', $channelId)
|
||||
->delete();
|
||||
|
||||
Route::where('feed_id', $feedId)
|
||||
->where('platform_channel_id', $channelId)
|
||||
->delete();
|
||||
}
|
||||
|
||||
public function addKeyword(): void
|
||||
{
|
||||
if (!$this->editingFeedId || !$this->editingChannelId || empty(trim($this->newKeyword))) {
|
||||
return;
|
||||
}
|
||||
|
||||
Keyword::create([
|
||||
'feed_id' => $this->editingFeedId,
|
||||
'platform_channel_id' => $this->editingChannelId,
|
||||
'keyword' => trim($this->newKeyword),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$this->newKeyword = '';
|
||||
$this->showKeywordInput = false;
|
||||
}
|
||||
|
||||
public function toggleKeyword(int $keywordId): void
|
||||
{
|
||||
$keyword = Keyword::findOrFail($keywordId);
|
||||
$keyword->is_active = !$keyword->is_active;
|
||||
$keyword->save();
|
||||
}
|
||||
|
||||
public function deleteKeyword(int $keywordId): void
|
||||
{
|
||||
Keyword::destroy($keywordId);
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
$routes = Route::with(['feed', 'platformChannel'])
|
||||
->orderBy('priority', 'desc')
|
||||
->get();
|
||||
|
||||
// Batch load keywords for all routes to avoid N+1 queries
|
||||
$routeKeys = $routes->map(fn($r) => $r->feed_id . '-' . $r->platform_channel_id);
|
||||
$allKeywords = Keyword::whereIn('feed_id', $routes->pluck('feed_id'))
|
||||
->whereIn('platform_channel_id', $routes->pluck('platform_channel_id'))
|
||||
->get()
|
||||
->groupBy(fn($k) => $k->feed_id . '-' . $k->platform_channel_id);
|
||||
|
||||
$routes = $routes->map(function ($route) use ($allKeywords) {
|
||||
$key = $route->feed_id . '-' . $route->platform_channel_id;
|
||||
$route->keywords = $allKeywords->get($key, collect());
|
||||
return $route;
|
||||
});
|
||||
|
||||
$feeds = Feed::where('is_active', true)->orderBy('name')->get();
|
||||
$channels = PlatformChannel::where('is_active', true)->orderBy('name')->get();
|
||||
|
||||
$editingRoute = null;
|
||||
$editingKeywords = collect();
|
||||
|
||||
if ($this->editingFeedId && $this->editingChannelId) {
|
||||
$editingRoute = Route::with(['feed', 'platformChannel'])
|
||||
->where('feed_id', $this->editingFeedId)
|
||||
->where('platform_channel_id', $this->editingChannelId)
|
||||
->first();
|
||||
|
||||
$editingKeywords = Keyword::where('feed_id', $this->editingFeedId)
|
||||
->where('platform_channel_id', $this->editingChannelId)
|
||||
->get();
|
||||
}
|
||||
|
||||
return view('livewire.routes', [
|
||||
'routes' => $routes,
|
||||
'feeds' => $feeds,
|
||||
'channels' => $channels,
|
||||
'editingRoute' => $editingRoute,
|
||||
'editingKeywords' => $editingKeywords,
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Models\Setting;
|
||||
use Livewire\Component;
|
||||
|
||||
class Settings extends Component
|
||||
{
|
||||
public bool $articleProcessingEnabled = true;
|
||||
public bool $publishingApprovalsEnabled = false;
|
||||
|
||||
public ?string $successMessage = null;
|
||||
public ?string $errorMessage = null;
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->articleProcessingEnabled = Setting::isArticleProcessingEnabled();
|
||||
$this->publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();
|
||||
}
|
||||
|
||||
public function toggleArticleProcessing(): void
|
||||
{
|
||||
$this->articleProcessingEnabled = !$this->articleProcessingEnabled;
|
||||
Setting::setArticleProcessingEnabled($this->articleProcessingEnabled);
|
||||
$this->showSuccess();
|
||||
}
|
||||
|
||||
public function togglePublishingApprovals(): void
|
||||
{
|
||||
$this->publishingApprovalsEnabled = !$this->publishingApprovalsEnabled;
|
||||
Setting::setPublishingApprovalsEnabled($this->publishingApprovalsEnabled);
|
||||
$this->showSuccess();
|
||||
}
|
||||
|
||||
protected function showSuccess(): void
|
||||
{
|
||||
$this->successMessage = 'Settings updated successfully!';
|
||||
$this->errorMessage = null;
|
||||
|
||||
// Clear success message after 3 seconds
|
||||
$this->dispatch('clear-message');
|
||||
}
|
||||
|
||||
public function clearMessages(): void
|
||||
{
|
||||
$this->successMessage = null;
|
||||
$this->errorMessage = null;
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.settings')->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
namespace App;
|
||||
|
||||
enum LogLevelEnum: string
|
||||
{
|
||||
|
|
@ -35,11 +35,13 @@ class Article extends Model
|
|||
'url',
|
||||
'title',
|
||||
'description',
|
||||
'content',
|
||||
'image_url',
|
||||
'published_at',
|
||||
'author',
|
||||
'is_valid',
|
||||
'is_duplicate',
|
||||
'approval_status',
|
||||
'approved_at',
|
||||
'approved_by',
|
||||
'fetched_at',
|
||||
'validated_at',
|
||||
];
|
||||
|
||||
/**
|
||||
|
|
@ -48,8 +50,12 @@ class Article extends Model
|
|||
public function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_valid' => 'boolean',
|
||||
'is_duplicate' => 'boolean',
|
||||
'approval_status' => 'string',
|
||||
'published_at' => 'datetime',
|
||||
'approved_at' => 'datetime',
|
||||
'fetched_at' => 'datetime',
|
||||
'validated_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
|
@ -57,9 +63,15 @@ public function casts(): array
|
|||
|
||||
public function isValid(): bool
|
||||
{
|
||||
// In the consolidated schema, we only have approval_status
|
||||
// Consider 'approved' status as valid
|
||||
return $this->approval_status === 'approved';
|
||||
if (is_null($this->validated_at)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (is_null($this->is_valid)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->is_valid;
|
||||
}
|
||||
|
||||
public function isApproved(): bool
|
||||
|
|
@ -81,6 +93,8 @@ public function approve(string $approvedBy = null): void
|
|||
{
|
||||
$this->update([
|
||||
'approval_status' => 'approved',
|
||||
'approved_at' => now(),
|
||||
'approved_by' => $approvedBy,
|
||||
]);
|
||||
|
||||
// Fire event to trigger publishing
|
||||
|
|
@ -91,6 +105,8 @@ public function reject(string $rejectedBy = null): void
|
|||
{
|
||||
$this->update([
|
||||
'approval_status' => 'rejected',
|
||||
'approved_at' => now(),
|
||||
'approved_by' => $rejectedBy,
|
||||
]);
|
||||
}
|
||||
|
||||
|
|
@ -109,11 +125,6 @@ public function canBePublished(): bool
|
|||
return $this->isApproved();
|
||||
}
|
||||
|
||||
public function getIsPublishedAttribute(): bool
|
||||
{
|
||||
return $this->articlePublication()->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasOne<ArticlePublication, $this>
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -2,8 +2,6 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use Database\Factories\ArticlePublicationFactory;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
|
|
@ -16,9 +14,6 @@
|
|||
*/
|
||||
class ArticlePublication extends Model
|
||||
{
|
||||
/** @use HasFactory<ArticlePublicationFactory> */
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'article_id',
|
||||
'platform_channel_id',
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@
|
|||
* @property string $name
|
||||
* @property string $url
|
||||
* @property string $type
|
||||
* @property string $provider
|
||||
* @property int $language_id
|
||||
* @property Language|null $language
|
||||
* @property string $description
|
||||
|
|
@ -39,7 +38,6 @@ class Feed extends Model
|
|||
'name',
|
||||
'url',
|
||||
'type',
|
||||
'provider',
|
||||
'language_id',
|
||||
'description',
|
||||
'settings',
|
||||
|
|
@ -89,7 +87,8 @@ public function getStatusAttribute(): string
|
|||
public function channels(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(PlatformChannel::class, 'routes')
|
||||
->withPivot(['is_active', 'priority'])
|
||||
->using(Route::class)
|
||||
->withPivot(['is_active', 'priority', 'filters'])
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
|
@ -20,8 +19,6 @@
|
|||
*/
|
||||
class Keyword extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'feed_id',
|
||||
'platform_channel_id',
|
||||
|
|
|
|||
|
|
@ -2,13 +2,12 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\LogLevelEnum;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use App\LogLevelEnum;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* @method static create(array $array)
|
||||
* @method static create(array<string, mixed> $array)
|
||||
* @property LogLevelEnum $level
|
||||
* @property string $message
|
||||
* @property array<string, mixed> $context
|
||||
|
|
@ -17,8 +16,6 @@
|
|||
*/
|
||||
class Log extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'logs';
|
||||
|
||||
protected $fillable = [
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ class PlatformAccount extends Model
|
|||
'instance_url',
|
||||
'username',
|
||||
'password',
|
||||
'api_token',
|
||||
'settings',
|
||||
'is_active',
|
||||
'last_tested_at',
|
||||
|
|
@ -59,40 +60,22 @@ class PlatformAccount extends Model
|
|||
protected function password(): Attribute
|
||||
{
|
||||
return Attribute::make(
|
||||
get: function ($value, array $attributes) {
|
||||
// Return null if the raw value is null
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Return empty string if value is empty
|
||||
if (empty($value)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
return Crypt::decryptString($value);
|
||||
} catch (\Exception $e) {
|
||||
// If decryption fails, return null to be safe
|
||||
return null;
|
||||
}
|
||||
},
|
||||
set: function ($value) {
|
||||
// Store null if null is passed
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Store empty string as null
|
||||
if (empty($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Crypt::encryptString($value);
|
||||
},
|
||||
)->withoutObjectCaching();
|
||||
get: fn ($value) => $value ? Crypt::decryptString($value) : null,
|
||||
set: fn ($value) => $value ? Crypt::encryptString($value) : null,
|
||||
);
|
||||
}
|
||||
|
||||
// Encrypt API token when storing
|
||||
/**
|
||||
* @return Attribute<string|null, string|null>
|
||||
*/
|
||||
protected function apiToken(): Attribute
|
||||
{
|
||||
return Attribute::make(
|
||||
get: fn ($value) => $value ? Crypt::decryptString($value) : null,
|
||||
set: fn ($value) => $value ? Crypt::encryptString($value) : null,
|
||||
);
|
||||
}
|
||||
|
||||
// Get the active accounts for a platform (returns collection)
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@
|
|||
|
||||
/**
|
||||
* @method static findMany(mixed $channel_ids)
|
||||
* @method static create(array $array)
|
||||
* @property integer $id
|
||||
* @property integer $platform_instance_id
|
||||
* @property PlatformInstance $platformInstance
|
||||
|
|
@ -64,7 +63,7 @@ public function platformAccounts(): BelongsToMany
|
|||
*/
|
||||
public function activePlatformAccounts(): BelongsToMany
|
||||
{
|
||||
return $this->platformAccounts()->wherePivot('is_active', true);
|
||||
return $this->platformAccounts()->where('is_active', true);
|
||||
}
|
||||
|
||||
public function getFullNameAttribute(): string
|
||||
|
|
@ -79,7 +78,8 @@ public function getFullNameAttribute(): string
|
|||
public function feeds(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Feed::class, 'routes')
|
||||
->withPivot(['is_active', 'priority'])
|
||||
->using(Route::class)
|
||||
->withPivot(['is_active', 'priority', 'filters'])
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@
|
|||
namespace App\Models;
|
||||
|
||||
use App\Enums\PlatformEnum;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
|
|
@ -12,7 +11,6 @@
|
|||
*/
|
||||
class PlatformChannelPost extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
protected $fillable = [
|
||||
'platform',
|
||||
'channel_id',
|
||||
|
|
|
|||
|
|
@ -2,11 +2,9 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use Database\Factories\RouteFactory;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\Pivot;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
|
|
@ -14,29 +12,27 @@
|
|||
* @property int $platform_channel_id
|
||||
* @property bool $is_active
|
||||
* @property int $priority
|
||||
* @property array<string, mixed> $filters
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
*/
|
||||
class Route extends Model
|
||||
class Route extends Pivot
|
||||
{
|
||||
/** @use HasFactory<RouteFactory> */
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'routes';
|
||||
|
||||
// Laravel doesn't handle composite primary keys well, so we'll use regular queries
|
||||
protected $primaryKey = null;
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $fillable = [
|
||||
'feed_id',
|
||||
'platform_channel_id',
|
||||
'is_active',
|
||||
'priority'
|
||||
'priority',
|
||||
'filters'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean'
|
||||
'is_active' => 'boolean',
|
||||
'filters' => 'array'
|
||||
];
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -2,24 +2,16 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* @method static updateOrCreate(string[] $array, array $array1)
|
||||
* @method static create(string[] $array)
|
||||
* @method static where(string $string, string $key)
|
||||
*/
|
||||
class Setting extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = ['key', 'value'];
|
||||
|
||||
public static function get(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$setting = static::where('key', $key)->first();
|
||||
|
||||
|
||||
return $setting ? $setting->value : $default;
|
||||
}
|
||||
|
||||
|
|
@ -31,7 +23,7 @@ public static function set(string $key, mixed $value): void
|
|||
public static function getBool(string $key, bool $default = false): bool
|
||||
{
|
||||
$value = static::get($key, $default);
|
||||
|
||||
|
||||
return filter_var($value, FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,12 +6,11 @@
|
|||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
/** @use HasFactory<\Database\Factories\UserFactory> */
|
||||
use HasFactory, Notifiable, HasApiTokens;
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
|
|
|
|||
|
|
@ -9,58 +9,26 @@ class LemmyRequest
|
|||
{
|
||||
private string $instance;
|
||||
private ?string $token;
|
||||
private string $scheme = 'https';
|
||||
|
||||
public function __construct(string $instance, ?string $token = null)
|
||||
{
|
||||
// Detect scheme if provided in the instance string
|
||||
if (preg_match('/^(https?):\/\//i', $instance, $m)) {
|
||||
$this->scheme = strtolower($m[1]);
|
||||
}
|
||||
// Handle both full URLs and just domain names
|
||||
$this->instance = $this->normalizeInstance($instance);
|
||||
$this->instance = $instance;
|
||||
$this->token = $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize instance URL to just the domain name
|
||||
*/
|
||||
private function normalizeInstance(string $instance): string
|
||||
{
|
||||
// Remove protocol if present
|
||||
$instance = preg_replace('/^https?:\/\//i', '', $instance);
|
||||
|
||||
// Remove trailing slash if present
|
||||
$instance = rtrim($instance, '/');
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicitly set the scheme (http or https) for subsequent requests.
|
||||
*/
|
||||
public function withScheme(string $scheme): self
|
||||
{
|
||||
$scheme = strtolower($scheme);
|
||||
if (in_array($scheme, ['http', 'https'], true)) {
|
||||
$this->scheme = $scheme;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
public function get(string $endpoint, array $params = []): Response
|
||||
{
|
||||
$url = sprintf('%s://%s/api/v3/%s', $this->scheme, $this->instance, $endpoint);
|
||||
|
||||
$url = "https://{$this->instance}/api/v3/{$endpoint}";
|
||||
|
||||
$request = Http::timeout(30);
|
||||
|
||||
|
||||
if ($this->token) {
|
||||
$request = $request->withToken($this->token);
|
||||
}
|
||||
|
||||
|
||||
return $request->get($url, $params);
|
||||
}
|
||||
|
||||
|
|
@ -69,14 +37,14 @@ public function get(string $endpoint, array $params = []): Response
|
|||
*/
|
||||
public function post(string $endpoint, array $data = []): Response
|
||||
{
|
||||
$url = sprintf('%s://%s/api/v3/%s', $this->scheme, $this->instance, $endpoint);
|
||||
|
||||
$url = "https://{$this->instance}/api/v3/{$endpoint}";
|
||||
|
||||
$request = Http::timeout(30);
|
||||
|
||||
|
||||
if ($this->token) {
|
||||
$request = $request->withToken($this->token);
|
||||
}
|
||||
|
||||
|
||||
return $request->post($url, $data);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -18,66 +18,27 @@ public function __construct(string $instance)
|
|||
|
||||
public function login(string $username, string $password): ?string
|
||||
{
|
||||
// Try HTTPS first; on failure, optionally retry with HTTP to support dev instances
|
||||
$schemesToTry = [];
|
||||
if (preg_match('/^https?:\/\//i', $this->instance)) {
|
||||
// Preserve user-provided scheme as first try
|
||||
$schemesToTry[] = strtolower(str_starts_with($this->instance, 'http://') ? 'http' : 'https');
|
||||
} else {
|
||||
// Default order: https then http
|
||||
$schemesToTry = ['https', 'http'];
|
||||
}
|
||||
try {
|
||||
$request = new LemmyRequest($this->instance);
|
||||
$response = $request->post('user/login', [
|
||||
'username_or_email' => $username,
|
||||
'password' => $password,
|
||||
]);
|
||||
|
||||
foreach ($schemesToTry as $idx => $scheme) {
|
||||
try {
|
||||
$request = new LemmyRequest($this->instance);
|
||||
// ensure scheme used matches current attempt
|
||||
$request = $request->withScheme($scheme);
|
||||
|
||||
$response = $request->post('user/login', [
|
||||
'username_or_email' => $username,
|
||||
'password' => $password,
|
||||
if (!$response->successful()) {
|
||||
logger()->error('Lemmy login failed', [
|
||||
'status' => $response->status(),
|
||||
'body' => $response->body()
|
||||
]);
|
||||
|
||||
if (!$response->successful()) {
|
||||
$responseBody = $response->body();
|
||||
logger()->error('Lemmy login failed', [
|
||||
'status' => $response->status(),
|
||||
'body' => $responseBody,
|
||||
'scheme' => $scheme,
|
||||
]);
|
||||
|
||||
// Check if it's a rate limit error
|
||||
if (str_contains($responseBody, 'rate_limit_error')) {
|
||||
throw new Exception('Rate limited by Lemmy instance. Please wait a moment and try again.');
|
||||
}
|
||||
|
||||
// If first attempt failed and there is another scheme to try, continue loop
|
||||
if ($idx === 0 && count($schemesToTry) > 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
return $data['jwt'] ?? null;
|
||||
} catch (Exception $e) {
|
||||
// Re-throw rate limit exceptions immediately
|
||||
if (str_contains($e->getMessage(), 'Rate limited')) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
logger()->error('Lemmy login exception', ['error' => $e->getMessage(), 'scheme' => $scheme]);
|
||||
// If this was the first attempt and HTTPS, try HTTP next
|
||||
if ($idx === 0 && in_array('http', $schemesToTry, true)) {
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
$data = $response->json();
|
||||
return $data['jwt'] ?? null;
|
||||
} catch (Exception $e) {
|
||||
logger()->error('Lemmy login exception', ['error' => $e->getMessage()]);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function getCommunityId(string $communityName, string $token): int
|
||||
|
|
|
|||
|
|
@ -28,21 +28,16 @@ public function __construct(PlatformAccount $account)
|
|||
*/
|
||||
public function publishToChannel(Article $article, array $extractedData, PlatformChannel $channel): array
|
||||
{
|
||||
$token = resolve(LemmyAuthService::class)->getToken($this->account);
|
||||
$token = LemmyAuthService::getToken($this->account);
|
||||
|
||||
// Use the language ID from extracted data (should be set during validation)
|
||||
$languageId = $extractedData['language_id'] ?? null;
|
||||
|
||||
// Resolve community name to numeric ID if needed
|
||||
$communityId = is_numeric($channel->channel_id)
|
||||
? (int) $channel->channel_id
|
||||
: $this->api->getCommunityId($channel->channel_id, $token);
|
||||
|
||||
return $this->api->createPost(
|
||||
$token,
|
||||
$extractedData['title'] ?? 'Untitled',
|
||||
$extractedData['description'] ?? '',
|
||||
$communityId,
|
||||
$channel->channel_id,
|
||||
$article->url,
|
||||
$extractedData['thumbnail'] ?? null,
|
||||
$languageId
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@
|
|||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\Events\ExceptionOccurred;
|
||||
use App\Listeners\LogExceptionToDatabase;
|
||||
use App\LogLevelEnum;
|
||||
use Error;
|
||||
use Illuminate\Contracts\Debug\ExceptionHandler;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
|
|
@ -25,12 +25,6 @@ public function boot(): void
|
|||
LogExceptionToDatabase::class,
|
||||
);
|
||||
|
||||
Event::listen(
|
||||
\App\Events\NewArticleFetched::class,
|
||||
\App\Listeners\ValidateArticleListener::class,
|
||||
);
|
||||
|
||||
|
||||
app()->make(ExceptionHandler::class)
|
||||
->reportable(function (Throwable $e) {
|
||||
$level = $this->mapExceptionToLogLevel($e);
|
||||
|
|
|
|||
|
|
@ -13,22 +13,18 @@
|
|||
|
||||
class ArticleFetcher
|
||||
{
|
||||
public function __construct(
|
||||
private LogSaver $logSaver
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
public function getArticlesFromFeed(Feed $feed): Collection
|
||||
public static function getArticlesFromFeed(Feed $feed): Collection
|
||||
{
|
||||
if ($feed->type === 'rss') {
|
||||
return $this->getArticlesFromRssFeed($feed);
|
||||
return self::getArticlesFromRssFeed($feed);
|
||||
} elseif ($feed->type === 'website') {
|
||||
return $this->getArticlesFromWebsiteFeed($feed);
|
||||
return self::getArticlesFromWebsiteFeed($feed);
|
||||
}
|
||||
|
||||
$this->logSaver->warning("Unsupported feed type", null, [
|
||||
LogSaver::warning("Unsupported feed type", null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_type' => $feed->type
|
||||
]);
|
||||
|
|
@ -39,7 +35,7 @@ public function getArticlesFromFeed(Feed $feed): Collection
|
|||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
private function getArticlesFromRssFeed(Feed $feed): Collection
|
||||
private static function getArticlesFromRssFeed(Feed $feed): Collection
|
||||
{
|
||||
// TODO: Implement RSS feed parsing
|
||||
// For now, return empty collection
|
||||
|
|
@ -49,14 +45,14 @@ private function getArticlesFromRssFeed(Feed $feed): Collection
|
|||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
private function getArticlesFromWebsiteFeed(Feed $feed): Collection
|
||||
private static function getArticlesFromWebsiteFeed(Feed $feed): Collection
|
||||
{
|
||||
try {
|
||||
// Try to get parser for this feed
|
||||
$parser = HomepageParserFactory::getParserForFeed($feed);
|
||||
|
||||
if (! $parser) {
|
||||
$this->logSaver->warning("No parser available for feed URL", null, [
|
||||
LogSaver::warning("No parser available for feed URL", null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url
|
||||
]);
|
||||
|
|
@ -68,10 +64,10 @@ private function getArticlesFromWebsiteFeed(Feed $feed): Collection
|
|||
$urls = $parser->extractArticleUrls($html);
|
||||
|
||||
return collect($urls)
|
||||
->map(fn (string $url) => $this->saveArticle($url, $feed->id));
|
||||
->map(fn (string $url) => self::saveArticle($url, $feed->id));
|
||||
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error("Failed to fetch articles from website feed", null, [
|
||||
LogSaver::error("Failed to fetch articles from website feed", null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
'error' => $e->getMessage()
|
||||
|
|
@ -84,7 +80,7 @@ private function getArticlesFromWebsiteFeed(Feed $feed): Collection
|
|||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function fetchArticleData(Article $article): array
|
||||
public static function fetchArticleData(Article $article): array
|
||||
{
|
||||
try {
|
||||
$html = HttpFetcher::fetchHtml($article->url);
|
||||
|
|
@ -92,7 +88,7 @@ public function fetchArticleData(Article $article): array
|
|||
|
||||
return $parser->extractData($html);
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Exception while fetching article data', null, [
|
||||
LogSaver::error('Exception while fetching article data', null, [
|
||||
'url' => $article->url,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
|
|
@ -101,7 +97,7 @@ public function fetchArticleData(Article $article): array
|
|||
}
|
||||
}
|
||||
|
||||
private function saveArticle(string $url, ?int $feedId = null): Article
|
||||
private static function saveArticle(string $url, ?int $feedId = null): Article
|
||||
{
|
||||
$existingArticle = Article::where('url', $url)->first();
|
||||
|
||||
|
|
@ -109,37 +105,9 @@ private function saveArticle(string $url, ?int $feedId = null): Article
|
|||
return $existingArticle;
|
||||
}
|
||||
|
||||
// Extract a basic title from URL as fallback
|
||||
$fallbackTitle = $this->generateFallbackTitle($url);
|
||||
|
||||
try {
|
||||
return Article::create([
|
||||
'url' => $url,
|
||||
'feed_id' => $feedId,
|
||||
'title' => $fallbackTitle,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
$this->logSaver->error("Failed to create article - title validation failed", null, [
|
||||
'url' => $url,
|
||||
'feed_id' => $feedId,
|
||||
'error' => $e->getMessage(),
|
||||
'suggestion' => 'Check regex parsing patterns for title extraction'
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
private function generateFallbackTitle(string $url): string
|
||||
{
|
||||
// Extract filename from URL as a basic fallback title
|
||||
$path = parse_url($url, PHP_URL_PATH);
|
||||
$filename = basename($path ?: $url);
|
||||
|
||||
// Remove file extension and convert to readable format
|
||||
$title = preg_replace('/\.[^.]*$/', '', $filename);
|
||||
$title = str_replace(['-', '_'], ' ', $title);
|
||||
$title = ucwords($title);
|
||||
|
||||
return $title ?: 'Untitled Article';
|
||||
return Article::create([
|
||||
'url' => $url,
|
||||
'feed_id' => $feedId
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,62 +6,40 @@
|
|||
|
||||
class ValidationService
|
||||
{
|
||||
public function __construct(
|
||||
private ArticleFetcher $articleFetcher
|
||||
) {}
|
||||
|
||||
public function validate(Article $article): Article
|
||||
public static function validate(Article $article): Article
|
||||
{
|
||||
logger('Checking keywords for article: ' . $article->id);
|
||||
|
||||
$articleData = $this->articleFetcher->fetchArticleData($article);
|
||||
$articleData = ArticleFetcher::fetchArticleData($article);
|
||||
|
||||
// Update article with fetched metadata (title, description)
|
||||
$updateData = [];
|
||||
|
||||
if (!empty($articleData)) {
|
||||
$updateData['title'] = $articleData['title'] ?? $article->title;
|
||||
$updateData['description'] = $articleData['description'] ?? $article->description;
|
||||
$updateData['content'] = $articleData['full_article'] ?? null;
|
||||
}
|
||||
|
||||
if (!isset($articleData['full_article']) || empty($articleData['full_article'])) {
|
||||
logger()->warning('Article data missing full_article content', [
|
||||
if (!isset($articleData['full_article'])) {
|
||||
logger()->warning('Article data missing full_article key', [
|
||||
'article_id' => $article->id,
|
||||
'url' => $article->url
|
||||
]);
|
||||
|
||||
$updateData['approval_status'] = 'rejected';
|
||||
$article->update($updateData);
|
||||
$article->update([
|
||||
'is_valid' => false,
|
||||
'validated_at' => now(),
|
||||
]);
|
||||
|
||||
return $article->refresh();
|
||||
}
|
||||
|
||||
// Validate using extracted content (not stored)
|
||||
$validationResult = $this->validateByKeywords($articleData['full_article']);
|
||||
$updateData['approval_status'] = $validationResult ? 'approved' : 'pending';
|
||||
$validationResult = self::validateByKeywords($articleData['full_article']);
|
||||
|
||||
$article->update($updateData);
|
||||
$article->update([
|
||||
'is_valid' => $validationResult,
|
||||
'validated_at' => now(),
|
||||
]);
|
||||
|
||||
return $article->refresh();
|
||||
}
|
||||
|
||||
private function validateByKeywords(string $full_article): bool
|
||||
private static function validateByKeywords(string $full_article): bool
|
||||
{
|
||||
// Belgian news content keywords - broader set for Belgian news relevance
|
||||
$keywords = [
|
||||
// Political parties and leaders
|
||||
'N-VA', 'Bart De Wever', 'Frank Vandenbroucke', 'Alexander De Croo',
|
||||
'Vooruit', 'Open Vld', 'CD&V', 'Vlaams Belang', 'PTB', 'PVDA',
|
||||
|
||||
// Belgian locations and institutions
|
||||
'Belgium', 'Belgian', 'Flanders', 'Flemish', 'Wallonia', 'Brussels',
|
||||
'Antwerp', 'Ghent', 'Bruges', 'Leuven', 'Mechelen', 'Namur', 'Liège', 'Charleroi',
|
||||
'parliament', 'government', 'minister', 'policy', 'law', 'legislation',
|
||||
|
||||
// Common Belgian news topics
|
||||
'economy', 'economic', 'education', 'healthcare', 'transport', 'climate', 'energy',
|
||||
'European', 'EU', 'migration', 'security', 'justice', 'culture', 'police'
|
||||
'N-VA', 'Bart De Wever', 'Frank Vandenbroucke',
|
||||
];
|
||||
|
||||
foreach ($keywords as $keyword) {
|
||||
|
|
|
|||
|
|
@ -6,15 +6,22 @@
|
|||
use App\Exceptions\PlatformAuthException;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Modules\Lemmy\Services\LemmyApiService;
|
||||
use Exception;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class LemmyAuthService
|
||||
{
|
||||
/**
|
||||
* @throws PlatformAuthException
|
||||
*/
|
||||
public function getToken(PlatformAccount $account): string
|
||||
public static function getToken(PlatformAccount $account): string
|
||||
{
|
||||
$cacheKey = "lemmy_jwt_token_$account->id";
|
||||
$cachedToken = Cache::get($cacheKey);
|
||||
|
||||
if ($cachedToken) {
|
||||
return $cachedToken;
|
||||
}
|
||||
|
||||
if (! $account->username || ! $account->password || ! $account->instance_url) {
|
||||
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Missing credentials for account: ' . $account->username);
|
||||
}
|
||||
|
|
@ -26,47 +33,9 @@ public function getToken(PlatformAccount $account): string
|
|||
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Login failed for account: ' . $account->username);
|
||||
}
|
||||
|
||||
// Cache for 50 minutes (3000 seconds) to allow buffer before token expires
|
||||
Cache::put($cacheKey, $token, 3000);
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate with Lemmy API and return user data with JWT
|
||||
* @throws PlatformAuthException
|
||||
*/
|
||||
public function authenticate(string $instanceUrl, string $username, string $password): array
|
||||
{
|
||||
try {
|
||||
$api = new LemmyApiService($instanceUrl);
|
||||
$token = $api->login($username, $password);
|
||||
|
||||
if (!$token) {
|
||||
// Throw a clean exception that will be caught and handled by the controller
|
||||
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Invalid credentials');
|
||||
}
|
||||
|
||||
// Get user info with the token
|
||||
// For now, we'll return a basic response structure
|
||||
// In a real implementation, you might want to fetch user details
|
||||
return [
|
||||
'jwt' => $token,
|
||||
'person_view' => [
|
||||
'person' => [
|
||||
'id' => 0, // Would need API call to get actual user info
|
||||
'display_name' => null,
|
||||
'bio' => null,
|
||||
]
|
||||
]
|
||||
];
|
||||
} catch (PlatformAuthException $e) {
|
||||
// Re-throw PlatformAuthExceptions as-is to avoid nesting
|
||||
throw $e;
|
||||
} catch (Exception $e) {
|
||||
// Check if it's a rate limit error
|
||||
if (str_contains($e->getMessage(), 'Rate limited by')) {
|
||||
throw new PlatformAuthException(PlatformEnum::LEMMY, $e->getMessage());
|
||||
}
|
||||
// For other exceptions, throw a clean PlatformAuthException
|
||||
throw new PlatformAuthException(PlatformEnum::LEMMY, 'Connection failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,36 +4,28 @@
|
|||
|
||||
use App\Models\Article;
|
||||
use App\Models\ArticlePublication;
|
||||
use App\Models\Feed;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\Route;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class DashboardStatsService
|
||||
{
|
||||
/**
|
||||
* @return array{articles_fetched: int, articles_published: int, published_percentage: float}
|
||||
*/
|
||||
public function getStats(string $period = 'today'): array
|
||||
{
|
||||
$dateRange = $this->getDateRange($period);
|
||||
|
||||
$articlesFetched = Article::when($dateRange, function ($query) use ($dateRange) {
|
||||
return $query->whereBetween('created_at', $dateRange);
|
||||
})->count();
|
||||
|
||||
// Get articles fetched for the period
|
||||
$articlesFetchedQuery = Article::query();
|
||||
if ($dateRange) {
|
||||
$articlesFetchedQuery->whereBetween('created_at', $dateRange);
|
||||
}
|
||||
$articlesFetched = $articlesFetchedQuery->count();
|
||||
$articlesPublished = ArticlePublication::when($dateRange, function ($query) use ($dateRange) {
|
||||
return $query->whereBetween('published_at', $dateRange);
|
||||
})->count();
|
||||
|
||||
// Get articles published for the period
|
||||
$articlesPublishedQuery = ArticlePublication::query()
|
||||
->whereNotNull('published_at');
|
||||
if ($dateRange) {
|
||||
$articlesPublishedQuery->whereBetween('published_at', $dateRange);
|
||||
}
|
||||
$articlesPublished = $articlesPublishedQuery->count();
|
||||
|
||||
// Calculate published percentage
|
||||
$publishedPercentage = $articlesFetched > 0 ? round(($articlesPublished / $articlesFetched) * 100, 1) : 0.0;
|
||||
$publishedPercentage = $articlesFetched > 0
|
||||
? round(($articlesPublished / $articlesFetched) * 100, 1)
|
||||
: 0.0;
|
||||
|
||||
return [
|
||||
'articles_fetched' => $articlesFetched,
|
||||
|
|
@ -62,7 +54,7 @@ public function getAvailablePeriods(): array
|
|||
private function getDateRange(string $period): ?array
|
||||
{
|
||||
$now = Carbon::now();
|
||||
|
||||
|
||||
return match ($period) {
|
||||
'today' => [$now->copy()->startOfDay(), $now->copy()->endOfDay()],
|
||||
'week' => [$now->copy()->startOfWeek(), $now->copy()->endOfWeek()],
|
||||
|
|
@ -73,26 +65,19 @@ private function getDateRange(string $period): ?array
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get additional stats for dashboard
|
||||
* @return array{total_feeds: int, active_feeds: int, total_channels: int, active_channels: int, total_routes: int, active_routes: int}
|
||||
*/
|
||||
public function getSystemStats(): array
|
||||
{
|
||||
$totalFeeds = Feed::query()->count();
|
||||
$activeFeeds = Feed::query()->where('is_active', 1)->count();
|
||||
$totalPlatformAccounts = PlatformAccount::query()->count();
|
||||
$activePlatformAccounts = PlatformAccount::query()->where('is_active', 1)->count();
|
||||
$totalPlatformChannels = PlatformChannel::query()->count();
|
||||
$activePlatformChannels = PlatformChannel::query()->where('is_active', 1)->count();
|
||||
$totalRoutes = Route::query()->count();
|
||||
$activeRoutes = Route::query()->where('is_active', 1)->count();
|
||||
|
||||
return [
|
||||
'total_feeds' => $totalFeeds,
|
||||
'active_feeds' => $activeFeeds,
|
||||
'total_platform_accounts' => $totalPlatformAccounts,
|
||||
'active_platform_accounts' => $activePlatformAccounts,
|
||||
'total_platform_channels' => $totalPlatformChannels,
|
||||
'active_platform_channels' => $activePlatformChannels,
|
||||
'total_routes' => $totalRoutes,
|
||||
'active_routes' => $activeRoutes,
|
||||
'total_feeds' => \App\Models\Feed::count(),
|
||||
'active_feeds' => \App\Models\Feed::where('is_active', true)->count(),
|
||||
'total_channels' => \App\Models\PlatformChannel::count(),
|
||||
'active_channels' => \App\Models\PlatformChannel::where('is_active', true)->count(),
|
||||
'total_routes' => \App\Models\Route::count(),
|
||||
'active_routes' => \App\Models\Route::where('is_active', true)->count(),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,6 @@
|
|||
namespace App\Services\Factories;
|
||||
|
||||
use App\Contracts\ArticleParserInterface;
|
||||
use App\Models\Feed;
|
||||
use App\Services\Parsers\VrtArticleParser;
|
||||
use App\Services\Parsers\BelgaArticleParser;
|
||||
use Exception;
|
||||
|
|
@ -18,14 +17,11 @@ class ArticleParserFactory
|
|||
BelgaArticleParser::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function getParser(string $url): ArticleParserInterface
|
||||
{
|
||||
foreach (self::$parsers as $parserClass) {
|
||||
$parser = new $parserClass();
|
||||
|
||||
|
||||
if ($parser->canParse($url)) {
|
||||
return $parser;
|
||||
}
|
||||
|
|
@ -34,25 +30,6 @@ public static function getParser(string $url): ArticleParserInterface
|
|||
throw new Exception("No parser found for URL: {$url}");
|
||||
}
|
||||
|
||||
public static function getParserForFeed(Feed $feed, string $parserType = 'article'): ?ArticleParserInterface
|
||||
{
|
||||
if (!$feed->provider) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$providerConfig = config("feed.providers.{$feed->provider}");
|
||||
if (!$providerConfig || !isset($providerConfig['parsers'][$parserType])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parserClass = $providerConfig['parsers'][$parserType];
|
||||
if (!class_exists($parserClass)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new $parserClass();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
|
|
@ -73,4 +50,4 @@ public static function registerParser(string $parserClass): void
|
|||
self::$parsers[] = $parserClass;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -36,20 +36,10 @@ public static function getParser(string $url): HomepageParserInterface
|
|||
|
||||
public static function getParserForFeed(Feed $feed): ?HomepageParserInterface
|
||||
{
|
||||
if (!$feed->provider) {
|
||||
try {
|
||||
return self::getParser($feed->url);
|
||||
} catch (Exception) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$providerConfig = config("feed.providers.{$feed->provider}");
|
||||
if (!$providerConfig || !isset($providerConfig['parsers']['homepage'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parserClass = $providerConfig['parsers']['homepage'];
|
||||
if (!class_exists($parserClass)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new $parserClass();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,25 +7,21 @@
|
|||
|
||||
class HttpFetcher
|
||||
{
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function fetchHtml(string $url): string
|
||||
{
|
||||
try {
|
||||
$response = Http::get($url);
|
||||
|
||||
|
||||
if (!$response->successful()) {
|
||||
throw new Exception("Failed to fetch URL: {$url} - Status: {$response->status()}");
|
||||
}
|
||||
|
||||
|
||||
return $response->body();
|
||||
} catch (Exception $e) {
|
||||
logger()->error('HTTP fetch failed', [
|
||||
'url' => $url,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
|
@ -44,11 +40,13 @@ public static function fetchMultipleUrls(array $urls): array
|
|||
});
|
||||
|
||||
return collect($responses)
|
||||
->filter(fn($response, $index) => isset($urls[$index]))
|
||||
->reject(fn($response, $index) => $response instanceof Exception)
|
||||
->map(function ($response, $index) use ($urls) {
|
||||
if (!isset($urls[$index])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$url = $urls[$index];
|
||||
|
||||
|
||||
try {
|
||||
if ($response->successful()) {
|
||||
return [
|
||||
|
|
@ -77,8 +75,7 @@ public static function fetchMultipleUrls(array $urls): array
|
|||
->toArray();
|
||||
} catch (Exception $e) {
|
||||
logger()->error('Multiple URL fetch failed', ['error' => $e->getMessage()]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
namespace App\Services\Log;
|
||||
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\LogLevelEnum;
|
||||
use App\Models\Log;
|
||||
use App\Models\PlatformChannel;
|
||||
|
||||
|
|
@ -11,39 +11,39 @@ class LogSaver
|
|||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
public function info(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
public static function info(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
{
|
||||
$this->log(LogLevelEnum::INFO, $message, $channel, $context);
|
||||
self::log(LogLevelEnum::INFO, $message, $channel, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
public function error(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
public static function error(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
{
|
||||
$this->log(LogLevelEnum::ERROR, $message, $channel, $context);
|
||||
self::log(LogLevelEnum::ERROR, $message, $channel, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
public function warning(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
public static function warning(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
{
|
||||
$this->log(LogLevelEnum::WARNING, $message, $channel, $context);
|
||||
self::log(LogLevelEnum::WARNING, $message, $channel, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
public function debug(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
public static function debug(string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
{
|
||||
$this->log(LogLevelEnum::DEBUG, $message, $channel, $context);
|
||||
self::log(LogLevelEnum::DEBUG, $message, $channel, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function log(LogLevelEnum $level, string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
private static function log(LogLevelEnum $level, string $message, ?PlatformChannel $channel = null, array $context = []): void
|
||||
{
|
||||
$logContext = $context;
|
||||
|
||||
|
|
@ -62,4 +62,4 @@ private function log(LogLevelEnum $level, string $message, ?PlatformChannel $cha
|
|||
'context' => $logContext,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
20
app/Services/OnboardingRedirectService.php
Normal file
20
app/Services/OnboardingRedirectService.php
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OnboardingRedirectService
|
||||
{
|
||||
public static function handleRedirect(Request $request, string $defaultRoute, string $successMessage): RedirectResponse
|
||||
{
|
||||
$redirectTo = $request->input('redirect_to');
|
||||
|
||||
if ($redirectTo) {
|
||||
return redirect($redirectTo)->with('success', $successMessage);
|
||||
}
|
||||
|
||||
return redirect()->route($defaultRoute)->with('success', $successMessage);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Feed;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\Route;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class OnboardingService
|
||||
{
|
||||
public function needsOnboarding(): bool
|
||||
{
|
||||
return Cache::remember('onboarding_needed', 300, function () {
|
||||
return $this->checkOnboardingStatus();
|
||||
});
|
||||
}
|
||||
|
||||
public function clearCache(): void
|
||||
{
|
||||
Cache::forget('onboarding_needed');
|
||||
}
|
||||
|
||||
private function checkOnboardingStatus(): bool
|
||||
{
|
||||
$onboardingSkipped = Setting::where('key', 'onboarding_skipped')->value('value') === 'true';
|
||||
$onboardingCompleted = Setting::where('key', 'onboarding_completed')->exists();
|
||||
|
||||
// If skipped or completed, no onboarding needed
|
||||
if ($onboardingCompleted || $onboardingSkipped) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if all components exist
|
||||
$hasPlatformAccount = PlatformAccount::where('is_active', true)->exists();
|
||||
$hasFeed = Feed::where('is_active', true)->exists();
|
||||
$hasChannel = PlatformChannel::where('is_active', true)->exists();
|
||||
$hasRoute = Route::where('is_active', true)->exists();
|
||||
|
||||
$hasAllComponents = $hasPlatformAccount && $hasFeed && $hasChannel && $hasRoute;
|
||||
|
||||
return !$hasAllComponents;
|
||||
}
|
||||
}
|
||||
|
|
@ -55,41 +55,15 @@ public static function extractFullArticle(string $html): ?string
|
|||
$cleanHtml = preg_replace('/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/mi', '', $html);
|
||||
$cleanHtml = preg_replace('/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/mi', '', $cleanHtml);
|
||||
|
||||
// Look for Belga-specific paragraph class
|
||||
if (preg_match_all('/<p[^>]*class="[^"]*styles_paragraph__[^"]*"[^>]*>(.*?)<\/p>/is', $cleanHtml, $matches)) {
|
||||
$paragraphs = array_map(function($paragraph) {
|
||||
return html_entity_decode(strip_tags($paragraph), ENT_QUOTES, 'UTF-8');
|
||||
}, $matches[1]);
|
||||
|
||||
// Filter out empty paragraphs and join with double newlines
|
||||
$fullText = implode("\n\n", array_filter($paragraphs, function($p) {
|
||||
return trim($p) !== '';
|
||||
}));
|
||||
|
||||
return $fullText ?: null;
|
||||
}
|
||||
|
||||
// Fallback: Try to extract from prezly-slate-document section
|
||||
// Try to extract content from Belga-specific document section
|
||||
if (preg_match('/<section[^>]*class="[^"]*prezly-slate-document[^"]*"[^>]*>(.*?)<\/section>/is', $cleanHtml, $sectionMatches)) {
|
||||
$sectionHtml = $sectionMatches[1];
|
||||
preg_match_all('/<p[^>]*>(.*?)<\/p>/is', $sectionHtml, $matches);
|
||||
|
||||
if (!empty($matches[1])) {
|
||||
$paragraphs = array_map(function($paragraph) {
|
||||
return html_entity_decode(strip_tags($paragraph), ENT_QUOTES, 'UTF-8');
|
||||
}, $matches[1]);
|
||||
|
||||
// Filter out empty paragraphs and join with double newlines
|
||||
$fullText = implode("\n\n", array_filter($paragraphs, function($p) {
|
||||
return trim($p) !== '';
|
||||
}));
|
||||
|
||||
return $fullText ?: null;
|
||||
}
|
||||
} else {
|
||||
// Fallback: Extract all paragraph content
|
||||
preg_match_all('/<p[^>]*>(.*?)<\/p>/is', $cleanHtml, $matches);
|
||||
}
|
||||
|
||||
// Final fallback: Extract all paragraph content
|
||||
preg_match_all('/<p[^>]*>(.*?)<\/p>/is', $cleanHtml, $matches);
|
||||
if (!empty($matches[1])) {
|
||||
$paragraphs = array_map(function($paragraph) {
|
||||
return html_entity_decode(strip_tags($paragraph), ENT_QUOTES, 'UTF-8');
|
||||
|
|
|
|||
|
|
@ -9,38 +9,10 @@ class BelgaHomepageParser
|
|||
*/
|
||||
public static function extractArticleUrls(string $html): array
|
||||
{
|
||||
// Find all relative article links (most articles use relative paths)
|
||||
preg_match_all('/<a[^>]+href="(\/[a-z0-9-]+)"/', $html, $matches);
|
||||
|
||||
// Blacklist of non-article paths
|
||||
$blacklistPaths = [
|
||||
'/',
|
||||
'/de',
|
||||
'/feed',
|
||||
'/search',
|
||||
'/category',
|
||||
'/about',
|
||||
'/contact',
|
||||
'/privacy',
|
||||
'/terms',
|
||||
];
|
||||
preg_match_all('/href="(https:\/\/www\.belganewsagency\.eu\/[a-z0-9-]+)"/', $html, $matches);
|
||||
|
||||
$urls = collect($matches[1])
|
||||
->unique()
|
||||
->filter(function ($path) use ($blacklistPaths) {
|
||||
// Exclude exact matches and paths starting with blacklisted paths
|
||||
foreach ($blacklistPaths as $blacklistedPath) {
|
||||
if ($path === $blacklistedPath || str_starts_with($path, $blacklistedPath . '/')) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})
|
||||
->map(function ($path) {
|
||||
// Convert relative paths to absolute URLs
|
||||
return 'https://www.belganewsagency.eu' . $path;
|
||||
})
|
||||
->values()
|
||||
->toArray();
|
||||
|
||||
return $urls;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@
|
|||
use App\Models\Article;
|
||||
use App\Models\ArticlePublication;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\Route;
|
||||
use App\Modules\Lemmy\Services\LemmyPublisher;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
|
|
@ -17,49 +16,28 @@
|
|||
|
||||
class ArticlePublishingService
|
||||
{
|
||||
public function __construct(private LogSaver $logSaver)
|
||||
{
|
||||
}
|
||||
/**
|
||||
* Factory seam to create publisher instances (helps testing without network calls)
|
||||
*/
|
||||
protected function makePublisher(mixed $account): LemmyPublisher
|
||||
{
|
||||
return new LemmyPublisher($account);
|
||||
}
|
||||
/**
|
||||
* @param array<string, mixed> $extractedData
|
||||
* @return Collection<int, ArticlePublication>
|
||||
* @return EloquentCollection<int, ArticlePublication>
|
||||
* @throws PublishException
|
||||
*/
|
||||
public function publishToRoutedChannels(Article $article, array $extractedData): Collection
|
||||
public function publishToRoutedChannels(Article $article, array $extractedData): EloquentCollection
|
||||
{
|
||||
if (! $article->isValid()) {
|
||||
if (! $article->is_valid) {
|
||||
throw new PublishException($article, PlatformEnum::LEMMY, new RuntimeException('CANNOT_PUBLISH_INVALID_ARTICLE'));
|
||||
}
|
||||
|
||||
$feed = $article->feed;
|
||||
|
||||
/** @var EloquentCollection<int, PlatformChannel> $activeChannels */
|
||||
$activeChannels = $feed->activeChannels()->with(['platformInstance', 'activePlatformAccounts'])->get();
|
||||
|
||||
// Get active routes with keywords instead of just channels
|
||||
$activeRoutes = Route::where('feed_id', $feed->id)
|
||||
->where('is_active', true)
|
||||
->with(['platformChannel.platformInstance', 'platformChannel.activePlatformAccounts', 'keywords'])
|
||||
->orderBy('priority', 'desc')
|
||||
->get();
|
||||
|
||||
// Filter routes based on keyword matches
|
||||
$matchingRoutes = $activeRoutes->filter(function (Route $route) use ($extractedData) {
|
||||
return $this->routeMatchesArticle($route, $extractedData);
|
||||
});
|
||||
|
||||
return $matchingRoutes->map(function (Route $route) use ($article, $extractedData) {
|
||||
$channel = $route->platformChannel;
|
||||
return $activeChannels->map(function (PlatformChannel $channel) use ($article, $extractedData) {
|
||||
$account = $channel->activePlatformAccounts()->first();
|
||||
|
||||
if (! $account) {
|
||||
$this->logSaver->warning('No active account for channel', $channel, [
|
||||
'article_id' => $article->id,
|
||||
'route_priority' => $route->priority
|
||||
LogSaver::warning('No active account for channel', $channel, [
|
||||
'article_id' => $article->id
|
||||
]);
|
||||
|
||||
return null;
|
||||
|
|
@ -70,50 +48,13 @@ public function publishToRoutedChannels(Article $article, array $extractedData):
|
|||
->filter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a route matches an article based on keywords
|
||||
* @param array<string, mixed> $extractedData
|
||||
*/
|
||||
private function routeMatchesArticle(Route $route, array $extractedData): bool
|
||||
{
|
||||
// Get active keywords for this route
|
||||
$activeKeywords = $route->keywords->where('is_active', true);
|
||||
|
||||
// If no keywords are defined for this route, the route matches any article
|
||||
if ($activeKeywords->isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Get article content for keyword matching
|
||||
$articleContent = '';
|
||||
if (isset($extractedData['full_article'])) {
|
||||
$articleContent = $extractedData['full_article'];
|
||||
}
|
||||
if (isset($extractedData['title'])) {
|
||||
$articleContent .= ' ' . $extractedData['title'];
|
||||
}
|
||||
if (isset($extractedData['description'])) {
|
||||
$articleContent .= ' ' . $extractedData['description'];
|
||||
}
|
||||
|
||||
// Check if any of the route's keywords match the article content
|
||||
foreach ($activeKeywords as $keywordModel) {
|
||||
$keyword = $keywordModel->keyword;
|
||||
if (stripos($articleContent, $keyword) !== false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $extractedData
|
||||
*/
|
||||
private function publishToChannel(Article $article, array $extractedData, PlatformChannel $channel, mixed $account): ?ArticlePublication
|
||||
{
|
||||
try {
|
||||
$publisher = $this->makePublisher($account);
|
||||
$publisher = new LemmyPublisher($account);
|
||||
$postData = $publisher->publishToChannel($article, $extractedData, $channel);
|
||||
|
||||
$publication = ArticlePublication::create([
|
||||
|
|
@ -126,13 +67,14 @@ private function publishToChannel(Article $article, array $extractedData, Platfo
|
|||
'publication_data' => $postData,
|
||||
]);
|
||||
|
||||
$this->logSaver->info('Published to channel via keyword-filtered routing', $channel, [
|
||||
'article_id' => $article->id
|
||||
LogSaver::info('Published to channel via routing', $channel, [
|
||||
'article_id' => $article->id,
|
||||
'priority' => $channel->pivot->priority ?? null
|
||||
]);
|
||||
|
||||
return $publication;
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->warning('Failed to publish to channel', $channel, [
|
||||
LogSaver::warning('Failed to publish to channel', $channel, [
|
||||
'article_id' => $article->id,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\View\Components;
|
||||
|
||||
use Illuminate\View\Component;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AppLayout extends Component
|
||||
{
|
||||
/**
|
||||
* Get the view / contents that represents the component.
|
||||
*/
|
||||
public function render(): View
|
||||
{
|
||||
return view('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\View\Components;
|
||||
|
||||
use Illuminate\View\Component;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class GuestLayout extends Component
|
||||
{
|
||||
/**
|
||||
* Get the view / contents that represents the component.
|
||||
*/
|
||||
public function render(): View
|
||||
{
|
||||
return view('layouts.guest');
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue