Compare commits
No commits in common. "main" and "v1.3.2" have entirely different histories.
273 changed files with 2542 additions and 23440 deletions
|
|
@ -1,4 +1,4 @@
|
|||
APP_NAME="Fedi Feed Router"
|
||||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_KEY=
|
||||
APP_DEBUG=true
|
||||
|
|
|
|||
|
|
@ -4,20 +4,27 @@ on:
|
|||
push:
|
||||
branches: ['release/*']
|
||||
pull_request:
|
||||
branches: [main, 'release/*']
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: forge.lvl0.xyz/lvl0/fedi-feed-router-ci:php8.3-3
|
||||
image: catthehacker/ubuntu:act-latest
|
||||
steps:
|
||||
- uses: https://data.forgejo.org/actions/checkout@v4
|
||||
|
||||
- name: Set up PHP
|
||||
uses: https://github.com/shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.3'
|
||||
extensions: pdo_sqlite, mbstring, xml, dom
|
||||
coverage: pcov
|
||||
|
||||
- name: Cache Composer dependencies
|
||||
uses: https://data.forgejo.org/actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/composer
|
||||
path: ~/.composer/cache
|
||||
key: composer-${{ hashFiles('composer.lock') }}
|
||||
restore-keys: composer-
|
||||
|
||||
|
|
@ -31,7 +38,76 @@ jobs:
|
|||
run: vendor/bin/pint --test
|
||||
|
||||
- name: Static analysis
|
||||
run: vendor/bin/phpstan analyse --memory-limit=1G
|
||||
run: vendor/bin/phpstan analyse
|
||||
|
||||
- name: Tests
|
||||
run: php -d memory_limit=512M vendor/bin/phpunit
|
||||
run: php artisan test --coverage-clover coverage.xml --coverage-text
|
||||
|
||||
- name: Parse coverage
|
||||
if: github.event_name == 'pull_request'
|
||||
id: coverage
|
||||
run: |
|
||||
COVERAGE=$(php -r '
|
||||
$xml = simplexml_load_file("coverage.xml");
|
||||
if ($xml === false || !isset($xml->project->metrics)) {
|
||||
echo "0";
|
||||
exit;
|
||||
}
|
||||
$metrics = $xml->project->metrics;
|
||||
$statements = (int) $metrics["statements"];
|
||||
$covered = (int) $metrics["coveredstatements"];
|
||||
echo $statements > 0 ? round(($covered / $statements) * 100, 2) : 0;
|
||||
')
|
||||
echo "percentage=$COVERAGE" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Comment coverage on PR
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
COVERAGE: ${{ steps.coverage.outputs.percentage }}
|
||||
REPO: ${{ github.repository }}
|
||||
SERVER_URL: ${{ github.server_url }}
|
||||
COMMIT_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
API_URL="${SERVER_URL}/api/v1/repos/${REPO}/issues/${PR_NUMBER}/comments"
|
||||
MARKER="<!-- ffr-ci-coverage-report -->"
|
||||
|
||||
BODY="${MARKER}
|
||||
## Code Coverage Report
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| **Line Coverage** | ${COVERAGE}% |
|
||||
|
||||
_Updated by CI — commit ${COMMIT_SHA}_"
|
||||
|
||||
# Find existing coverage comment
|
||||
EXISTING=$(curl -sf -H "Authorization: token ${FORGEJO_TOKEN}" \
|
||||
"${API_URL}?limit=50" | \
|
||||
php -r '
|
||||
$comments = json_decode(file_get_contents("php://stdin"), true);
|
||||
if (!is_array($comments)) exit;
|
||||
foreach ($comments as $c) {
|
||||
if (str_contains($c["body"], "<!-- ffr-ci-coverage-report -->")) {
|
||||
echo $c["id"];
|
||||
exit;
|
||||
}
|
||||
}
|
||||
' || true)
|
||||
|
||||
if [ -n "$EXISTING" ]; then
|
||||
# Update existing comment
|
||||
curl -sf -X PATCH \
|
||||
-H "Authorization: token ${FORGEJO_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(php -r 'echo json_encode(["body" => $argv[1]]);' "$BODY")" \
|
||||
"${SERVER_URL}/api/v1/repos/${REPO}/issues/comments/${EXISTING}" > /dev/null
|
||||
else
|
||||
# Create new comment
|
||||
curl -sf -X POST \
|
||||
-H "Authorization: token ${FORGEJO_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(php -r 'echo json_encode(["body" => $argv[1]]);' "$BODY")" \
|
||||
"${API_URL}" > /dev/null
|
||||
fi
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
name: Build and Push Base Images
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'docker/build/**'
|
||||
- '.forgejo/workflows/images.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
images:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: catthehacker/ubuntu:act-latest
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- name: fedi-feed-router-base
|
||||
file: docker/build/Dockerfile.base
|
||||
version: php8.3-1
|
||||
- name: fedi-feed-router-ci
|
||||
file: docker/build/Dockerfile.ci
|
||||
version: php8.3-3
|
||||
steps:
|
||||
- uses: https://data.forgejo.org/actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: https://data.forgejo.org/docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Forgejo Registry
|
||||
uses: https://data.forgejo.org/docker/login-action@v3
|
||||
with:
|
||||
registry: forge.lvl0.xyz
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Build and push
|
||||
uses: https://data.forgejo.org/docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ${{ matrix.file }}
|
||||
push: true
|
||||
tags: |
|
||||
forge.lvl0.xyz/lvl0/${{ matrix.name }}:${{ matrix.version }}
|
||||
forge.lvl0.xyz/lvl0/${{ matrix.name }}:latest
|
||||
forge.lvl0.xyz/lvl0/${{ matrix.name }}:${{ github.sha }}
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -19,10 +19,8 @@ npm-debug.log
|
|||
yarn-error.log
|
||||
/package-lock.json
|
||||
/auth.json
|
||||
/composer.lock
|
||||
/.idea
|
||||
/coverage-report*
|
||||
/coverage.xml
|
||||
/.php-cs-fixer.dist.php
|
||||
/.php-cs-fixer.cache
|
||||
/.codewhale
|
||||
.aider*
|
||||
|
|
|
|||
63
CHANGELOG.md
63
CHANGELOG.md
|
|
@ -1,63 +0,0 @@
|
|||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [1.4.2] - 2026-08-16
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix Belga discovery always dropping the newest press release (#158)
|
||||
- The Belga API `offset` parameter is a 0-based item index, so the configured `offset=1` skipped the newest article on every fetch. A data migration repoints the existing Belga feed to `offset=0`.
|
||||
- Fix articles validated before their feed had an active route never becoming routable (#157)
|
||||
- Route articles are now backfilled when a route is created or re-activated, using the article content stored at validation time — no re-fetch.
|
||||
|
||||
## [1.4.1] - 2026-08-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix migrations being unable to run since v1.3.7, which left the dashboard and article approval returning a 500 and publishing failing (#150)
|
||||
- The migration converting channel community ids logged in to Lemmy to resolve them, once per channel. Lemmy rate-limits authentication, so it failed and blocked the eight migrations behind it.
|
||||
- **Upgrading deletes channels whose community id was never converted, along with their routes, keywords and publication history.** Recreate them from the Channels page; the community is validated against the instance at creation.
|
||||
- Fix tests failing at random from factories generating duplicate values for columns with unique constraints (#152)
|
||||
- Fix the daily publish cap tests depending on the time of day they ran (#152)
|
||||
|
||||
### Changed
|
||||
|
||||
- CI runs in about two minutes instead of fifteen to thirty (#147)
|
||||
- PHP is now baked into a prebuilt image rather than installed on every run, coverage is no longer collected since nothing consumed it, and the Composer cache path was wrong so no packages were ever cached.
|
||||
- Give the CI runner a fallback DNS resolver, so a dropped lookup no longer times out an entire run (#153)
|
||||
|
||||
## [1.4.0] - 2026-08-14
|
||||
|
||||
### Added
|
||||
|
||||
- Add a dark theme (#88)
|
||||
- Add a daily publish cap, so a feed returning a large batch cannot flood a community (#90)
|
||||
- Defaults to unlimited, so existing installs publish exactly as before until someone opts in.
|
||||
- Add an in-app activity log showing what the automation has been doing (#91)
|
||||
- Add a scheduled platform credential health check (#95)
|
||||
- Add a warning for feeds that fetch successfully but return no articles (#116)
|
||||
- Add community existence validation when creating a channel (#114)
|
||||
- Add edit and delete actions to feed and channel cards (#136, #137, #141)
|
||||
- Deleting a channel cascades to its routes, keywords, route articles and publications, so past days in the dashboard charts lose those data points.
|
||||
- Add a Failed tab surfacing publishes that did not go through (#142)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix a failed publish disappearing from the interface instead of returning to the user (#142)
|
||||
- Automatic retry is removed, replaced by a per-row Retry action.
|
||||
- Fix modals being unusable by keyboard (#111)
|
||||
- Fix oversized thumbnails (#138)
|
||||
- Fix renamed Tailwind v4 utilities rendering at a shifted scale (#109)
|
||||
|
||||
### Changed
|
||||
|
||||
- Rework the dashboard with trends and breakdowns over a selectable date range (#83)
|
||||
- Make an article's routing legible on the Articles page, with per-feed colour, grouping and a filter (#113)
|
||||
- Store an article's thumbnail when it is fetched rather than re-fetching the page on every publish (#119)
|
||||
- Replace the stock Laravel branding with the project's own (#121)
|
||||
- Extract business logic from services into Action classes (#144)
|
||||
|
||||
### Removed
|
||||
|
||||
- Remove the unused Inertia, Ziggy and Breeze dependencies, the dead Jenkinsfile, and the Inertia middleware (#140)
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
# Contributing
|
||||
|
||||
Thanks for your interest in FFR. This is a small self-hosted project, issues and
|
||||
pull requests are both welcome.
|
||||
|
||||
## Reporting issues
|
||||
|
||||
Use [Issues](https://forge.lvl0.xyz/lvl0/fedi-feed-router/issues).
|
||||
|
||||
For bugs, include what you expected, what happened, and enough detail to
|
||||
reproduce it. If a feed is behaving unexpectedly, the feed URL matters most
|
||||
because differences in how providers structure their RSS or Atom output are the
|
||||
usual cause. Relevant log output helps; `dev-logs` follows the application log.
|
||||
|
||||
## Development setup
|
||||
|
||||
Requires PHP 8.2+ and Docker. The development environment runs in containers
|
||||
defined by `docker/dev/docker-compose.yml`.
|
||||
|
||||
On NixOS, or anywhere with Nix installed:
|
||||
|
||||
```bash
|
||||
git clone https://forge.lvl0.xyz/lvl0/fedi-feed-router.git
|
||||
cd fedi-feed-router
|
||||
nix-shell
|
||||
```
|
||||
|
||||
The shell prints the available commands on entry and can start the containers
|
||||
for you:
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `dev-up` | Start the development environment |
|
||||
| `dev-down` | Stop the development environment |
|
||||
| `dev-restart` | Restart the containers |
|
||||
| `dev-rebuild` | Rebuild the images |
|
||||
| `dev-shell` | Enter the app container |
|
||||
| `dev-artisan <cmd>` | Run an artisan command |
|
||||
| `dev-logs` | Follow the application log |
|
||||
| `dev-logs-db` | Follow the database log |
|
||||
|
||||
Once running:
|
||||
|
||||
| Service | URL |
|
||||
|---------|-----|
|
||||
| App | http://localhost:8000 |
|
||||
| Vite | http://localhost:5173 |
|
||||
| MariaDB | localhost:3307 |
|
||||
| Redis | localhost:6380 |
|
||||
|
||||
Without Nix, start the same containers directly from
|
||||
`docker/dev/docker-compose.yml`. Contributions improving the setup instructions
|
||||
for other platforms are welcome.
|
||||
|
||||
## Before opening a pull request
|
||||
|
||||
Three checks run in CI, and all three must pass. Run them locally first, from
|
||||
inside the app container or anywhere the project's dependencies are available:
|
||||
|
||||
```bash
|
||||
vendor/bin/pint --test # code style, Laravel preset
|
||||
vendor/bin/phpstan analyse # static analysis, level 7
|
||||
php artisan test # PHPUnit, Unit and Feature suites
|
||||
```
|
||||
|
||||
Some conventions:
|
||||
|
||||
- **Static analysis.** PHPStan runs at level 7 with a baseline
|
||||
(`phpstan-baseline.neon`) covering pre-existing findings. Don't add baseline
|
||||
entries to silence errors in code you're writing. Fix the cause instead.
|
||||
Inline `@phpstan-ignore` comments aren't used in this project. The baseline is
|
||||
for cases where the analyser or an upstream docblock is wrong, not real bugs.
|
||||
- **Tests.** New behaviour needs a test. Tests must run offline, so use fixtures
|
||||
or fakes rather than reaching for the network.
|
||||
- **Dependencies.** `composer.lock` is committed. If you change dependencies,
|
||||
commit the updated lockfile alongside `composer.json`.
|
||||
|
||||
## Commits
|
||||
|
||||
One commit does one thing. Keep each commit passing all three checks so history
|
||||
stays bisectable. Separate renames from behaviour changes, and mechanical edits
|
||||
from logic.
|
||||
|
||||
Commit messages are a single line, referencing the issue they belong to:
|
||||
|
||||
```
|
||||
141 - Add channel deletion to the Channels page
|
||||
```
|
||||
|
||||
No body, no trailers.
|
||||
|
||||
## License
|
||||
|
||||
By contributing, you agree that your contributions are licensed under the
|
||||
[GNU AGPL-3.0](LICENSE), the same license as the project.
|
||||
|
|
@ -101,9 +101,6 @@ php artisan db:seed --force || echo "Seeders failed or already run"
|
|||
# Start Horizon in the background
|
||||
php artisan horizon &
|
||||
|
||||
# Start the scheduler in the background
|
||||
php artisan schedule:work &
|
||||
|
||||
# Start FrankenPHP
|
||||
exec frankenphp run --config /etc/caddy/Caddyfile
|
||||
EOF
|
||||
|
|
|
|||
|
|
@ -114,9 +114,6 @@ npm run dev &
|
|||
# Start Horizon (queue worker) in background
|
||||
php artisan horizon &
|
||||
|
||||
# Scheduler left off in dev on purpose; run schedule:work by hand when needed.
|
||||
# php artisan schedule:work &
|
||||
|
||||
# Start FrankenPHP
|
||||
exec frankenphp run --config /etc/caddy/Caddyfile
|
||||
EOF
|
||||
|
|
|
|||
241
Jenkinsfile
vendored
Normal file
241
Jenkinsfile
vendored
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
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'
|
||||
}
|
||||
}
|
||||
}
|
||||
661
LICENSE
661
LICENSE
|
|
@ -1,661 +0,0 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
138
README.md
138
README.md
|
|
@ -1,77 +1,26 @@
|
|||
# FFR: Feed to Fediverse Router
|
||||
# FFR (Feed to Fediverse Router)
|
||||
|
||||
[](https://forge.lvl0.xyz/lvl0/fedi-feed-router/actions)
|
||||
[](https://forge.lvl0.xyz/lvl0/fedi-feed-router/releases)
|
||||
[](LICENSE)
|
||||
|
||||
Routes news articles to Fediverse communities. FFR polls a set of sources,
|
||||
extracts each article, and posts it to the Lemmy communities you map it to,
|
||||
either automatically or after you approve it.
|
||||
|
||||
It is meant to run unattended on your own server: point it at a source, map that
|
||||
source to a community, and let it publish on a schedule you control.
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||
|
||||
The dashboard, showing article volume over a selected range, approval and publish
|
||||
success rates, and per-feed breakdowns.
|
||||
|
||||

|
||||
|
||||
The review queue. Each row is one feed and community pairing, grouped by feed,
|
||||
with the routing shown above the headline.
|
||||
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.
|
||||
|
||||
## Features
|
||||
|
||||
- **Article routing**: map each source to one or more Lemmy communities, with
|
||||
optional keyword filtering
|
||||
- **Approval workflow**: review articles before they publish, or let them go out
|
||||
automatically
|
||||
- **Publishing controls**: a global interval and an optional daily cap, so a
|
||||
source returning a large batch cannot flood a community
|
||||
- **Dashboard**: articles fetched and published over time, approval and publish
|
||||
success rates, and per-source and per-community breakdowns
|
||||
- **Activity log**: a chronological record of what the automation has done
|
||||
- **Health checks**: warnings for sources that stop producing articles and for
|
||||
platform credentials that stop working
|
||||
- **Dark theme**
|
||||
- **Single container**: FrankenPHP serves the app, with MariaDB and Redis
|
||||
alongside
|
||||
|
||||
## Sources and platforms
|
||||
|
||||
FFR ships with parsers for three sources:
|
||||
|
||||
| Source | Type |
|
||||
|--------|------|
|
||||
| VRT News | Website |
|
||||
| Belga | Website |
|
||||
| The Guardian | RSS |
|
||||
|
||||
Some sources publish a usable feed and some do not, so a source is either read
|
||||
from RSS or scraped from its pages. Either way a parser handles it, registered
|
||||
in `config/feed.php`.
|
||||
|
||||
Adding a source means implementing `ArticleParserInterface` (three methods:
|
||||
`canParse`, `extractData`, `getSourceName`) and registering it. See
|
||||
[CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
Lemmy is currently the only supported platform.
|
||||
- **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
|
||||
|
||||
## Self-hosting
|
||||
|
||||
Images are published to `forge.lvl0.xyz/lvl0/fedi-feed-router`. The example below
|
||||
pins a release tag; check [Releases](https://forge.lvl0.xyz/lvl0/fedi-feed-router/releases)
|
||||
for the current one, and the [CHANGELOG](CHANGELOG.md) before upgrading.
|
||||
The production image is available at `forge.lvl0.xyz/lvl0/fedi-feed-router:latest`.
|
||||
|
||||
### docker-compose.yml
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
image: forge.lvl0.xyz/lvl0/fedi-feed-router:v1.4.1
|
||||
image: forge.lvl0.xyz/lvl0/fedi-feed-router:latest
|
||||
container_name: ffr_app
|
||||
restart: always
|
||||
ports:
|
||||
|
|
@ -121,59 +70,42 @@ ### docker-compose.yml
|
|||
app_storage:
|
||||
```
|
||||
|
||||
### Environment variables
|
||||
### 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`) |
|
||||
| `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 |
|
||||
|
||||
## Usage
|
||||
|
||||
On first run FFR walks you through onboarding. After that:
|
||||
|
||||
1. **Add a channel** on the Channels page. A channel is a Lemmy community on a
|
||||
given instance, together with the account that posts to it. The community is
|
||||
picked from the instance, so a typo cannot create a channel that fails later.
|
||||
2. **Add a feed** on the Feeds page, choosing one of the supported sources.
|
||||
3. **Add a route** on the Routes page, mapping a feed to a channel. Keywords on a
|
||||
route restrict it to articles that match.
|
||||
|
||||
Articles are then discovered on a schedule. Each one becomes a row per matching
|
||||
route, so an article routed to three communities is three separate decisions.
|
||||
Approve one on the Articles page and it publishes to that route's community;
|
||||
publishing failures come back to you on the Failed tab rather than retrying
|
||||
silently.
|
||||
|
||||
Publishing runs every five minutes, one article per run, bounded by the daily cap
|
||||
if you set one.
|
||||
|
||||
## Development
|
||||
|
||||
### NixOS / Nix
|
||||
|
||||
```bash
|
||||
git clone https://forge.lvl0.xyz/lvl0/fedi-feed-router.git
|
||||
cd fedi-feed-router
|
||||
cd ffr
|
||||
nix-shell
|
||||
```
|
||||
|
||||
The shell prints the available commands and can start the containers for you.
|
||||
The shell will display available commands and optionally start the containers for you.
|
||||
|
||||
#### Available Commands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `dev-up` | Start the development environment |
|
||||
| `dev-down` | Stop the development environment |
|
||||
| `dev-restart` | Restart the containers |
|
||||
| `dev-rebuild` | Rebuild the images |
|
||||
| `dev-shell` | Enter the app container |
|
||||
| `dev-artisan <cmd>` | Run an artisan command |
|
||||
| `dev-logs` | Follow the application log |
|
||||
| `dev-logs-db` | Follow the database log |
|
||||
| `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 |
|
||||
|
||||
#### Services
|
||||
|
||||
| Service | URL |
|
||||
|---------|-----|
|
||||
|
|
@ -182,22 +114,14 @@ ### NixOS / Nix
|
|||
| MariaDB | localhost:3307 |
|
||||
| Redis | localhost:6380 |
|
||||
|
||||
### Other platforms
|
||||
### Other Platforms
|
||||
|
||||
Contributions welcome for development setup instructions on other platforms.
|
||||
|
||||
## Contributing
|
||||
|
||||
Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for
|
||||
the development setup, the checks that run in CI, and the commit conventions.
|
||||
|
||||
For bugs and questions, use
|
||||
[Issues](https://forge.lvl0.xyz/lvl0/fedi-feed-router/issues).
|
||||
|
||||
## Note on AI assistance
|
||||
|
||||
This project was developed with AI assistance.
|
||||
|
||||
## License
|
||||
|
||||
FFR is free software, licensed under the [GNU AGPL-3.0](LICENSE).
|
||||
This project is open-source software licensed under the [AGPL-3.0 license](LICENSE).
|
||||
|
||||
## Support
|
||||
|
||||
For issues and questions, please use [Issues](https://forge.lvl0.xyz/lvl0/fedi-feed-router/issues).
|
||||
|
|
|
|||
|
|
@ -1,35 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Route;
|
||||
|
||||
class BackfillRouteArticlesAction
|
||||
{
|
||||
public function __construct(
|
||||
private CreateRouteArticlesAction $createRouteArticles,
|
||||
) {}
|
||||
|
||||
public function execute(Route $route): void
|
||||
{
|
||||
if (! $route->is_active) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Articles already validated with content, but never routed to this
|
||||
// route. Uses the stored content rather than re-fetching, so a large
|
||||
// backlog cannot trigger a network storm (#157).
|
||||
Article::query()
|
||||
->where('feed_id', $route->feed_id)
|
||||
->whereNotNull('content')
|
||||
->whereDoesntHave('routeArticles', function ($query) use ($route) {
|
||||
$query->where('feed_id', $route->feed_id)
|
||||
->where('platform_channel_id', $route->platform_channel_id);
|
||||
})
|
||||
->lazy()
|
||||
->each(function (Article $article) use ($route) {
|
||||
$this->createRouteArticles->createForRoute($article, $route, (string) $article->content);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -10,7 +10,7 @@
|
|||
|
||||
class CreateChannelAction
|
||||
{
|
||||
public function execute(string $name, int $communityId, int $platformInstanceId, ?int $languageId = null, ?string $description = null): PlatformChannel
|
||||
public function execute(string $name, int $platformInstanceId, ?int $languageId = null, ?string $description = null): PlatformChannel
|
||||
{
|
||||
$platformInstance = PlatformInstance::findOrFail($platformInstanceId);
|
||||
|
||||
|
|
@ -22,10 +22,10 @@ public function execute(string $name, int $communityId, int $platformInstanceId,
|
|||
throw new RuntimeException('No active platform accounts found for this instance. Please create a platform account first.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($name, $communityId, $platformInstanceId, $languageId, $description, $activeAccounts) {
|
||||
return DB::transaction(function () use ($name, $platformInstanceId, $languageId, $description, $activeAccounts) {
|
||||
$channel = PlatformChannel::create([
|
||||
'platform_instance_id' => $platformInstanceId,
|
||||
'channel_id' => $communityId,
|
||||
'channel_id' => $name,
|
||||
'name' => $name,
|
||||
'display_name' => ucfirst($name),
|
||||
'description' => $description,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\AccountStatusEnum;
|
||||
use App\Exceptions\PlatformAuthException;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformInstance;
|
||||
|
|
@ -47,7 +46,7 @@ public function execute(string $instanceDomain, string $username, string $passwo
|
|||
'api_token' => $authResponse['jwt'] ?? null,
|
||||
],
|
||||
'is_active' => true,
|
||||
'status' => AccountStatusEnum::HEALTHY,
|
||||
'status' => 'active',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Events\RouteActivated;
|
||||
use App\Models\Route;
|
||||
|
||||
class CreateRouteAction
|
||||
|
|
@ -13,7 +12,7 @@ class CreateRouteAction
|
|||
*/
|
||||
public function execute(int $feedId, int $platformChannelId, int $priority = 0, bool $isActive = true): Route
|
||||
{
|
||||
$route = Route::firstOrCreate(
|
||||
return Route::firstOrCreate(
|
||||
[
|
||||
'feed_id' => $feedId,
|
||||
'platform_channel_id' => $platformChannelId,
|
||||
|
|
@ -23,11 +22,5 @@ public function execute(int $feedId, int $platformChannelId, int $priority = 0,
|
|||
'is_active' => $isActive,
|
||||
]
|
||||
);
|
||||
|
||||
if ($route->wasRecentlyCreated && $route->is_active) {
|
||||
RouteActivated::dispatch($route->feed_id, $route->platform_channel_id);
|
||||
}
|
||||
|
||||
return $route;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,81 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\ApprovalStatusEnum;
|
||||
use App\Models\Article;
|
||||
use App\Models\Keyword;
|
||||
use App\Models\Route;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class CreateRouteArticlesAction
|
||||
{
|
||||
public function execute(Article $article, string $content): void
|
||||
{
|
||||
$activeRoutes = Route::where('feed_id', $article->feed_id)
|
||||
->where('is_active', true)
|
||||
->get();
|
||||
|
||||
foreach ($activeRoutes as $route) {
|
||||
$this->createForRoute($article, $route, $content);
|
||||
}
|
||||
}
|
||||
|
||||
public function createForRoute(Article $article, Route $route, string $content): void
|
||||
{
|
||||
$routeKeywords = Keyword::where('feed_id', $route->feed_id)
|
||||
->where('platform_channel_id', $route->platform_channel_id)
|
||||
->where('is_active', true)
|
||||
->get();
|
||||
|
||||
// Match keywords against full article content, title, and description
|
||||
$searchableContent = $content.' '.$article->title.' '.$article->description;
|
||||
$status = $this->evaluateKeywords($routeKeywords, $searchableContent);
|
||||
|
||||
if ($status === ApprovalStatusEnum::PENDING && $this->shouldAutoApprove($route)) {
|
||||
$status = ApprovalStatusEnum::APPROVED;
|
||||
}
|
||||
|
||||
RouteArticle::firstOrCreate(
|
||||
[
|
||||
'feed_id' => $route->feed_id,
|
||||
'platform_channel_id' => $route->platform_channel_id,
|
||||
'article_id' => $article->id,
|
||||
],
|
||||
[
|
||||
'approval_status' => $status,
|
||||
'validated_at' => now(),
|
||||
'decided_at' => $status === ApprovalStatusEnum::PENDING ? null : now(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Keyword> $keywords
|
||||
*/
|
||||
private function evaluateKeywords(Collection $keywords, string $content): ApprovalStatusEnum
|
||||
{
|
||||
if ($keywords->isEmpty()) {
|
||||
return ApprovalStatusEnum::PENDING;
|
||||
}
|
||||
|
||||
foreach ($keywords as $keyword) {
|
||||
if (stripos($content, $keyword->keyword) !== false) {
|
||||
return ApprovalStatusEnum::PENDING;
|
||||
}
|
||||
}
|
||||
|
||||
return ApprovalStatusEnum::REJECTED;
|
||||
}
|
||||
|
||||
private function shouldAutoApprove(Route $route): bool
|
||||
{
|
||||
if ($route->auto_approve !== null) {
|
||||
return $route->auto_approve;
|
||||
}
|
||||
|
||||
return ! Setting::isPublishingApprovalsEnabled();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Services\Factories\ArticleParserFactory;
|
||||
use App\Services\Http\HttpFetcher;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
|
||||
class FetchArticleDataAction
|
||||
{
|
||||
public function __construct(
|
||||
private LogSaver $logSaver
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function execute(Article $article): array
|
||||
{
|
||||
try {
|
||||
$html = HttpFetcher::fetchHtml($article->url);
|
||||
$parser = ArticleParserFactory::getParser($article->url);
|
||||
|
||||
return $parser->extractData($html);
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Exception while fetching article data', null, [
|
||||
'url' => $article->url,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Feed;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class FetchFeedArticlesAction
|
||||
{
|
||||
public function __construct(
|
||||
private LogSaver $logSaver,
|
||||
private FetchRssArticlesAction $fetchRssArticles,
|
||||
private FetchWebsiteArticlesAction $fetchWebsiteArticles,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
public function execute(Feed $feed): Collection
|
||||
{
|
||||
if ($feed->type === 'rss') {
|
||||
return $this->fetchRssArticles->execute($feed);
|
||||
} elseif ($feed->type === 'website') {
|
||||
return $this->fetchWebsiteArticles->execute($feed);
|
||||
}
|
||||
|
||||
$this->logSaver->warning('Unsupported feed type', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_type' => $feed->type,
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Feed;
|
||||
use App\Services\Http\HttpFetcher;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class FetchRssArticlesAction
|
||||
{
|
||||
public function __construct(
|
||||
private LogSaver $logSaver,
|
||||
private SaveArticleAction $saveArticle,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
public function execute(Feed $feed): Collection
|
||||
{
|
||||
try {
|
||||
$xml = HttpFetcher::fetchHtml($feed->url);
|
||||
|
||||
$previousUseErrors = libxml_use_internal_errors(true);
|
||||
|
||||
try {
|
||||
$rss = simplexml_load_string($xml);
|
||||
} finally {
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previousUseErrors);
|
||||
}
|
||||
|
||||
if ($rss === false || ! isset($rss->channel->item)) {
|
||||
$this->logSaver->warning('Failed to parse RSS feed XML', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
|
||||
$articles = collect();
|
||||
foreach ($rss->channel->item as $item) {
|
||||
$link = (string) $item->link;
|
||||
if ($link !== '') {
|
||||
$articles->push($this->saveArticle->execute($link, $feed->id));
|
||||
}
|
||||
}
|
||||
|
||||
return $articles;
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Failed to fetch articles from RSS feed', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Feed;
|
||||
use App\Services\Factories\HomepageParserFactory;
|
||||
use App\Services\Http\HttpFetcher;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class FetchWebsiteArticlesAction
|
||||
{
|
||||
public function __construct(
|
||||
private LogSaver $logSaver,
|
||||
private SaveArticleAction $saveArticle,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
public function execute(Feed $feed): Collection
|
||||
{
|
||||
try {
|
||||
$parser = HomepageParserFactory::getParserForFeed($feed);
|
||||
|
||||
if (! $parser) {
|
||||
$this->logSaver->warning('No parser available for feed URL', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
|
||||
$html = HttpFetcher::fetchHtml($feed->url);
|
||||
$urls = $parser->extractArticleUrls($html);
|
||||
|
||||
return collect($urls)
|
||||
->map(fn (string $url) => $this->saveArticle->execute($url, $feed->id));
|
||||
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Failed to fetch articles from website feed', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,167 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\Enums\NotificationSeverityEnum;
|
||||
use App\Enums\NotificationTypeEnum;
|
||||
use App\Enums\PublishStatusEnum;
|
||||
use App\Events\ActionPerformed;
|
||||
use App\Events\ActivityLogged;
|
||||
use App\Exceptions\PublishException;
|
||||
use App\Models\Article;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Services\Notification\NotificationService;
|
||||
use App\Services\Publishing\ArticlePublishingService;
|
||||
use App\Services\Publishing\PublishOutcome;
|
||||
use Exception;
|
||||
|
||||
class PublishRouteArticleAction
|
||||
{
|
||||
public function __construct(
|
||||
private FetchArticleDataAction $fetchArticleData,
|
||||
private ArticlePublishingService $publishingService,
|
||||
private NotificationService $notificationService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws PublishException
|
||||
*/
|
||||
public function execute(RouteArticle $routeArticle): PublishOutcome
|
||||
{
|
||||
$article = $routeArticle->article;
|
||||
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHING]);
|
||||
|
||||
try {
|
||||
$extractedData = $this->resolvePublishData($article);
|
||||
|
||||
$outcome = $this->hasPublishableContent($extractedData)
|
||||
? $this->publishingService->publishRouteArticle($routeArticle, $extractedData)
|
||||
: PublishOutcome::failure('Could not recover the article content to publish');
|
||||
} catch (Exception $e) {
|
||||
$routeArticle->recordPublishFailed($e->getMessage());
|
||||
|
||||
ActionPerformed::dispatch('Failed to publish article', LogLevelEnum::ERROR, [
|
||||
'article_id' => $article->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::ERROR,
|
||||
"Failed to publish \"{$article->title}\"",
|
||||
['error' => $e->getMessage()],
|
||||
$article,
|
||||
);
|
||||
|
||||
$this->notificationService->send(
|
||||
NotificationTypeEnum::PUBLISH_FAILED,
|
||||
NotificationSeverityEnum::ERROR,
|
||||
"Publish failed: {$article->title}",
|
||||
$e->getMessage(),
|
||||
$article,
|
||||
);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
match (true) {
|
||||
$outcome->succeeded() => $this->recordPublished($routeArticle),
|
||||
$outcome->wasSkipped() => $this->recordSkipped($routeArticle, $outcome),
|
||||
default => $this->recordFailed($routeArticle, $outcome),
|
||||
};
|
||||
|
||||
return $outcome;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $extractedData
|
||||
*/
|
||||
private function hasPublishableContent(array $extractedData): bool
|
||||
{
|
||||
return ! empty($extractedData['description']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function resolvePublishData(Article $article): array
|
||||
{
|
||||
if (empty($article->description) && empty($article->image_url)) {
|
||||
return $this->fetchArticleData->execute($article);
|
||||
}
|
||||
|
||||
return [
|
||||
'title' => $article->title,
|
||||
'description' => $article->description,
|
||||
'thumbnail' => $article->image_url,
|
||||
];
|
||||
}
|
||||
|
||||
private function recordPublished(RouteArticle $routeArticle): void
|
||||
{
|
||||
$routeArticle->update([
|
||||
'publish_status' => PublishStatusEnum::PUBLISHED,
|
||||
'publish_error' => null,
|
||||
]);
|
||||
|
||||
ActionPerformed::dispatch('Published article', LogLevelEnum::INFO, [
|
||||
'article_id' => $routeArticle->article->id,
|
||||
'title' => $routeArticle->article->title,
|
||||
]);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::PUBLISH,
|
||||
"Published \"{$routeArticle->article->title}\"",
|
||||
['route_article_id' => $routeArticle->id],
|
||||
$routeArticle->article,
|
||||
);
|
||||
}
|
||||
|
||||
private function recordSkipped(RouteArticle $routeArticle, PublishOutcome $outcome): void
|
||||
{
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::SKIPPED]);
|
||||
|
||||
ActionPerformed::dispatch('Skipped publishing article', LogLevelEnum::INFO, [
|
||||
'article_id' => $routeArticle->article->id,
|
||||
'title' => $routeArticle->article->title,
|
||||
'reason' => $outcome->reason,
|
||||
]);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::PUBLISH,
|
||||
"Skipped \"{$routeArticle->article->title}\"",
|
||||
['skipped' => true, 'reason' => $outcome->reason],
|
||||
$routeArticle->article,
|
||||
);
|
||||
}
|
||||
|
||||
private function recordFailed(RouteArticle $routeArticle, PublishOutcome $outcome): void
|
||||
{
|
||||
$article = $routeArticle->article;
|
||||
|
||||
$routeArticle->recordPublishFailed($outcome->reason ?? 'Publishing failed');
|
||||
|
||||
ActionPerformed::dispatch('No publication created for article', LogLevelEnum::WARNING, [
|
||||
'article_id' => $article->id,
|
||||
'title' => $article->title,
|
||||
'reason' => $outcome->reason,
|
||||
]);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::ERROR,
|
||||
"Failed to publish \"{$article->title}\"",
|
||||
['reason' => $outcome->reason],
|
||||
$article,
|
||||
);
|
||||
|
||||
$this->notificationService->send(
|
||||
NotificationTypeEnum::PUBLISH_FAILED,
|
||||
NotificationSeverityEnum::WARNING,
|
||||
"Publish failed: {$article->title}",
|
||||
$outcome->reason ?? 'No publication was created for this article.',
|
||||
$article,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
|
||||
class SaveArticleAction
|
||||
{
|
||||
public function __construct(
|
||||
private LogSaver $logSaver
|
||||
) {}
|
||||
|
||||
public function execute(string $url, ?int $feedId = null): Article
|
||||
{
|
||||
try {
|
||||
$article = Article::firstOrCreate(
|
||||
['url' => $url],
|
||||
[
|
||||
'feed_id' => $feedId,
|
||||
'title' => $this->generateFallbackTitle($url),
|
||||
]
|
||||
);
|
||||
|
||||
if ($article->wasRecentlyCreated) {
|
||||
$article->dispatchFetchedEvent();
|
||||
}
|
||||
|
||||
return $article;
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Failed to create article', null, [
|
||||
'url' => $url,
|
||||
'feed_id' => $feedId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
private function generateFallbackTitle(string $url): string
|
||||
{
|
||||
$path = parse_url($url, PHP_URL_PATH);
|
||||
$filename = basename($path ?: $url);
|
||||
|
||||
$title = preg_replace('/\.[^.]*$/', '', $filename);
|
||||
$title = str_replace(['-', '_'], ' ', $title);
|
||||
$title = ucwords($title);
|
||||
|
||||
return $title ?: 'Untitled Article';
|
||||
}
|
||||
}
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Article;
|
||||
|
||||
class ValidateArticleAction
|
||||
{
|
||||
public function __construct(
|
||||
private FetchArticleDataAction $fetchArticleData,
|
||||
private CreateRouteArticlesAction $createRouteArticles,
|
||||
) {}
|
||||
|
||||
public function execute(Article $article): Article
|
||||
{
|
||||
logger('Validating article for routes: '.$article->id);
|
||||
|
||||
$articleData = $this->fetchArticleData->execute($article);
|
||||
|
||||
$updateData = [];
|
||||
|
||||
if (! empty($articleData)) {
|
||||
$updateData['title'] = $articleData['title'] ?? $article->title;
|
||||
$updateData['description'] = $articleData['description'] ?? $article->description;
|
||||
$updateData['content'] = $articleData['full_article'] ?? null;
|
||||
$updateData['image_url'] = ($articleData['thumbnail'] ?? null) ?: $article->image_url;
|
||||
}
|
||||
|
||||
if (! isset($articleData['full_article']) || empty($articleData['full_article'])) {
|
||||
logger()->warning('Article data missing full_article content', [
|
||||
'article_id' => $article->id,
|
||||
'url' => $article->url,
|
||||
]);
|
||||
|
||||
$updateData['validated_at'] = now();
|
||||
$article->update($updateData);
|
||||
|
||||
return $article->refresh();
|
||||
}
|
||||
|
||||
$updateData['validated_at'] = now();
|
||||
$article->update($updateData);
|
||||
|
||||
$this->createRouteArticles->execute($article, $articleData['full_article']);
|
||||
|
||||
return $article->refresh();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Enums\ApprovalStatusEnum;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Support\DateRange;
|
||||
|
||||
class ApprovalRate extends DailySeriesStat
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'approval-rate';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Approval Rate';
|
||||
}
|
||||
|
||||
protected function series(DateRange $range, array $days): SeriesResult
|
||||
{
|
||||
$decisions = RouteArticle::query()
|
||||
->toBase()
|
||||
->whereNotNull('decided_at')
|
||||
->whereBetween('decided_at', [$range->from, $range->to])
|
||||
->whereIn('approval_status', ApprovalStatusEnum::decidedValues())
|
||||
->selectRaw(
|
||||
'DATE(decided_at) as bucket, COUNT(*) as total, SUM(CASE WHEN approval_status = ? THEN 1 ELSE 0 END) as approved',
|
||||
[ApprovalStatusEnum::APPROVED->value],
|
||||
)
|
||||
->groupBy('bucket')
|
||||
->get()
|
||||
->keyBy('bucket');
|
||||
|
||||
$values = array_map(
|
||||
function (string $day) use ($decisions): ?float {
|
||||
$decision = $decisions->get($day);
|
||||
|
||||
if ($decision === null || (int) $decision->total === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return round(((int) $decision->approved / (int) $decision->total) * 100, 1);
|
||||
},
|
||||
$days,
|
||||
);
|
||||
|
||||
return new SeriesResult($days, [
|
||||
new Series('Approval Rate', $values, zeroIsMeaningful: true),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Feed;
|
||||
use App\Support\DateRange;
|
||||
|
||||
class ArticlesPerFeed implements BreakdownStat
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'articles-per-feed';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Articles per Feed';
|
||||
}
|
||||
|
||||
public function for(DateRange $range): BreakdownResult
|
||||
{
|
||||
/** @var array<int, int> $counts */
|
||||
$counts = Article::query()
|
||||
->whereBetween('created_at', [$range->from, $range->to])
|
||||
->selectRaw('feed_id, COUNT(*) as aggregate')
|
||||
->groupBy('feed_id')
|
||||
->pluck('aggregate', 'feed_id')
|
||||
->all();
|
||||
|
||||
// Zero-fill in PHP; assumes the feed table stays small enough to load whole.
|
||||
$rows = Feed::query()
|
||||
->get()
|
||||
->map(fn (Feed $feed): Breakdown => new Breakdown(
|
||||
$feed->name,
|
||||
(int) ($counts[$feed->id] ?? 0),
|
||||
))
|
||||
->all();
|
||||
|
||||
usort(
|
||||
$rows,
|
||||
fn (Breakdown $a, Breakdown $b): int => [$b->count, $a->label] <=> [$a->count, $b->label],
|
||||
);
|
||||
|
||||
return new BreakdownResult($rows);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\ArticlePublication;
|
||||
use App\Support\DateRange;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ArticlesTrend extends DailySeriesStat
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'articles-trend';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Articles Fetched vs Published';
|
||||
}
|
||||
|
||||
protected function series(DateRange $range, array $days): SeriesResult
|
||||
{
|
||||
return new SeriesResult($days, [
|
||||
new Series('Fetched', $this->countByDay(Article::query(), 'created_at', $range, $days)),
|
||||
new Series('Published', $this->countByDay(ArticlePublication::query(), 'published_at', $range, $days)),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<covariant Model> $query
|
||||
* @param array<int, string> $days
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function countByDay(Builder $query, string $column, DateRange $range, array $days): array
|
||||
{
|
||||
/** @var array<string, int> $counts */
|
||||
$counts = $query
|
||||
->whereBetween($column, [$range->from, $range->to])
|
||||
->selectRaw("DATE({$column}) as bucket, COUNT(*) as aggregate")
|
||||
->groupBy('bucket')
|
||||
->pluck('aggregate', 'bucket')
|
||||
->all();
|
||||
|
||||
return array_map(
|
||||
fn (string $day): int => (int) ($counts[$day] ?? 0),
|
||||
$days,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
class Breakdown
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $label,
|
||||
public readonly int $count,
|
||||
) {}
|
||||
}
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
class BreakdownResult
|
||||
{
|
||||
/**
|
||||
* @param array<int, Breakdown> $rows
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $rows,
|
||||
) {}
|
||||
|
||||
public function total(): int
|
||||
{
|
||||
return array_sum(array_map(fn (Breakdown $row): int => $row->count, $this->rows));
|
||||
}
|
||||
|
||||
public function shareOf(Breakdown $row): float
|
||||
{
|
||||
$total = $this->total();
|
||||
|
||||
return $total > 0 ? round(($row->count / $total) * 100, 1) : 0.0;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Support\DateRange;
|
||||
|
||||
interface BreakdownStat extends Stat
|
||||
{
|
||||
public function for(DateRange $range): BreakdownResult;
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Support\DateRange;
|
||||
|
||||
abstract class DailySeriesStat implements SeriesStat
|
||||
{
|
||||
final public function for(DateRange $range): SeriesResult
|
||||
{
|
||||
if (! $range->isBucketableByDay()) {
|
||||
return SeriesResult::tooWide();
|
||||
}
|
||||
|
||||
return $this->series($range, $range->days());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $days
|
||||
*/
|
||||
abstract protected function series(DateRange $range, array $days): SeriesResult;
|
||||
}
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Models\ArticlePublication;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Support\DateRange;
|
||||
|
||||
class PublicationsPerChannel implements BreakdownStat
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'publications-per-channel';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Publications per Channel';
|
||||
}
|
||||
|
||||
public function for(DateRange $range): BreakdownResult
|
||||
{
|
||||
/** @var array<int, int> $counts */
|
||||
$counts = ArticlePublication::query()
|
||||
->whereBetween('published_at', [$range->from, $range->to])
|
||||
->selectRaw('platform_channel_id, COUNT(*) as aggregate')
|
||||
->groupBy('platform_channel_id')
|
||||
->pluck('aggregate', 'platform_channel_id')
|
||||
->all();
|
||||
|
||||
// Zero-fill in PHP; assumes the channel table stays small enough to load whole.
|
||||
$rows = PlatformChannel::query()
|
||||
->get()
|
||||
->map(fn (PlatformChannel $channel): Breakdown => new Breakdown(
|
||||
$channel->display_name,
|
||||
(int) ($counts[$channel->id] ?? 0),
|
||||
))
|
||||
->all();
|
||||
|
||||
usort(
|
||||
$rows,
|
||||
fn (Breakdown $a, Breakdown $b): int => [$b->count, $a->label] <=> [$a->count, $b->label],
|
||||
);
|
||||
|
||||
return new BreakdownResult($rows);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Enums\PublishStatusEnum;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Support\DateRange;
|
||||
|
||||
class PublishSuccessRate extends DailySeriesStat
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'publish-success-rate';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Publish Success Rate';
|
||||
}
|
||||
|
||||
protected function series(DateRange $range, array $days): SeriesResult
|
||||
{
|
||||
// Buckets follow updated_at, so a retry re-dates its article to the retry day.
|
||||
$attempts = RouteArticle::query()
|
||||
->toBase()
|
||||
->whereBetween('updated_at', [$range->from, $range->to])
|
||||
->whereIn('publish_status', PublishStatusEnum::settledValues())
|
||||
->selectRaw(
|
||||
'DATE(updated_at) as bucket, COUNT(*) as total, SUM(CASE WHEN publish_status = ? THEN 1 ELSE 0 END) as published',
|
||||
[PublishStatusEnum::PUBLISHED->value],
|
||||
)
|
||||
->groupBy('bucket')
|
||||
->get()
|
||||
->keyBy('bucket');
|
||||
|
||||
$values = array_map(
|
||||
function (string $day) use ($attempts): ?float {
|
||||
$attempt = $attempts->get($day);
|
||||
|
||||
if ($attempt === null || (int) $attempt->total === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return round(((int) $attempt->published / (int) $attempt->total) * 100, 1);
|
||||
},
|
||||
$days,
|
||||
);
|
||||
|
||||
return new SeriesResult($days, [
|
||||
new Series('Publish Success Rate', $values, zeroIsMeaningful: true),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
class Series
|
||||
{
|
||||
/**
|
||||
* @param array<int, int|float|null> $values
|
||||
* @param bool $zeroIsMeaningful A rate of 0 is a real measurement; a count of 0 is an absence.
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $name,
|
||||
public readonly array $values,
|
||||
public readonly bool $zeroIsMeaningful = false,
|
||||
) {}
|
||||
|
||||
public function hasData(): bool
|
||||
{
|
||||
foreach ($this->values as $value) {
|
||||
if ($value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->zeroIsMeaningful || $value != 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class SeriesResult
|
||||
{
|
||||
private bool $tooWide = false;
|
||||
|
||||
/**
|
||||
* @param array<int, string> $labels
|
||||
* @param array<int, Series> $series
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $labels,
|
||||
public readonly array $series,
|
||||
) {
|
||||
foreach ($series as $one) {
|
||||
if (count($one->values) !== count($labels)) {
|
||||
throw new InvalidArgumentException(
|
||||
"Series [{$one->name}] has ".count($one->values).' values for '.count($labels).' labels.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function tooWide(): self
|
||||
{
|
||||
$result = new self([], []);
|
||||
$result->tooWide = true;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function isTooWide(): bool
|
||||
{
|
||||
return $this->tooWide;
|
||||
}
|
||||
|
||||
/** True only when no axis was built; a real range always has one label per day. */
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return ! $this->tooWide && $this->labels === [];
|
||||
}
|
||||
|
||||
/** True when no series carries a measurement — an axis exists but nothing happened on it. */
|
||||
public function hasNoData(): bool
|
||||
{
|
||||
foreach ($this->series as $one) {
|
||||
if ($one->hasData()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
use App\Support\DateRange;
|
||||
|
||||
interface SeriesStat extends Stat
|
||||
{
|
||||
public function for(DateRange $range): SeriesResult;
|
||||
}
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard\Stats;
|
||||
|
||||
interface Stat
|
||||
{
|
||||
/**
|
||||
* Stable identifier. Island names in dashboard.blade.php are written to match by hand, not derived from this.
|
||||
*/
|
||||
public function key(): string;
|
||||
|
||||
public function label(): string;
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
enum AccountStatusEnum: string
|
||||
{
|
||||
case UNTESTED = 'untested';
|
||||
case HEALTHY = 'healthy';
|
||||
case UNHEALTHY = 'unhealthy';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::UNTESTED => 'Untested',
|
||||
self::HEALTHY => 'Healthy',
|
||||
self::UNHEALTHY => 'Unhealthy',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
enum ActivityTypeEnum: string
|
||||
{
|
||||
case FETCH = 'fetch';
|
||||
case VALIDATE = 'validate';
|
||||
case APPROVE = 'approve';
|
||||
case REJECT = 'reject';
|
||||
case PUBLISH = 'publish';
|
||||
case ERROR = 'error';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::FETCH => 'Fetched',
|
||||
self::VALIDATE => 'Validated',
|
||||
self::APPROVE => 'Approved',
|
||||
self::REJECT => 'Rejected',
|
||||
self::PUBLISH => 'Published',
|
||||
self::ERROR => 'Error',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function options(): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (self::cases() as $case) {
|
||||
$options[$case->value] = $case->label();
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,20 +7,4 @@ enum ApprovalStatusEnum: string
|
|||
case PENDING = 'pending';
|
||||
case APPROVED = 'approved';
|
||||
case REJECTED = 'rejected';
|
||||
|
||||
public function isDecided(): bool
|
||||
{
|
||||
return $this !== self::PENDING;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function decidedValues(): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (self $status): string => $status->value,
|
||||
array_filter(self::cases(), fn (self $status): bool => $status->isDecided()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,36 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
enum FeedColorEnum: string
|
||||
{
|
||||
case SLATE = 'slate';
|
||||
case AMBER = 'amber';
|
||||
case SKY = 'sky';
|
||||
case VIOLET = 'violet';
|
||||
case TEAL = 'teal';
|
||||
case ROSE = 'rose';
|
||||
case INDIGO = 'indigo';
|
||||
case ORANGE = 'orange';
|
||||
|
||||
public function dotClass(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::SLATE => 'bg-slate-500',
|
||||
self::AMBER => 'bg-amber-500',
|
||||
self::SKY => 'bg-sky-500',
|
||||
self::VIOLET => 'bg-violet-500',
|
||||
self::TEAL => 'bg-teal-500',
|
||||
self::ROSE => 'bg-rose-500',
|
||||
self::INDIGO => 'bg-indigo-500',
|
||||
self::ORANGE => 'bg-orange-500',
|
||||
};
|
||||
}
|
||||
|
||||
public static function forId(int $id): self
|
||||
{
|
||||
$cases = self::cases();
|
||||
|
||||
return $cases[$id % count($cases)];
|
||||
}
|
||||
}
|
||||
|
|
@ -6,7 +6,6 @@ enum NotificationTypeEnum: string
|
|||
{
|
||||
case GENERAL = 'general';
|
||||
case FEED_STALE = 'feed_stale';
|
||||
case FEED_EMPTY = 'feed_empty';
|
||||
case PUBLISH_FAILED = 'publish_failed';
|
||||
case CREDENTIAL_EXPIRED = 'credential_expired';
|
||||
|
||||
|
|
@ -15,7 +14,6 @@ public function label(): string
|
|||
return match ($this) {
|
||||
self::GENERAL => 'General',
|
||||
self::FEED_STALE => 'Feed Stale',
|
||||
self::FEED_EMPTY => 'Feed Empty',
|
||||
self::PUBLISH_FAILED => 'Publish Failed',
|
||||
self::CREDENTIAL_EXPIRED => 'Credential Expired',
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,23 +7,5 @@ enum PublishStatusEnum: string
|
|||
case UNPUBLISHED = 'unpublished';
|
||||
case PUBLISHING = 'publishing';
|
||||
case PUBLISHED = 'published';
|
||||
case SKIPPED = 'skipped';
|
||||
case ERROR = 'error';
|
||||
|
||||
/** Skipped articles were never attempted, so they are not a publish outcome. */
|
||||
public function isSettled(): bool
|
||||
{
|
||||
return $this === self::PUBLISHED || $this === self::ERROR;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function settledValues(): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (self $status): string => $status->value,
|
||||
array_filter(self::cases(), fn (self $status): bool => $status->isSettled()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,20 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Events;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
|
||||
class ActivityLogged
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public ActivityTypeEnum $type,
|
||||
public string $message,
|
||||
/** @var array<string, mixed> */
|
||||
public array $context = [],
|
||||
public ?Model $subject = null,
|
||||
) {}
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Events;
|
||||
|
||||
use Illuminate\Broadcasting\InteractsWithSockets;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class RouteActivated
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public int $feedId,
|
||||
public int $platformChannelId,
|
||||
) {}
|
||||
}
|
||||
|
|
@ -2,11 +2,10 @@
|
|||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Services\DashboardStatsService;
|
||||
use App\Support\DateRange;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class DashboardController extends BaseController
|
||||
{
|
||||
|
|
@ -19,26 +18,23 @@ public function __construct(
|
|||
*/
|
||||
public function stats(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'from' => ['nullable', 'date', 'required_with:to'],
|
||||
'to' => ['nullable', 'date', 'after_or_equal:from', 'required_with:from'],
|
||||
]);
|
||||
|
||||
$range = isset($validated['from'], $validated['to'])
|
||||
? new DateRange(
|
||||
Carbon::parse($validated['from'])->startOfDay(),
|
||||
Carbon::parse($validated['to'])->endOfDay(),
|
||||
)
|
||||
: DateRange::preset('today');
|
||||
$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' => $this->dashboardStatsService->getStats($range),
|
||||
'system_stats' => $this->dashboardStatsService->getSystemStats(),
|
||||
'range' => [
|
||||
'from' => $range->from->toDateString(),
|
||||
'to' => $range->to->toDateString(),
|
||||
],
|
||||
'article_stats' => $articleStats,
|
||||
'system_stats' => $systemStats,
|
||||
'available_periods' => $availablePeriods,
|
||||
'current_period' => $period,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return $this->sendError('Failed to fetch dashboard stats: '.$e->getMessage(), [], 500);
|
||||
|
|
|
|||
|
|
@ -7,8 +7,6 @@
|
|||
use App\Http\Resources\PlatformChannelResource;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Services\Platform\CommunityDirectory;
|
||||
use Exception;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
|
@ -42,12 +40,8 @@ public function store(StorePlatformChannelRequest $request, CreateChannelAction
|
|||
try {
|
||||
$validated = $request->validated();
|
||||
|
||||
$instance = PlatformInstance::query()->findOrFail((int) $validated['platform_instance_id']);
|
||||
$name = app(CommunityDirectory::class)->name($instance, (int) $validated['channel_id']);
|
||||
|
||||
$channel = $createChannelAction->execute(
|
||||
$name,
|
||||
(int) $validated['channel_id'],
|
||||
$validated['name'],
|
||||
$validated['platform_instance_id'],
|
||||
$validated['language_id'] ?? null,
|
||||
$validated['description'] ?? null,
|
||||
|
|
|
|||
|
|
@ -71,10 +71,7 @@ public function reject(RouteArticle $routeArticle): JsonResponse
|
|||
public function restore(RouteArticle $routeArticle): JsonResponse
|
||||
{
|
||||
try {
|
||||
$routeArticle->update([
|
||||
'approval_status' => ApprovalStatusEnum::PENDING,
|
||||
'decided_at' => null,
|
||||
]);
|
||||
$routeArticle->update(['approval_status' => ApprovalStatusEnum::PENDING]);
|
||||
|
||||
return $this->sendResponse(
|
||||
new RouteArticleResource($routeArticle->fresh(['article.feed', 'feed', 'platformChannel'])),
|
||||
|
|
@ -91,10 +88,7 @@ public function clear(): JsonResponse
|
|||
$count = RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)->count();
|
||||
|
||||
RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)
|
||||
->update([
|
||||
'approval_status' => ApprovalStatusEnum::REJECTED,
|
||||
'decided_at' => now(),
|
||||
]);
|
||||
->update(['approval_status' => ApprovalStatusEnum::REJECTED]);
|
||||
|
||||
return $this->sendResponse(
|
||||
['rejected_count' => $count],
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@ public function index(): JsonResponse
|
|||
'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
|
||||
'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
|
||||
'article_publishing_interval' => Setting::getArticlePublishingInterval(),
|
||||
'daily_publish_cap' => Setting::getDailyPublishCap(),
|
||||
];
|
||||
|
||||
return $this->sendResponse($settings, 'Settings retrieved successfully.');
|
||||
|
|
@ -38,7 +37,6 @@ public function update(Request $request): JsonResponse
|
|||
'article_processing_enabled' => 'boolean',
|
||||
'publishing_approvals_enabled' => 'boolean',
|
||||
'article_publishing_interval' => 'integer|min:0',
|
||||
'daily_publish_cap' => 'integer|min:0',
|
||||
]);
|
||||
|
||||
if (isset($validated['article_processing_enabled'])) {
|
||||
|
|
@ -53,15 +51,10 @@ public function update(Request $request): JsonResponse
|
|||
Setting::setArticlePublishingInterval($validated['article_publishing_interval']);
|
||||
}
|
||||
|
||||
if (isset($validated['daily_publish_cap'])) {
|
||||
Setting::setDailyPublishCap($validated['daily_publish_cap']);
|
||||
}
|
||||
|
||||
$updatedSettings = [
|
||||
'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
|
||||
'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
|
||||
'article_publishing_interval' => Setting::getArticlePublishingInterval(),
|
||||
'daily_publish_cap' => Setting::getDailyPublishCap(),
|
||||
];
|
||||
|
||||
return $this->sendResponse(
|
||||
|
|
|
|||
42
app/Http/Middleware/HandleInertiaRequests.php
Normal file
42
app/Http/Middleware/HandleInertiaRequests.php
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
<?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), [
|
||||
//
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,9 +2,6 @@
|
|||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Services\Platform\CommunityDirectory;
|
||||
use Exception;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
|
|
@ -20,22 +17,19 @@ public function authorize(): bool
|
|||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
try {
|
||||
$communityRules = [
|
||||
Rule::in($this->communityIds()),
|
||||
Rule::unique('platform_channels', 'channel_id')
|
||||
->where('platform_instance_id', $this->input('platform_instance_id')),
|
||||
];
|
||||
} catch (Exception $e) {
|
||||
// Falling through to Rule::in([]) would report the community as non-existent
|
||||
// when the truth is we never reached the instance to check.
|
||||
$message = 'Could not reach this instance to list its communities: '.$e->getMessage();
|
||||
$communityRules = [fn ($attribute, $value, $fail) => $fail($message)];
|
||||
}
|
||||
|
||||
return [
|
||||
'platform_instance_id' => 'required|exists:platform_instances,id',
|
||||
'channel_id' => ['required', 'integer', ...$communityRules],
|
||||
// name doubles as the Lemmy community slug (CreateChannelAction copies it
|
||||
// verbatim into channel_id for community lookup at publish time), so it must
|
||||
// be slug format and unique per instance — matching the Livewire create form.
|
||||
'name' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
'regex:/^[a-z0-9_]+$/',
|
||||
Rule::unique('platform_channels', 'name')
|
||||
->where('platform_instance_id', $this->input('platform_instance_id')),
|
||||
],
|
||||
'language_id' => 'nullable|exists:languages,id',
|
||||
'description' => 'nullable|string',
|
||||
];
|
||||
|
|
@ -47,24 +41,8 @@ public function rules(): array
|
|||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'channel_id.in' => 'That community does not exist on the selected instance.',
|
||||
'channel_id.unique' => 'A channel for this community already exists.',
|
||||
'name.regex' => 'The name must be a valid community slug (lowercase letters, numbers, and underscores only).',
|
||||
'name.unique' => 'A channel with this name already exists for this instance.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function communityIds(): array
|
||||
{
|
||||
$instance = PlatformInstance::query()->find((int) $this->input('platform_instance_id'));
|
||||
|
||||
if (! $instance) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect(app(CommunityDirectory::class)->forInstance($instance))
|
||||
->pluck('id')
|
||||
->all();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,15 +2,9 @@
|
|||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Actions\FetchFeedArticlesAction;
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Enums\NotificationSeverityEnum;
|
||||
use App\Enums\NotificationTypeEnum;
|
||||
use App\Events\ActivityLogged;
|
||||
use App\Models\Feed;
|
||||
use App\Models\Notification;
|
||||
use App\Services\Article\ArticleFetcher;
|
||||
use App\Services\Log\LogSaver;
|
||||
use App\Services\Notification\NotificationService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
|
|
@ -26,7 +20,7 @@ public function __construct(
|
|||
$this->onQueue('feed-discovery');
|
||||
}
|
||||
|
||||
public function handle(LogSaver $logSaver, FetchFeedArticlesAction $fetchFeedArticles, NotificationService $notificationService): void
|
||||
public function handle(LogSaver $logSaver, ArticleFetcher $articleFetcher): void
|
||||
{
|
||||
$logSaver->info('Starting feed article fetch', null, [
|
||||
'feed_id' => $this->feed->id,
|
||||
|
|
@ -34,7 +28,7 @@ public function handle(LogSaver $logSaver, FetchFeedArticlesAction $fetchFeedArt
|
|||
'feed_url' => $this->feed->url,
|
||||
]);
|
||||
|
||||
$articles = $fetchFeedArticles->execute($this->feed);
|
||||
$articles = $articleFetcher->getArticlesFromFeed($this->feed);
|
||||
|
||||
$logSaver->info('Feed article fetch completed', null, [
|
||||
'feed_id' => $this->feed->id,
|
||||
|
|
@ -43,48 +37,6 @@ public function handle(LogSaver $logSaver, FetchFeedArticlesAction $fetchFeedArt
|
|||
]);
|
||||
|
||||
$this->feed->update(['last_fetched_at' => now()]);
|
||||
|
||||
if ($articles->isEmpty()) {
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::ERROR,
|
||||
"{$this->feed->name} returned no articles",
|
||||
['articles_count' => 0],
|
||||
$this->feed,
|
||||
);
|
||||
|
||||
$this->warnFeedReturnedNothing($notificationService);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::FETCH,
|
||||
"Fetched {$articles->count()} articles from {$this->feed->name}",
|
||||
['articles_count' => $articles->count()],
|
||||
$this->feed,
|
||||
);
|
||||
}
|
||||
|
||||
private function warnFeedReturnedNothing(NotificationService $notificationService): void
|
||||
{
|
||||
$alreadyNotified = Notification::query()
|
||||
->where('type', NotificationTypeEnum::FEED_EMPTY)
|
||||
->where('notifiable_type', $this->feed->getMorphClass())
|
||||
->where('notifiable_id', $this->feed->getKey())
|
||||
->unread()
|
||||
->exists();
|
||||
|
||||
if ($alreadyNotified) {
|
||||
return;
|
||||
}
|
||||
|
||||
$notificationService->send(
|
||||
type: NotificationTypeEnum::FEED_EMPTY,
|
||||
severity: NotificationSeverityEnum::WARNING,
|
||||
title: "Feed \"{$this->feed->name}\" returned no articles",
|
||||
message: "The fetch completed but produced nothing. Check that {$this->feed->url} is still a valid feed.",
|
||||
notifiable: $this->feed,
|
||||
);
|
||||
}
|
||||
|
||||
public static function dispatchForAllActiveFeeds(): void
|
||||
|
|
|
|||
|
|
@ -1,79 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Enums\NotificationSeverityEnum;
|
||||
use App\Enums\NotificationTypeEnum;
|
||||
use App\Models\Notification;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Modules\Lemmy\Services\LemmyApiService;
|
||||
use App\Services\Notification\NotificationService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Throwable;
|
||||
|
||||
class CheckPlatformCredentialsJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public function handle(NotificationService $notificationService): void
|
||||
{
|
||||
$accounts = PlatformAccount::where('is_active', true)->get();
|
||||
|
||||
foreach ($accounts as $account) {
|
||||
$this->check($account, $notificationService);
|
||||
}
|
||||
}
|
||||
|
||||
private function check(PlatformAccount $account, NotificationService $notificationService): void
|
||||
{
|
||||
if ($this->canLogIn($account)) {
|
||||
$account->recordCredentialCheckPassed();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$wasUnhealthy = $account->isUnhealthy();
|
||||
$account->recordCredentialCheckFailed();
|
||||
|
||||
if (! $wasUnhealthy && $account->refresh()->isUnhealthy()) {
|
||||
$this->notify($account, $notificationService);
|
||||
}
|
||||
}
|
||||
|
||||
private function canLogIn(PlatformAccount $account): bool
|
||||
{
|
||||
try {
|
||||
return $this->makeApiService($account)->login($account->username, $account->password) !== null;
|
||||
} catch (Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected function makeApiService(PlatformAccount $account): LemmyApiService
|
||||
{
|
||||
return new LemmyApiService($account->instance_url);
|
||||
}
|
||||
|
||||
private function notify(PlatformAccount $account, NotificationService $notificationService): void
|
||||
{
|
||||
$alreadyNotified = Notification::query()
|
||||
->where('type', NotificationTypeEnum::CREDENTIAL_EXPIRED)
|
||||
->where('notifiable_type', $account->getMorphClass())
|
||||
->where('notifiable_id', $account->getKey())
|
||||
->unread()
|
||||
->exists();
|
||||
|
||||
if ($alreadyNotified) {
|
||||
return;
|
||||
}
|
||||
|
||||
$notificationService->send(
|
||||
type: NotificationTypeEnum::CREDENTIAL_EXPIRED,
|
||||
severity: NotificationSeverityEnum::ERROR,
|
||||
title: "Credentials failed for {$account->username}",
|
||||
message: "Could not log in to {$account->instance_url} after ".PlatformAccount::FAILURES_BEFORE_UNHEALTHY.' attempts. Publishing to this account will fail until it is fixed.',
|
||||
notifiable: $account,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\ActivityLog;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
class CleanupActivityLogsJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
private const RETENTION_DAYS = 90;
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
ActivityLog::where('logged_at', '<', now()->subDays(self::RETENTION_DAYS))->delete();
|
||||
}
|
||||
}
|
||||
|
|
@ -2,14 +2,19 @@
|
|||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Actions\PublishRouteArticleAction;
|
||||
use App\Enums\ApprovalStatusEnum;
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\Enums\NotificationSeverityEnum;
|
||||
use App\Enums\NotificationTypeEnum;
|
||||
use App\Enums\PublishStatusEnum;
|
||||
use App\Events\ActionPerformed;
|
||||
use App\Exceptions\PublishException;
|
||||
use App\Models\ArticlePublication;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Models\Setting;
|
||||
use App\Services\Article\ArticleFetcher;
|
||||
use App\Services\Notification\NotificationService;
|
||||
use App\Services\Publishing\ArticlePublishingService;
|
||||
use Illuminate\Contracts\Queue\ShouldBeUnique;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
|
@ -33,12 +38,8 @@ public function __construct()
|
|||
*
|
||||
* @throws PublishException
|
||||
*/
|
||||
public function handle(PublishRouteArticleAction $publishRouteArticle): void
|
||||
public function handle(ArticleFetcher $articleFetcher, ArticlePublishingService $publishingService, NotificationService $notificationService): void
|
||||
{
|
||||
if ($this->dailyCapReached()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$interval = Setting::getArticlePublishingInterval();
|
||||
|
||||
if ($interval > 0) {
|
||||
|
|
@ -51,7 +52,6 @@ public function handle(PublishRouteArticleAction $publishRouteArticle): void
|
|||
|
||||
// Get the oldest approved route_article that hasn't been published to its channel yet
|
||||
$routeArticle = RouteArticle::where('approval_status', ApprovalStatusEnum::APPROVED)
|
||||
->dueForPublishing()
|
||||
->whereDoesntHave('article.articlePublications', function ($query) {
|
||||
$query->whereColumn('article_publications.platform_channel_id', 'route_articles.platform_channel_id');
|
||||
})
|
||||
|
|
@ -72,17 +72,52 @@ public function handle(PublishRouteArticleAction $publishRouteArticle): void
|
|||
'route' => $routeArticle->feed_id.'-'.$routeArticle->platform_channel_id,
|
||||
]);
|
||||
|
||||
$publishRouteArticle->execute($routeArticle);
|
||||
}
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHING]);
|
||||
|
||||
private function dailyCapReached(): bool
|
||||
{
|
||||
$cap = Setting::getDailyPublishCap();
|
||||
try {
|
||||
$extractedData = $articleFetcher->fetchArticleData($article);
|
||||
$publication = $publishingService->publishRouteArticle($routeArticle, $extractedData);
|
||||
|
||||
if ($cap <= 0) {
|
||||
return false;
|
||||
}
|
||||
if ($publication) {
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHED]);
|
||||
|
||||
return ArticlePublication::where('published_at', '>=', now()->startOfDay())->count() >= $cap;
|
||||
ActionPerformed::dispatch('Successfully published article', LogLevelEnum::INFO, [
|
||||
'article_id' => $article->id,
|
||||
'title' => $article->title,
|
||||
]);
|
||||
} else {
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::ERROR]);
|
||||
|
||||
ActionPerformed::dispatch('No publication created for article', LogLevelEnum::WARNING, [
|
||||
'article_id' => $article->id,
|
||||
'title' => $article->title,
|
||||
]);
|
||||
|
||||
$notificationService->send(
|
||||
NotificationTypeEnum::PUBLISH_FAILED,
|
||||
NotificationSeverityEnum::WARNING,
|
||||
"Publish failed: {$article->title}",
|
||||
'No publication was created for this article. Check channel routing configuration.',
|
||||
$article,
|
||||
);
|
||||
}
|
||||
} catch (PublishException $e) {
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::ERROR]);
|
||||
|
||||
ActionPerformed::dispatch('Failed to publish article', LogLevelEnum::ERROR, [
|
||||
'article_id' => $article->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
$notificationService->send(
|
||||
NotificationTypeEnum::PUBLISH_FAILED,
|
||||
NotificationSeverityEnum::ERROR,
|
||||
"Publish failed: {$article->title}",
|
||||
$e->getMessage(),
|
||||
$article,
|
||||
);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -68,7 +68,9 @@ private function syncLemmyChannelPosts(LogSaver $logSaver): void
|
|||
$api = $this->makeApiService($this->channel->platformInstance->url);
|
||||
$token = $this->getAuthToken($api, $account);
|
||||
|
||||
$api->syncChannelPosts($token, $this->channel, $this->channel->channel_id);
|
||||
$communityId = $api->resolveCommunityId($this->channel->channel_id, $token);
|
||||
|
||||
$api->syncChannelPosts($token, $communityId, $this->channel->name);
|
||||
|
||||
$logSaver->info('Channel posts synced successfully', $this->channel);
|
||||
} catch (Exception $e) {
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Actions\BackfillRouteArticlesAction;
|
||||
use App\Events\RouteActivated;
|
||||
use App\Models\Route;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
|
||||
class BackfillRouteArticlesListener implements ShouldQueue
|
||||
{
|
||||
public string $queue = 'default';
|
||||
|
||||
public function __construct(
|
||||
private BackfillRouteArticlesAction $backfillRouteArticles,
|
||||
) {}
|
||||
|
||||
public function handle(RouteActivated $event): void
|
||||
{
|
||||
$route = Route::query()
|
||||
->where('feed_id', $event->feedId)
|
||||
->where('platform_channel_id', $event->platformChannelId)
|
||||
->first();
|
||||
|
||||
if ($route === null || ! $route->is_active) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->backfillRouteArticles->execute($route);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,8 +2,15 @@
|
|||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Actions\PublishRouteArticleAction;
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\Enums\NotificationSeverityEnum;
|
||||
use App\Enums\NotificationTypeEnum;
|
||||
use App\Enums\PublishStatusEnum;
|
||||
use App\Events\ActionPerformed;
|
||||
use App\Events\RouteArticleApproved;
|
||||
use App\Services\Article\ArticleFetcher;
|
||||
use App\Services\Notification\NotificationService;
|
||||
use App\Services\Publishing\ArticlePublishingService;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
|
||||
|
|
@ -12,7 +19,9 @@ class PublishApprovedArticleListener implements ShouldQueue
|
|||
public string $queue = 'publishing';
|
||||
|
||||
public function __construct(
|
||||
private PublishRouteArticleAction $publishRouteArticle,
|
||||
private ArticleFetcher $articleFetcher,
|
||||
private ArticlePublishingService $publishingService,
|
||||
private NotificationService $notificationService,
|
||||
) {}
|
||||
|
||||
public function handle(RouteArticleApproved $event): void
|
||||
|
|
@ -20,6 +29,7 @@ public function handle(RouteArticleApproved $event): void
|
|||
$routeArticle = $event->routeArticle;
|
||||
$article = $routeArticle->article;
|
||||
|
||||
// Skip if already published to this channel
|
||||
if ($article->articlePublications()
|
||||
->where('platform_channel_id', $routeArticle->platform_channel_id)
|
||||
->exists()
|
||||
|
|
@ -27,10 +37,50 @@ public function handle(RouteArticleApproved $event): void
|
|||
return;
|
||||
}
|
||||
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHING]);
|
||||
|
||||
try {
|
||||
$this->publishRouteArticle->execute($routeArticle);
|
||||
} catch (Exception) {
|
||||
// The action has already recorded the failure and notified.
|
||||
$extractedData = $this->articleFetcher->fetchArticleData($article);
|
||||
$publication = $this->publishingService->publishRouteArticle($routeArticle, $extractedData);
|
||||
|
||||
if ($publication) {
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHED]);
|
||||
|
||||
ActionPerformed::dispatch('Published approved article', LogLevelEnum::INFO, [
|
||||
'article_id' => $article->id,
|
||||
'title' => $article->title,
|
||||
]);
|
||||
} else {
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::ERROR]);
|
||||
|
||||
ActionPerformed::dispatch('No publication created for approved article', LogLevelEnum::WARNING, [
|
||||
'article_id' => $article->id,
|
||||
'title' => $article->title,
|
||||
]);
|
||||
|
||||
$this->notificationService->send(
|
||||
NotificationTypeEnum::PUBLISH_FAILED,
|
||||
NotificationSeverityEnum::WARNING,
|
||||
"Publish failed: {$article->title}",
|
||||
'No publication was created for this article. Check channel routing configuration.',
|
||||
$article,
|
||||
);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
$routeArticle->update(['publish_status' => PublishStatusEnum::ERROR]);
|
||||
|
||||
ActionPerformed::dispatch('Failed to publish approved article', LogLevelEnum::ERROR, [
|
||||
'article_id' => $article->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
$this->notificationService->send(
|
||||
NotificationTypeEnum::PUBLISH_FAILED,
|
||||
NotificationSeverityEnum::ERROR,
|
||||
"Publish failed: {$article->title}",
|
||||
$e->getMessage(),
|
||||
$article,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,29 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Events\ActivityLogged;
|
||||
use App\Models\ActivityLog;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
class RecordActivityListener
|
||||
{
|
||||
private const MESSAGE_LIMIT = 255;
|
||||
|
||||
public function handle(ActivityLogged $event): void
|
||||
{
|
||||
try {
|
||||
ActivityLog::create([
|
||||
'type' => $event->type,
|
||||
'message' => Str::limit($event->message, self::MESSAGE_LIMIT, ''),
|
||||
'context' => $event->context === [] ? null : $event->context,
|
||||
'subject_type' => $event->subject?->getMorphClass(),
|
||||
'subject_id' => $event->subject?->getKey(),
|
||||
'logged_at' => now(),
|
||||
]);
|
||||
} catch (Throwable $e) {
|
||||
error_log('Failed to record activity: '.$e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2,12 +2,10 @@
|
|||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Actions\ValidateArticleAction;
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\Events\ActionPerformed;
|
||||
use App\Events\ActivityLogged;
|
||||
use App\Events\NewArticleFetched;
|
||||
use App\Services\Article\ValidationService;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
|
||||
|
|
@ -16,7 +14,7 @@ class ValidateArticleListener implements ShouldQueue
|
|||
public string $queue = 'default';
|
||||
|
||||
public function __construct(
|
||||
private ValidateArticleAction $validateArticle
|
||||
private ValidationService $validationService
|
||||
) {}
|
||||
|
||||
public function handle(NewArticleFetched $event): void
|
||||
|
|
@ -33,26 +31,12 @@ public function handle(NewArticleFetched $event): void
|
|||
}
|
||||
|
||||
try {
|
||||
$this->validateArticle->execute($article);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::VALIDATE,
|
||||
"Validated \"{$article->title}\"",
|
||||
[],
|
||||
$article,
|
||||
);
|
||||
$this->validationService->validate($article);
|
||||
} catch (Exception $e) {
|
||||
ActionPerformed::dispatch('Article validation failed', LogLevelEnum::ERROR, [
|
||||
'article_id' => $article->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::ERROR,
|
||||
"Validation failed for \"{$article->title}\"",
|
||||
['error' => $e->getMessage()],
|
||||
$article,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,55 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Services\Activity\ActivitySummary;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Livewire\Component;
|
||||
use Livewire\WithPagination;
|
||||
|
||||
class Activity extends Component
|
||||
{
|
||||
use WithPagination;
|
||||
|
||||
public string $type = '';
|
||||
|
||||
public int $days = 7;
|
||||
|
||||
public function updatedType(): void
|
||||
{
|
||||
$this->resetPage();
|
||||
}
|
||||
|
||||
public function updatedDays(): void
|
||||
{
|
||||
$this->resetPage();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder<ActivityLog>
|
||||
*/
|
||||
private function query(): Builder
|
||||
{
|
||||
return ActivityLog::query()
|
||||
->withSubjectDetails()
|
||||
->since(now()->subDays($this->days))
|
||||
->when(
|
||||
$this->type !== '',
|
||||
fn (Builder $q) => $q->where('type', $this->type),
|
||||
)
|
||||
->latestFirst();
|
||||
}
|
||||
|
||||
public function render(ActivitySummary $summary): View
|
||||
{
|
||||
return view('livewire.activity', [
|
||||
'entries' => $this->query()->paginate(25),
|
||||
'typeOptions' => ActivityTypeEnum::options(),
|
||||
'summaryDay' => $summary->since(now()->subDay()),
|
||||
'summaryWeek' => $summary->since(now()->subWeek()),
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -2,17 +2,10 @@
|
|||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Enums\ApprovalStatusEnum;
|
||||
use App\Events\ActivityLogged;
|
||||
use App\Jobs\ArticleDiscoveryJob;
|
||||
use App\Models\Feed;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Support\PendingFeedGroup;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Support\Collection;
|
||||
use Livewire\Component;
|
||||
use Livewire\WithPagination;
|
||||
|
||||
|
|
@ -24,38 +17,15 @@ class Articles extends Component
|
|||
|
||||
public string $search = '';
|
||||
|
||||
public ?int $feedId = null;
|
||||
|
||||
public bool $isRefreshing = false;
|
||||
|
||||
/** @var array<int, bool> */
|
||||
public array $expandedFeeds = [];
|
||||
|
||||
public function setTab(string $tab): void
|
||||
{
|
||||
$this->tab = $tab;
|
||||
$this->search = '';
|
||||
$this->expandedFeeds = [];
|
||||
$this->resetPage();
|
||||
}
|
||||
|
||||
public function updatedFeedId(): void
|
||||
{
|
||||
$this->expandedFeeds = [];
|
||||
$this->resetPage();
|
||||
}
|
||||
|
||||
public function toggleFeed(int $feedId): void
|
||||
{
|
||||
if (isset($this->expandedFeeds[$feedId])) {
|
||||
unset($this->expandedFeeds[$feedId]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->expandedFeeds[$feedId] = true;
|
||||
}
|
||||
|
||||
public function updatedSearch(): void
|
||||
{
|
||||
$this->resetPage();
|
||||
|
|
@ -74,42 +44,13 @@ public function reject(int $routeArticleId): void
|
|||
public function restore(int $routeArticleId): void
|
||||
{
|
||||
$routeArticle = RouteArticle::findOrFail($routeArticleId);
|
||||
$routeArticle->update([
|
||||
'approval_status' => ApprovalStatusEnum::PENDING,
|
||||
'decided_at' => null,
|
||||
]);
|
||||
$routeArticle->update(['approval_status' => ApprovalStatusEnum::PENDING]);
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
$feed = $this->feedId !== null ? Feed::find($this->feedId) : null;
|
||||
$cleared = $this->clearableQuery()->update([
|
||||
'approval_status' => ApprovalStatusEnum::REJECTED,
|
||||
'decided_at' => now(),
|
||||
]);
|
||||
|
||||
if ($cleared > 0) {
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::REJECT,
|
||||
$feed !== null
|
||||
? "Cleared {$cleared} pending articles from {$feed->name}"
|
||||
: "Cleared {$cleared} pending articles",
|
||||
['cleared' => $cleared],
|
||||
$feed,
|
||||
);
|
||||
}
|
||||
|
||||
$this->expandedFeeds = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder<RouteArticle>
|
||||
*/
|
||||
private function clearableQuery(): Builder
|
||||
{
|
||||
return RouteArticle::query()
|
||||
->where('approval_status', ApprovalStatusEnum::PENDING)
|
||||
->when($this->feedId !== null, fn (Builder $q) => $q->where('feed_id', $this->feedId));
|
||||
RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)
|
||||
->update(['approval_status' => ApprovalStatusEnum::REJECTED]);
|
||||
}
|
||||
|
||||
public function refresh(): void
|
||||
|
|
@ -121,52 +62,14 @@ public function refresh(): void
|
|||
$this->dispatch('refresh-started');
|
||||
}
|
||||
|
||||
public function retryPublish(int $routeArticleId): void
|
||||
{
|
||||
$routeArticle = RouteArticle::failed()->find($routeArticleId);
|
||||
|
||||
if (! $routeArticle instanceof RouteArticle) {
|
||||
return;
|
||||
}
|
||||
|
||||
$routeArticle->clearPublishFailure();
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::PUBLISH,
|
||||
"Queued \"{$routeArticle->article->title}\" for another publish attempt",
|
||||
['route_article_id' => $routeArticle->id],
|
||||
$routeArticle->article,
|
||||
);
|
||||
}
|
||||
|
||||
public function render(): View
|
||||
{
|
||||
$pendingCount = RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)->count();
|
||||
$failedCount = RouteArticle::failed()->count();
|
||||
|
||||
if ($this->tab === 'pending') {
|
||||
return view('livewire.articles', [
|
||||
'routeArticles' => null,
|
||||
'pendingFeeds' => $this->pendingFeeds(),
|
||||
'feedOptions' => $this->feedOptions(),
|
||||
'pendingCount' => $pendingCount,
|
||||
'failedCount' => $failedCount,
|
||||
'clearableCount' => $this->clearableQuery()->count(),
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
|
||||
$query = RouteArticle::with(['article.feed', 'feed', 'platformChannel'])
|
||||
->orderBy('created_at', 'desc');
|
||||
|
||||
if ($this->tab === 'failed') {
|
||||
$query->failed();
|
||||
}
|
||||
|
||||
if ($this->feedId !== null) {
|
||||
$query->where('feed_id', $this->feedId);
|
||||
}
|
||||
|
||||
if ($this->search !== '') {
|
||||
if ($this->tab === 'pending') {
|
||||
$query->where('approval_status', ApprovalStatusEnum::PENDING);
|
||||
} elseif ($this->search !== '') {
|
||||
$search = $this->search;
|
||||
$query->whereHas('article', function ($q) use ($search) {
|
||||
$q->where('title', 'like', "%{$search}%")
|
||||
|
|
@ -174,59 +77,13 @@ public function render(): View
|
|||
});
|
||||
}
|
||||
|
||||
$routeArticles = $query->paginate(15);
|
||||
|
||||
$pendingCount = RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)->count();
|
||||
|
||||
return view('livewire.articles', [
|
||||
'routeArticles' => $query->paginate(15),
|
||||
'pendingFeeds' => null,
|
||||
'feedOptions' => $this->feedOptions(),
|
||||
'routeArticles' => $routeArticles,
|
||||
'pendingCount' => $pendingCount,
|
||||
'failedCount' => $failedCount,
|
||||
'clearableCount' => 0,
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, PendingFeedGroup>
|
||||
*/
|
||||
private function pendingFeeds(): Collection
|
||||
{
|
||||
$counts = RouteArticle::query()
|
||||
->selectRaw('feed_id, COUNT(*) as aggregate')
|
||||
->where('approval_status', ApprovalStatusEnum::PENDING)
|
||||
->when($this->feedId !== null, fn ($q) => $q->where('feed_id', $this->feedId))
|
||||
->groupBy('feed_id')
|
||||
->pluck('aggregate', 'feed_id');
|
||||
|
||||
return Feed::whereIn('id', $counts->keys())->get()
|
||||
->map(fn (Feed $feed): PendingFeedGroup => new PendingFeedGroup(
|
||||
$feed,
|
||||
(int) $counts->get($feed->id, 0),
|
||||
isset($this->expandedFeeds[$feed->id])
|
||||
? $this->routeArticlesForFeed($feed->id)
|
||||
: null,
|
||||
))
|
||||
->sortByDesc('count')
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return EloquentCollection<int, Feed>
|
||||
*/
|
||||
private function feedOptions(): EloquentCollection
|
||||
{
|
||||
return Feed::whereIn('id', RouteArticle::query()->select('feed_id')->distinct())
|
||||
->orderBy('name')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return EloquentCollection<int, RouteArticle>
|
||||
*/
|
||||
private function routeArticlesForFeed(int $feedId): EloquentCollection
|
||||
{
|
||||
return RouteArticle::with(['article.feed', 'feed', 'platformChannel'])
|
||||
->where('approval_status', ApprovalStatusEnum::PENDING)
|
||||
->where('feed_id', $feedId)
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,16 +3,10 @@
|
|||
namespace App\Livewire;
|
||||
|
||||
use App\Actions\CreateChannelAction;
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\Events\ActionPerformed;
|
||||
use App\Models\ArticlePublication;
|
||||
use App\Models\Language;
|
||||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Services\Platform\CommunityDirectory;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
|
@ -25,27 +19,14 @@ class Channels extends Component
|
|||
|
||||
public bool $showCreateModal = false;
|
||||
|
||||
public ?int $newCommunityId = null;
|
||||
public string $newName = '';
|
||||
|
||||
public ?int $newPlatformInstanceId = null;
|
||||
|
||||
/** @var array<int, array{id: int, name: string, title: string}> */
|
||||
public array $availableCommunities = [];
|
||||
|
||||
public ?string $communityLoadError = null;
|
||||
|
||||
public ?int $newLanguageId = null;
|
||||
|
||||
public string $newDescription = '';
|
||||
|
||||
public ?int $editingChannelId = null;
|
||||
|
||||
public string $editDisplayName = '';
|
||||
|
||||
public ?int $editLanguageId = null;
|
||||
|
||||
public string $editDescription = '';
|
||||
|
||||
public function toggle(int $channelId): void
|
||||
{
|
||||
$channel = PlatformChannel::findOrFail($channelId);
|
||||
|
|
@ -53,74 +34,13 @@ public function toggle(int $channelId): void
|
|||
$channel->save();
|
||||
}
|
||||
|
||||
public function deleteChannel(int $channelId): void
|
||||
{
|
||||
$channel = PlatformChannel::find($channelId);
|
||||
|
||||
if (! $channel instanceof PlatformChannel) {
|
||||
return;
|
||||
}
|
||||
|
||||
$name = $channel->display_name;
|
||||
|
||||
// Routes, keywords, route articles, publications, account links and synced posts
|
||||
// all cascade at the database level.
|
||||
$channel->delete();
|
||||
|
||||
if ($this->managingChannelId === $channelId) {
|
||||
$this->managingChannelId = null;
|
||||
}
|
||||
|
||||
if ($this->editingChannelId === $channelId) {
|
||||
$this->editingChannelId = null;
|
||||
}
|
||||
|
||||
ActionPerformed::dispatch('Deleted platform channel', LogLevelEnum::WARNING, [
|
||||
'platform_channel_id' => $channelId,
|
||||
'display_name' => $name,
|
||||
]);
|
||||
}
|
||||
|
||||
public function openCreateModal(): void
|
||||
{
|
||||
$this->reset(['newCommunityId', 'newPlatformInstanceId', 'newLanguageId', 'newDescription', 'availableCommunities', 'communityLoadError']);
|
||||
$this->reset(['newName', 'newPlatformInstanceId', 'newLanguageId', 'newDescription']);
|
||||
$this->resetErrorBag();
|
||||
$this->showCreateModal = true;
|
||||
}
|
||||
|
||||
public function updatedNewPlatformInstanceId(?int $value): void
|
||||
{
|
||||
$this->reset(['newCommunityId', 'availableCommunities', 'communityLoadError']);
|
||||
|
||||
if (! $value) {
|
||||
return;
|
||||
}
|
||||
|
||||
$instance = PlatformInstance::find($value);
|
||||
|
||||
if (! $instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->availableCommunities = app(CommunityDirectory::class)->forInstance($instance);
|
||||
} catch (Exception $e) {
|
||||
$this->communityLoadError = 'Could not reach this instance to list its communities: '.$e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public function refreshCommunities(): void
|
||||
{
|
||||
$instance = $this->newPlatformInstanceId ? PlatformInstance::find($this->newPlatformInstanceId) : null;
|
||||
|
||||
if (! $instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(CommunityDirectory::class)->forget($instance);
|
||||
$this->updatedNewPlatformInstanceId($this->newPlatformInstanceId);
|
||||
}
|
||||
|
||||
public function closeCreateModal(): void
|
||||
{
|
||||
$this->showCreateModal = false;
|
||||
|
|
@ -129,33 +49,36 @@ public function closeCreateModal(): void
|
|||
public function createChannel(CreateChannelAction $action): void
|
||||
{
|
||||
$this->validate([
|
||||
'newCommunityId' => [
|
||||
// name doubles as the Lemmy community slug (used verbatim as channel_id for
|
||||
// community lookup at publish time), so it must be lowercase slug format.
|
||||
'newName' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::in(collect($this->availableCommunities)->pluck('id')->all()),
|
||||
Rule::unique('platform_channels', 'channel_id')
|
||||
'string',
|
||||
'max:255',
|
||||
'regex:/^[a-z0-9_]+$/',
|
||||
Rule::unique('platform_channels', 'name')
|
||||
->where('platform_instance_id', $this->newPlatformInstanceId),
|
||||
],
|
||||
'newPlatformInstanceId' => 'required|integer|exists:platform_instances,id',
|
||||
'newLanguageId' => 'nullable|integer|exists:languages,id',
|
||||
], [
|
||||
'newCommunityId.in' => 'Select a community from this instance.',
|
||||
'newCommunityId.unique' => 'A channel for this community already exists.',
|
||||
'newName.regex' => 'The name must be a valid community slug (lowercase letters, numbers, and underscores only).',
|
||||
'newName.unique' => 'A channel with this name already exists for this instance.',
|
||||
]);
|
||||
|
||||
$name = collect($this->availableCommunities)->firstWhere('id', $this->newCommunityId)['name'] ?? null;
|
||||
|
||||
try {
|
||||
$action->execute(
|
||||
$name,
|
||||
$this->newCommunityId,
|
||||
$this->newName,
|
||||
$this->newPlatformInstanceId,
|
||||
$this->newLanguageId,
|
||||
// Blade textarea binds an empty string when blank; the action expects null for "no description".
|
||||
$this->newDescription !== '' ? $this->newDescription : null,
|
||||
);
|
||||
} catch (UniqueConstraintViolationException $e) {
|
||||
$this->addError('newCommunityId', 'A channel for this community already exists.');
|
||||
// Unreachable via this form (the unique rule above catches duplicates first),
|
||||
// but the (platform_instance_id, channel_id) index can still fire if channel_id
|
||||
// ever drifts from name. Surface it as a field error instead of a 500.
|
||||
$this->addError('newName', 'A channel with this name already exists for this instance.');
|
||||
|
||||
return;
|
||||
} catch (RuntimeException $e) {
|
||||
|
|
@ -167,45 +90,6 @@ public function createChannel(CreateChannelAction $action): void
|
|||
$this->closeCreateModal();
|
||||
}
|
||||
|
||||
public function openEditModal(int $channelId): void
|
||||
{
|
||||
$channel = PlatformChannel::findOrFail($channelId);
|
||||
|
||||
$this->resetErrorBag();
|
||||
$this->editingChannelId = $channelId;
|
||||
$this->editDisplayName = $channel->display_name;
|
||||
$this->editLanguageId = $channel->language_id;
|
||||
$this->editDescription = $channel->description ?? '';
|
||||
}
|
||||
|
||||
public function closeEditModal(): void
|
||||
{
|
||||
$this->editingChannelId = null;
|
||||
}
|
||||
|
||||
// The community pairing (name, channel_id, platform_instance_id) is deliberately immutable:
|
||||
// it is the channel's remote identity, unique per instance, and re-pointing it would change
|
||||
// the meaning of every route already attached.
|
||||
public function updateChannel(): void
|
||||
{
|
||||
if ($this->editingChannelId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->validate([
|
||||
'editDisplayName' => 'required|string|max:255',
|
||||
'editLanguageId' => 'nullable|integer|exists:languages,id',
|
||||
]);
|
||||
|
||||
PlatformChannel::findOrFail($this->editingChannelId)->update([
|
||||
'display_name' => $this->editDisplayName,
|
||||
'language_id' => $this->editLanguageId,
|
||||
'description' => $this->editDescription !== '' ? $this->editDescription : null,
|
||||
]);
|
||||
|
||||
$this->closeEditModal();
|
||||
}
|
||||
|
||||
public function openAccountModal(int $channelId): void
|
||||
{
|
||||
$this->managingChannelId = $channelId;
|
||||
|
|
@ -240,39 +124,6 @@ public function detachAccount(int $channelId, int $accountId): void
|
|||
$channel->platformAccounts()->detach($accountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Row counts per channel, so the delete confirmation can say what is about to go.
|
||||
*
|
||||
* @return array<int, array{articles: int, publications: int}>
|
||||
*/
|
||||
private function deletionImpact(): array
|
||||
{
|
||||
/** @var array<int, int> $articles */
|
||||
$articles = RouteArticle::query()
|
||||
->selectRaw('platform_channel_id, COUNT(*) as aggregate')
|
||||
->groupBy('platform_channel_id')
|
||||
->pluck('aggregate', 'platform_channel_id')
|
||||
->all();
|
||||
|
||||
/** @var array<int, int> $publications */
|
||||
$publications = ArticlePublication::query()
|
||||
->selectRaw('platform_channel_id, COUNT(*) as aggregate')
|
||||
->groupBy('platform_channel_id')
|
||||
->pluck('aggregate', 'platform_channel_id')
|
||||
->all();
|
||||
|
||||
$impact = [];
|
||||
|
||||
foreach (array_keys($articles + $publications) as $channelId) {
|
||||
$impact[$channelId] = [
|
||||
'articles' => (int) ($articles[$channelId] ?? 0),
|
||||
'publications' => (int) ($publications[$channelId] ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
return $impact;
|
||||
}
|
||||
|
||||
public function render(): View
|
||||
{
|
||||
$channels = PlatformChannel::with(['platformInstance', 'platformAccounts'])->orderBy('name')->get();
|
||||
|
|
@ -289,11 +140,7 @@ public function render(): View
|
|||
return view('livewire.channels', [
|
||||
'channels' => $channels,
|
||||
'managingChannel' => $managingChannel,
|
||||
'editingChannel' => $this->editingChannelId !== null
|
||||
? PlatformChannel::with('platformInstance')->find($this->editingChannelId)
|
||||
: null,
|
||||
'availableAccounts' => $availableAccounts,
|
||||
'deletionImpact' => $this->deletionImpact(),
|
||||
'platformInstances' => PlatformInstance::where('is_active', true)->orderBy('name')->get(),
|
||||
'languages' => Language::where('is_active', true)->orderBy('name')->get(),
|
||||
])->layout('layouts.app');
|
||||
|
|
|
|||
|
|
@ -2,243 +2,36 @@
|
|||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Dashboard\Stats\ApprovalRate;
|
||||
use App\Dashboard\Stats\ArticlesPerFeed;
|
||||
use App\Dashboard\Stats\ArticlesTrend;
|
||||
use App\Dashboard\Stats\BreakdownResult;
|
||||
use App\Dashboard\Stats\BreakdownStat;
|
||||
use App\Dashboard\Stats\PublicationsPerChannel;
|
||||
use App\Dashboard\Stats\PublishSuccessRate;
|
||||
use App\Dashboard\Stats\SeriesResult;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Services\DashboardStatsService;
|
||||
use App\Support\DateRange;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Carbon;
|
||||
use InvalidArgumentException;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Component;
|
||||
|
||||
class Dashboard extends Component
|
||||
{
|
||||
public string $from = '';
|
||||
|
||||
public string $to = '';
|
||||
public string $period = 'today';
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->applyPreset('month');
|
||||
// Default period
|
||||
}
|
||||
|
||||
/**
|
||||
* Islands whose content depends on the global range; skipped islands never re-render on their own.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const RANGE_DEPENDENT_ISLANDS = [
|
||||
'article-statistics',
|
||||
'articles-trend',
|
||||
'approval-rate',
|
||||
'publish-success-rate',
|
||||
'articles-per-feed',
|
||||
'publications-per-channel',
|
||||
];
|
||||
|
||||
private const RECENT_ACTIVITY_LIMIT = 5;
|
||||
|
||||
public function applyPreset(string $preset): void
|
||||
public function setPeriod(string $period): void
|
||||
{
|
||||
try {
|
||||
$range = DateRange::preset($preset);
|
||||
} catch (InvalidArgumentException) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->applyRange($range->from->toDateString(), $range->to->toDateString());
|
||||
}
|
||||
|
||||
public function applyRange(string $from, string $to): void
|
||||
{
|
||||
$this->from = $from;
|
||||
$this->to = $to;
|
||||
|
||||
$this->validateRange();
|
||||
$this->refreshRangeDependentIslands();
|
||||
}
|
||||
|
||||
private function refreshRangeDependentIslands(): void
|
||||
{
|
||||
foreach (self::RANGE_DEPENDENT_ISLANDS as $island) {
|
||||
$this->renderIsland(name: $island);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
#[Computed]
|
||||
public function presets(): array
|
||||
{
|
||||
return DateRange::presets();
|
||||
}
|
||||
|
||||
public bool $rangeIsValid = true;
|
||||
|
||||
public function range(): ?DateRange
|
||||
{
|
||||
$from = $this->parseBoundary($this->from);
|
||||
$to = $this->parseBoundary($this->to);
|
||||
|
||||
if (! $from instanceof Carbon || ! $to instanceof Carbon) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new DateRange($from->startOfDay(), $to->endOfDay());
|
||||
} catch (InvalidArgumentException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function parseBoundary(string $value): ?Carbon
|
||||
{
|
||||
try {
|
||||
return Carbon::parse($value);
|
||||
} catch (\Exception) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
#[Computed]
|
||||
public function articleStats(): array
|
||||
{
|
||||
$range = $this->range();
|
||||
|
||||
if (! $range instanceof DateRange) {
|
||||
return [
|
||||
'articles_fetched' => 0,
|
||||
'articles_published' => 0,
|
||||
'published_percentage' => 0.0,
|
||||
];
|
||||
}
|
||||
|
||||
return app(DashboardStatsService::class)->getStats($range);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function articlesTrend(): SeriesResult
|
||||
{
|
||||
$range = $this->range();
|
||||
|
||||
return $range instanceof DateRange
|
||||
? app(ArticlesTrend::class)->for($range)
|
||||
: new SeriesResult([], []);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function approvalRate(): SeriesResult
|
||||
{
|
||||
$range = $this->range();
|
||||
|
||||
return $range instanceof DateRange
|
||||
? app(ApprovalRate::class)->for($range)
|
||||
: new SeriesResult([], []);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function publishSuccessRate(): SeriesResult
|
||||
{
|
||||
$range = $this->range();
|
||||
|
||||
return $range instanceof DateRange
|
||||
? app(PublishSuccessRate::class)->for($range)
|
||||
: new SeriesResult([], []);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function articlesPerFeed(): BreakdownResult
|
||||
{
|
||||
return $this->breakdown(ArticlesPerFeed::class);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function publicationsPerChannel(): BreakdownResult
|
||||
{
|
||||
return $this->breakdown(PublicationsPerChannel::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string<BreakdownStat> $stat
|
||||
*/
|
||||
private function breakdown(string $stat): BreakdownResult
|
||||
{
|
||||
$range = $this->range();
|
||||
|
||||
return $range instanceof DateRange
|
||||
? app($stat)->for($range)
|
||||
: new BreakdownResult([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deliberately range-independent: "recent" means latest, not latest within the filter.
|
||||
*
|
||||
* @return Collection<int, ActivityLog>
|
||||
*/
|
||||
#[Computed]
|
||||
public function recentActivity(): Collection
|
||||
{
|
||||
return ActivityLog::query()
|
||||
->withSubjectDetails()
|
||||
->latestFirst()
|
||||
->limit(self::RECENT_ACTIVITY_LIMIT)
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
#[Computed]
|
||||
public function systemStats(): array
|
||||
{
|
||||
return app(DashboardStatsService::class)->getSystemStats();
|
||||
}
|
||||
|
||||
public function updated(string $property): void
|
||||
{
|
||||
if (in_array($property, ['from', 'to'], true)) {
|
||||
$this->validateRange();
|
||||
$this->refreshRangeDependentIslands();
|
||||
}
|
||||
}
|
||||
|
||||
private function validateRange(): void
|
||||
{
|
||||
$this->resetErrorBag(['from', 'to']);
|
||||
|
||||
$from = $this->parseBoundary($this->from);
|
||||
$to = $this->parseBoundary($this->to);
|
||||
|
||||
if (! $from instanceof Carbon) {
|
||||
$this->addError('from', 'The start date is not a valid date.');
|
||||
}
|
||||
|
||||
if (! $to instanceof Carbon) {
|
||||
$this->addError('to', 'The end date is not a valid date.');
|
||||
}
|
||||
|
||||
if ($from instanceof Carbon && $to instanceof Carbon && $to->lessThan($from)) {
|
||||
$this->addError('to', 'The end date must not be earlier than the start date.');
|
||||
}
|
||||
|
||||
$this->rangeIsValid = $this->range() instanceof DateRange;
|
||||
$this->period = $period;
|
||||
}
|
||||
|
||||
public function render(): View
|
||||
{
|
||||
return view('livewire.dashboard')->layout('layouts.app');
|
||||
$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');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,12 +21,6 @@ class Feeds extends Component
|
|||
|
||||
public string $newDescription = '';
|
||||
|
||||
public ?int $editingFeedId = null;
|
||||
|
||||
public string $editName = '';
|
||||
|
||||
public string $editDescription = '';
|
||||
|
||||
public function toggle(int $feedId): void
|
||||
{
|
||||
$feed = Feed::findOrFail($feedId);
|
||||
|
|
@ -73,41 +67,6 @@ public function createFeed(CreateFeedAction $action): void
|
|||
$this->closeCreateModal();
|
||||
}
|
||||
|
||||
public function openEditModal(int $feedId): void
|
||||
{
|
||||
$feed = Feed::findOrFail($feedId);
|
||||
|
||||
$this->resetErrorBag();
|
||||
$this->editingFeedId = $feedId;
|
||||
$this->editName = $feed->name;
|
||||
$this->editDescription = $feed->description ?? '';
|
||||
}
|
||||
|
||||
public function closeEditModal(): void
|
||||
{
|
||||
$this->editingFeedId = null;
|
||||
}
|
||||
|
||||
// Provider and language are deliberately not editable: CreateFeedAction derives the unique
|
||||
// feeds.url from that pair, so changing either re-points the feed and orphans its articles.
|
||||
public function updateFeed(): void
|
||||
{
|
||||
if ($this->editingFeedId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->validate([
|
||||
'editName' => 'required|string|max:255',
|
||||
]);
|
||||
|
||||
Feed::findOrFail($this->editingFeedId)->update([
|
||||
'name' => $this->editName,
|
||||
'description' => $this->editDescription !== '' ? $this->editDescription : null,
|
||||
]);
|
||||
|
||||
$this->closeEditModal();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<string, mixed>>
|
||||
*/
|
||||
|
|
@ -127,9 +86,6 @@ public function render(): View
|
|||
'feeds' => $feeds,
|
||||
'providers' => $this->activeProviders(),
|
||||
'languages' => Language::where('is_active', true)->orderBy('name')->get(),
|
||||
'editingFeed' => $this->editingFeedId !== null
|
||||
? Feed::with('language')->find($this->editingFeedId)
|
||||
: null,
|
||||
])->layout('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,10 +17,8 @@
|
|||
use App\Models\Route;
|
||||
use App\Models\Setting;
|
||||
use App\Services\OnboardingService;
|
||||
use App\Services\Platform\CommunityDirectory;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Validation\Rule;
|
||||
use InvalidArgumentException;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
|
@ -51,12 +49,7 @@ class Onboarding extends Component
|
|||
public string $feedDescription = '';
|
||||
|
||||
// Channel form
|
||||
public ?int $channelCommunityId = null;
|
||||
|
||||
/** @var array<int, array{id: int, name: string, title: string}> */
|
||||
public array $availableCommunities = [];
|
||||
|
||||
public ?string $communityLoadError = null;
|
||||
public string $channelName = '';
|
||||
|
||||
public ?int $platformInstanceId = null;
|
||||
|
||||
|
|
@ -124,11 +117,10 @@ public function mount(): void
|
|||
// 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 ?? '';
|
||||
$this->loadCommunities();
|
||||
$this->channelCommunityId = $channel->channel_id;
|
||||
}
|
||||
|
||||
// Pre-fill route form if exists
|
||||
|
|
@ -260,61 +252,16 @@ public function createFeed(): void
|
|||
}
|
||||
}
|
||||
|
||||
public function updatedPlatformInstanceId(?int $value): void
|
||||
{
|
||||
$this->reset(['channelCommunityId', 'availableCommunities', 'communityLoadError']);
|
||||
|
||||
if ($value) {
|
||||
$this->loadCommunities();
|
||||
}
|
||||
}
|
||||
|
||||
public function refreshCommunities(): void
|
||||
{
|
||||
$instance = $this->platformInstanceId ? PlatformInstance::find($this->platformInstanceId) : null;
|
||||
|
||||
if (! $instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(CommunityDirectory::class)->forget($instance);
|
||||
$this->loadCommunities();
|
||||
}
|
||||
|
||||
private function loadCommunities(): void
|
||||
{
|
||||
$this->availableCommunities = [];
|
||||
$this->communityLoadError = null;
|
||||
|
||||
$instance = $this->platformInstanceId ? PlatformInstance::find($this->platformInstanceId) : null;
|
||||
|
||||
if (! $instance) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->availableCommunities = app(CommunityDirectory::class)->forInstance($instance);
|
||||
} catch (Exception $e) {
|
||||
$this->communityLoadError = 'Could not reach this instance to list its communities: '.$e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public function createChannel(): void
|
||||
{
|
||||
$this->formErrors = [];
|
||||
$this->isLoading = true;
|
||||
|
||||
$this->validate([
|
||||
'channelCommunityId' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::in(collect($this->availableCommunities)->pluck('id')->all()),
|
||||
],
|
||||
'channelName' => 'required|string|max:255',
|
||||
'platformInstanceId' => 'required|exists:platform_instances,id',
|
||||
'channelLanguageId' => 'required|exists:languages,id',
|
||||
'channelDescription' => 'nullable|string|max:1000',
|
||||
], [
|
||||
'channelCommunityId.in' => 'Select a community from this instance.',
|
||||
]);
|
||||
|
||||
// If language changed, reset feed form
|
||||
|
|
@ -327,14 +274,11 @@ public function createChannel(): void
|
|||
}
|
||||
$this->previousChannelLanguageId = $this->channelLanguageId;
|
||||
|
||||
$name = collect($this->availableCommunities)->firstWhere('id', $this->channelCommunityId)['name'] ?? null;
|
||||
|
||||
try {
|
||||
$channel = $this->createChannelAction->execute(
|
||||
$name,
|
||||
(int) $this->channelCommunityId,
|
||||
(int) $this->platformInstanceId,
|
||||
$this->channelLanguageId !== null ? (int) $this->channelLanguageId : null,
|
||||
$this->channelName,
|
||||
$this->platformInstanceId,
|
||||
$this->channelLanguageId,
|
||||
$this->channelDescription ?: null,
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Events\RouteActivated;
|
||||
use App\Models\Feed;
|
||||
use App\Models\Keyword;
|
||||
use App\Models\PlatformChannel;
|
||||
|
|
@ -73,8 +72,6 @@ public function createRoute(): void
|
|||
'is_active' => true,
|
||||
]);
|
||||
|
||||
RouteActivated::dispatch($this->newFeedId, $this->newChannelId);
|
||||
|
||||
$this->closeCreateModal();
|
||||
}
|
||||
|
||||
|
|
@ -132,10 +129,6 @@ public function toggle(int $feedId, int $channelId): void
|
|||
|
||||
$route->is_active = ! $route->is_active;
|
||||
$route->save();
|
||||
|
||||
if ($route->is_active) {
|
||||
RouteActivated::dispatch($route->feed_id, $route->platform_channel_id);
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(int $feedId, int $channelId): void
|
||||
|
|
|
|||
|
|
@ -16,8 +16,6 @@ class Settings extends Component
|
|||
|
||||
public int $feedStalenessThreshold = 48;
|
||||
|
||||
public int $dailyPublishCap = 0;
|
||||
|
||||
public ?string $successMessage = null;
|
||||
|
||||
public ?string $errorMessage = null;
|
||||
|
|
@ -28,7 +26,6 @@ public function mount(): void
|
|||
$this->publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();
|
||||
$this->articlePublishingInterval = Setting::getArticlePublishingInterval();
|
||||
$this->feedStalenessThreshold = Setting::getFeedStalenessThreshold();
|
||||
$this->dailyPublishCap = Setting::getDailyPublishCap();
|
||||
}
|
||||
|
||||
public function toggleArticleProcessing(): void
|
||||
|
|
@ -65,16 +62,6 @@ public function updateFeedStalenessThreshold(): void
|
|||
$this->showSuccess();
|
||||
}
|
||||
|
||||
public function updateDailyPublishCap(): void
|
||||
{
|
||||
$this->validate([
|
||||
'dailyPublishCap' => 'required|integer|min:0',
|
||||
]);
|
||||
|
||||
Setting::setDailyPublishCap($this->dailyPublishCap);
|
||||
$this->showSuccess();
|
||||
}
|
||||
|
||||
protected function showSuccess(): void
|
||||
{
|
||||
$this->successMessage = 'Settings updated successfully!';
|
||||
|
|
|
|||
|
|
@ -1,94 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use Database\Factories\ActivityLogFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property ActivityTypeEnum $type
|
||||
* @property string $message
|
||||
* @property array<string, mixed>|null $context
|
||||
* @property string|null $subject_type
|
||||
* @property int|null $subject_id
|
||||
* @property Carbon $logged_at
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
*/
|
||||
class ActivityLog extends Model
|
||||
{
|
||||
/** @use HasFactory<ActivityLogFactory> */
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'type',
|
||||
'message',
|
||||
'context',
|
||||
'subject_type',
|
||||
'subject_id',
|
||||
'logged_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'type' => ActivityTypeEnum::class,
|
||||
'context' => 'array',
|
||||
'logged_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return MorphTo<Model, $this>
|
||||
*/
|
||||
public function subject(): MorphTo
|
||||
{
|
||||
return $this->morphTo();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<ActivityLog> $query
|
||||
* @return Builder<ActivityLog>
|
||||
*/
|
||||
public function scopeOfType(Builder $query, ActivityTypeEnum $type): Builder
|
||||
{
|
||||
return $query->where('type', $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<ActivityLog> $query
|
||||
* @return Builder<ActivityLog>
|
||||
*/
|
||||
public function scopeSince(Builder $query, Carbon $since): Builder
|
||||
{
|
||||
return $query->where('logged_at', '>=', $since);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<ActivityLog> $query
|
||||
* @return Builder<ActivityLog>
|
||||
*/
|
||||
public function scopeLatestFirst(Builder $query): Builder
|
||||
{
|
||||
return $query->orderByDesc('logged_at')->orderByDesc('id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<ActivityLog> $query
|
||||
* @return Builder<ActivityLog>
|
||||
*/
|
||||
public function scopeWithSubjectDetails(Builder $query): Builder
|
||||
{
|
||||
return $query->with(['subject' => function (Relation $morphTo): void {
|
||||
if ($morphTo instanceof MorphTo) {
|
||||
$morphTo->morphWith([Article::class => ['feed']]);
|
||||
}
|
||||
}]);
|
||||
}
|
||||
}
|
||||
|
|
@ -17,12 +17,11 @@
|
|||
* @method static create(array<string, mixed> $array)
|
||||
*
|
||||
* @property int $id
|
||||
* @property int|null $feed_id
|
||||
* @property int $feed_id
|
||||
* @property Feed $feed
|
||||
* @property string $url
|
||||
* @property string $title
|
||||
* @property string|null $description
|
||||
* @property string|null $content
|
||||
* @property Carbon|null $validated_at
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\FeedColorEnum;
|
||||
use Database\Factories\FeedFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
|
|
@ -20,8 +19,7 @@
|
|||
* @property string $provider
|
||||
* @property int|null $language_id
|
||||
* @property Language|null $language
|
||||
* @property string|null $description
|
||||
* @property FeedColorEnum|null $color
|
||||
* @property string $description
|
||||
* @property array<string, mixed> $settings
|
||||
* @property bool $is_active
|
||||
* @property Carbon|null $last_fetched_at
|
||||
|
|
@ -48,7 +46,6 @@ class Feed extends Model
|
|||
'provider',
|
||||
'language_id',
|
||||
'description',
|
||||
'color',
|
||||
'settings',
|
||||
'is_active',
|
||||
'last_fetched_at',
|
||||
|
|
@ -58,14 +55,8 @@ class Feed extends Model
|
|||
'settings' => 'array',
|
||||
'is_active' => 'boolean',
|
||||
'last_fetched_at' => 'datetime',
|
||||
'color' => FeedColorEnum::class,
|
||||
];
|
||||
|
||||
public function displayColor(): FeedColorEnum
|
||||
{
|
||||
return $this->color ?? FeedColorEnum::forId($this->id);
|
||||
}
|
||||
|
||||
public function getTypeDisplayAttribute(): string
|
||||
{
|
||||
return match ($this->type) {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\AccountStatusEnum;
|
||||
use App\Enums\PlatformEnum;
|
||||
use Database\Factories\PlatformAccountFactory;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
|
|
@ -22,8 +21,7 @@
|
|||
* @property array<string, mixed> $settings
|
||||
* @property bool $is_active
|
||||
* @property Carbon|null $last_tested_at
|
||||
* @property AccountStatusEnum $status
|
||||
* @property int $consecutive_failures
|
||||
* @property string $status
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
* @property Collection<int, PlatformChannel> $activeChannels
|
||||
|
|
@ -46,12 +44,10 @@ class PlatformAccount extends Model
|
|||
'is_active',
|
||||
'last_tested_at',
|
||||
'status',
|
||||
'consecutive_failures',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'platform' => PlatformEnum::class,
|
||||
'status' => AccountStatusEnum::class,
|
||||
'settings' => 'array',
|
||||
'is_active' => 'boolean',
|
||||
'last_tested_at' => 'datetime',
|
||||
|
|
@ -140,33 +136,4 @@ public function activeChannels(): BelongsToMany
|
|||
->wherePivot('is_active', true)
|
||||
->orderByPivot('priority', 'desc');
|
||||
}
|
||||
|
||||
public const FAILURES_BEFORE_UNHEALTHY = 3;
|
||||
|
||||
public function recordCredentialCheckPassed(): void
|
||||
{
|
||||
$this->update([
|
||||
'status' => AccountStatusEnum::HEALTHY,
|
||||
'consecutive_failures' => 0,
|
||||
'last_tested_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function recordCredentialCheckFailed(): void
|
||||
{
|
||||
$failures = $this->consecutive_failures + 1;
|
||||
|
||||
$this->update([
|
||||
'status' => $failures >= self::FAILURES_BEFORE_UNHEALTHY
|
||||
? AccountStatusEnum::UNHEALTHY
|
||||
: $this->status,
|
||||
'consecutive_failures' => $failures,
|
||||
'last_tested_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function isUnhealthy(): bool
|
||||
{
|
||||
return $this->status === AccountStatusEnum::UNHEALTHY;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,11 +15,9 @@
|
|||
* @property int $id
|
||||
* @property int $platform_instance_id
|
||||
* @property PlatformInstance $platformInstance
|
||||
* @property int $channel_id
|
||||
* @property string $channel_id
|
||||
* @property string $name
|
||||
* @property string $display_name
|
||||
* @property string|null $description
|
||||
* @property int|null $language_id
|
||||
* @property int $language_id
|
||||
* @property Language|null $language
|
||||
* @property bool $is_active
|
||||
*/
|
||||
|
|
@ -42,7 +40,6 @@ class PlatformChannel extends Model
|
|||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
'channel_id' => 'integer',
|
||||
];
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -2,12 +2,13 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\PlatformEnum;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* @method static where(string $string, PlatformEnum $platform)
|
||||
* @method static updateOrCreate(array<string, mixed> $array, array<string, mixed> $array1)
|
||||
*/
|
||||
class PlatformChannelPost extends Model
|
||||
|
|
@ -16,7 +17,9 @@ class PlatformChannelPost extends Model
|
|||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'platform_channel_id',
|
||||
'platform',
|
||||
'channel_id',
|
||||
'channel_name',
|
||||
'post_id',
|
||||
'url',
|
||||
'title',
|
||||
|
|
@ -30,24 +33,26 @@ protected function casts(): array
|
|||
{
|
||||
return [
|
||||
'posted_at' => 'datetime',
|
||||
'platform' => PlatformEnum::class,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<PlatformChannel, $this>
|
||||
*/
|
||||
public function platformChannel(): BelongsTo
|
||||
public static function urlExists(PlatformEnum $platform, string $channelId, string $url): bool
|
||||
{
|
||||
return $this->belongsTo(PlatformChannel::class);
|
||||
return self::where('platform', $platform)
|
||||
->where('channel_id', $channelId)
|
||||
->where('url', $url)
|
||||
->exists();
|
||||
}
|
||||
|
||||
public static function duplicateExists(PlatformChannel $channel, ?string $url, ?string $title): bool
|
||||
public static function duplicateExists(PlatformEnum $platform, string $channelId, ?string $url, ?string $title): bool
|
||||
{
|
||||
if (! $url && ! $title) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return self::where('platform_channel_id', $channel->id)
|
||||
return self::where('platform', $platform)
|
||||
->where('channel_id', $channelId)
|
||||
->where(function ($query) use ($url, $title) {
|
||||
if ($url) {
|
||||
$query->orWhere('url', $url);
|
||||
|
|
@ -59,14 +64,16 @@ public static function duplicateExists(PlatformChannel $channel, ?string $url, ?
|
|||
->exists();
|
||||
}
|
||||
|
||||
public static function storePost(PlatformChannel $channel, string $postId, ?string $url, ?string $title, ?\DateTime $postedAt = null): self
|
||||
public static function storePost(PlatformEnum $platform, string $channelId, ?string $channelName, string $postId, ?string $url, ?string $title, ?\DateTime $postedAt = null): self
|
||||
{
|
||||
return self::updateOrCreate(
|
||||
[
|
||||
'platform_channel_id' => $channel->id,
|
||||
'platform' => $platform,
|
||||
'channel_id' => $channelId,
|
||||
'post_id' => $postId,
|
||||
],
|
||||
[
|
||||
'channel_name' => $channelName,
|
||||
'url' => $url,
|
||||
'title' => $title,
|
||||
'posted_at' => $postedAt ?? now(),
|
||||
|
|
|
|||
|
|
@ -2,13 +2,10 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Enums\ApprovalStatusEnum;
|
||||
use App\Enums\PublishStatusEnum;
|
||||
use App\Events\ActivityLogged;
|
||||
use App\Events\RouteArticleApproved;
|
||||
use Database\Factories\RouteArticleFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
|
@ -21,9 +18,7 @@
|
|||
* @property int $article_id
|
||||
* @property ApprovalStatusEnum $approval_status
|
||||
* @property PublishStatusEnum $publish_status
|
||||
* @property string|null $publish_error
|
||||
* @property Carbon|null $validated_at
|
||||
* @property Carbon|null $decided_at
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
*/
|
||||
|
|
@ -38,16 +33,13 @@ class RouteArticle extends Model
|
|||
'article_id',
|
||||
'approval_status',
|
||||
'publish_status',
|
||||
'publish_error',
|
||||
'validated_at',
|
||||
'decided_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'approval_status' => ApprovalStatusEnum::class,
|
||||
'publish_status' => PublishStatusEnum::class,
|
||||
'validated_at' => 'datetime',
|
||||
'decided_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
|
|
@ -100,77 +92,13 @@ public function isRejected(): bool
|
|||
|
||||
public function approve(): void
|
||||
{
|
||||
if ($this->isApproved()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->update([
|
||||
'approval_status' => ApprovalStatusEnum::APPROVED,
|
||||
'decided_at' => now(),
|
||||
]);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::APPROVE,
|
||||
"Approved \"{$this->article->title}\"",
|
||||
['route_article_id' => $this->id],
|
||||
$this->article,
|
||||
);
|
||||
$this->update(['approval_status' => ApprovalStatusEnum::APPROVED]);
|
||||
|
||||
event(new RouteArticleApproved($this));
|
||||
}
|
||||
|
||||
public function reject(): void
|
||||
{
|
||||
if ($this->isRejected()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->update([
|
||||
'approval_status' => ApprovalStatusEnum::REJECTED,
|
||||
'decided_at' => now(),
|
||||
]);
|
||||
|
||||
ActivityLogged::dispatch(
|
||||
ActivityTypeEnum::REJECT,
|
||||
"Rejected \"{$this->article->title}\"",
|
||||
['route_article_id' => $this->id],
|
||||
$this->article,
|
||||
);
|
||||
}
|
||||
|
||||
public function recordPublishFailed(string $reason): void
|
||||
{
|
||||
$this->update([
|
||||
'publish_status' => PublishStatusEnum::ERROR,
|
||||
'publish_error' => $reason,
|
||||
]);
|
||||
}
|
||||
|
||||
public function clearPublishFailure(): void
|
||||
{
|
||||
$this->update([
|
||||
'publish_status' => PublishStatusEnum::UNPUBLISHED,
|
||||
'publish_error' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed article is never picked up again on its own; the user retries it from the Articles page.
|
||||
*
|
||||
* @param Builder<RouteArticle> $query
|
||||
* @return Builder<RouteArticle>
|
||||
*/
|
||||
public function scopeDueForPublishing(Builder $query): Builder
|
||||
{
|
||||
return $query->where('publish_status', '!=', PublishStatusEnum::ERROR);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<RouteArticle> $query
|
||||
* @return Builder<RouteArticle>
|
||||
*/
|
||||
public function scopeFailed(Builder $query): Builder
|
||||
{
|
||||
return $query->where('publish_status', PublishStatusEnum::ERROR);
|
||||
$this->update(['approval_status' => ApprovalStatusEnum::REJECTED]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -81,14 +81,4 @@ public static function setFeedStalenessThreshold(int $hours): void
|
|||
{
|
||||
static::set('feed_staleness_threshold', (string) $hours);
|
||||
}
|
||||
|
||||
public static function getDailyPublishCap(): int
|
||||
{
|
||||
return (int) static::get('daily_publish_cap', 0);
|
||||
}
|
||||
|
||||
public static function setDailyPublishCap(int $articles): void
|
||||
{
|
||||
static::set('daily_publish_cap', (string) $articles);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,9 +7,6 @@
|
|||
|
||||
class LemmyRequest
|
||||
{
|
||||
// Uploads carry an image payload; the 30s used for JSON calls is not enough.
|
||||
private const UPLOAD_TIMEOUT_SECONDS = 60;
|
||||
|
||||
private string $instance;
|
||||
|
||||
private ?string $token;
|
||||
|
|
@ -86,27 +83,6 @@ public function post(string $endpoint, array $data = []): Response
|
|||
return $request->post($url, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* pict-rs is mounted outside the /api/v3 prefix, so this takes a root-relative path.
|
||||
*
|
||||
* @param string $path Root-relative, e.g. 'pictrs/image'
|
||||
* @param string $name Multipart field name, e.g. 'images[]'
|
||||
* @param string $contents Raw file bytes
|
||||
* @param string $filename Filename sent with the part
|
||||
*/
|
||||
public function postMultipart(string $path, string $name, string $contents, string $filename): Response
|
||||
{
|
||||
$url = sprintf('%s://%s/%s', $this->scheme, $this->instance, ltrim($path, '/'));
|
||||
|
||||
$request = Http::timeout(self::UPLOAD_TIMEOUT_SECONDS);
|
||||
|
||||
if ($this->token) {
|
||||
$request = $request->withToken($this->token);
|
||||
}
|
||||
|
||||
return $request->attach($name, $contents, $filename)->post($url);
|
||||
}
|
||||
|
||||
public function withToken(string $token): self
|
||||
{
|
||||
$this->token = $token;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
namespace App\Modules\Lemmy\Services;
|
||||
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Enums\PlatformEnum;
|
||||
use App\Models\PlatformChannelPost;
|
||||
use App\Modules\Lemmy\LemmyRequest;
|
||||
use Exception;
|
||||
|
|
@ -84,35 +84,18 @@ public function login(string $username, string $password): ?string
|
|||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{id: int, name: string, title: string}>
|
||||
* Resolve a PlatformChannel.channel_id to a numeric Lemmy community id.
|
||||
*
|
||||
* channel_id holds either a community slug (the usual case — CreateChannelAction
|
||||
* copies `name` into it) or an already-numeric community id. Callers that need the
|
||||
* numeric id should use this rather than reimplementing the check, so the two forms
|
||||
* stay handled identically everywhere.
|
||||
*/
|
||||
public function listCommunities(?string $token = null): array
|
||||
public function resolveCommunityId(string $channelId, string $token): int
|
||||
{
|
||||
$request = new LemmyRequest($this->instance, $token);
|
||||
$response = $request->get('community/list', [
|
||||
'type_' => 'Local',
|
||||
'limit' => 50,
|
||||
'sort' => 'TopAll',
|
||||
]);
|
||||
|
||||
if (! $response->successful()) {
|
||||
throw new Exception('Failed to list communities: '.$response->status());
|
||||
}
|
||||
|
||||
/** @var array<int, array<string, mixed>> $communities */
|
||||
$communities = $response->json('communities') ?? [];
|
||||
|
||||
return collect($communities)
|
||||
->pluck('community')
|
||||
->reject(fn ($community) => ($community['removed'] ?? false) || ($community['deleted'] ?? false))
|
||||
->map(fn ($community) => [
|
||||
'id' => (int) $community['id'],
|
||||
'name' => (string) $community['name'],
|
||||
'title' => (string) ($community['title'] ?? $community['name']),
|
||||
])
|
||||
->sortBy('name')
|
||||
->values()
|
||||
->all();
|
||||
return is_numeric($channelId)
|
||||
? (int) $channelId
|
||||
: $this->getCommunityId($channelId, $token);
|
||||
}
|
||||
|
||||
public function getCommunityId(string $communityName, string $token): int
|
||||
|
|
@ -134,12 +117,12 @@ public function getCommunityId(string $communityName, string $token): int
|
|||
}
|
||||
}
|
||||
|
||||
public function syncChannelPosts(string $token, PlatformChannel $channel, int $communityId): void
|
||||
public function syncChannelPosts(string $token, int $platformChannelId, string $communityName): void
|
||||
{
|
||||
try {
|
||||
$request = new LemmyRequest($this->instance, $token);
|
||||
$response = $request->get('post/list', [
|
||||
'community_id' => $communityId,
|
||||
'community_id' => $platformChannelId,
|
||||
'limit' => 50,
|
||||
'sort' => 'New',
|
||||
]);
|
||||
|
|
@ -147,7 +130,7 @@ public function syncChannelPosts(string $token, PlatformChannel $channel, int $c
|
|||
if (! $response->successful()) {
|
||||
logger()->warning('Failed to sync channel posts', [
|
||||
'status' => $response->status(),
|
||||
'platform_channel_id' => $channel->id,
|
||||
'platform_channel_id' => $platformChannelId,
|
||||
]);
|
||||
|
||||
return;
|
||||
|
|
@ -160,7 +143,9 @@ public function syncChannelPosts(string $token, PlatformChannel $channel, int $c
|
|||
$post = $postData['post'];
|
||||
|
||||
PlatformChannelPost::storePost(
|
||||
$channel,
|
||||
PlatformEnum::LEMMY,
|
||||
(string) $platformChannelId,
|
||||
$communityName,
|
||||
(string) $post['id'],
|
||||
$post['url'] ?? null,
|
||||
$post['name'] ?? null,
|
||||
|
|
@ -169,14 +154,14 @@ public function syncChannelPosts(string $token, PlatformChannel $channel, int $c
|
|||
}
|
||||
|
||||
logger()->info('Synced channel posts', [
|
||||
'platform_channel_id' => $channel->id,
|
||||
'platform_channel_id' => $platformChannelId,
|
||||
'posts_count' => count($posts),
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
logger()->error('Exception while syncing channel posts', [
|
||||
'error' => $e->getMessage(),
|
||||
'platform_channel_id' => $channel->id,
|
||||
'platform_channel_id' => $platformChannelId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@
|
|||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Services\Auth\LemmyAuthService;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
|
||||
class LemmyPublisher
|
||||
|
|
@ -16,13 +15,10 @@ class LemmyPublisher
|
|||
|
||||
private PlatformAccount $account;
|
||||
|
||||
private ThumbnailUploader $thumbnailUploader;
|
||||
|
||||
public function __construct(PlatformAccount $account)
|
||||
{
|
||||
$this->api = new LemmyApiService($account->instance_url);
|
||||
$this->account = $account;
|
||||
$this->thumbnailUploader = new ThumbnailUploader($account->instance_url);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -37,63 +33,36 @@ public function publishToChannel(Article $article, array $extractedData, Platfor
|
|||
$authService = resolve(LemmyAuthService::class);
|
||||
$token = $authService->getToken($this->account);
|
||||
|
||||
$thumbnail = $this->hostedThumbnail($extractedData, $channel, $article, $token);
|
||||
|
||||
try {
|
||||
return $this->createPost($token, $extractedData, $channel, $article, $thumbnail);
|
||||
return $this->createPost($token, $extractedData, $channel, $article);
|
||||
} catch (Exception $e) {
|
||||
// If the cached token was stale, refresh and retry once
|
||||
if (str_contains($e->getMessage(), 'not_logged_in') || str_contains($e->getMessage(), 'Unauthorized')) {
|
||||
$token = $authService->refreshToken($this->account);
|
||||
|
||||
return $this->createPost($token, $extractedData, $channel, $article, $thumbnail);
|
||||
return $this->createPost($token, $extractedData, $channel, $article);
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploaded once per publish, outside the stale-token retry: the upload is the expensive
|
||||
* part and a retry would otherwise re-download, re-encode and re-log.
|
||||
*
|
||||
* @param array<string, mixed> $extractedData
|
||||
*/
|
||||
private function hostedThumbnail(array $extractedData, PlatformChannel $channel, Article $article, string $token): ?string
|
||||
{
|
||||
$source = $extractedData['thumbnail'] ?? null;
|
||||
$source = is_string($source) && $source !== '' ? $source : null;
|
||||
|
||||
if ($source === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$hosted = $this->thumbnailUploader->upload($source, $token);
|
||||
|
||||
if ($hosted === null) {
|
||||
app(LogSaver::class)->warning('Thumbnail upload failed; publishing without one', $channel, [
|
||||
'article_id' => $article->id,
|
||||
'source' => $source,
|
||||
]);
|
||||
}
|
||||
|
||||
return $hosted;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $extractedData
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function createPost(string $token, array $extractedData, PlatformChannel $channel, Article $article, ?string $thumbnail = null): array
|
||||
private function createPost(string $token, array $extractedData, PlatformChannel $channel, Article $article): array
|
||||
{
|
||||
$languageId = $extractedData['language_id'] ?? null;
|
||||
|
||||
$communityId = $this->api->resolveCommunityId($channel->channel_id, $token);
|
||||
|
||||
return $this->api->createPost(
|
||||
$token,
|
||||
$extractedData['title'] ?? 'Untitled',
|
||||
$extractedData['description'] ?? '',
|
||||
$channel->channel_id,
|
||||
$communityId,
|
||||
$article->url,
|
||||
$thumbnail,
|
||||
$extractedData['thumbnail'] ?? null,
|
||||
$languageId
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,125 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Modules\Lemmy\Services;
|
||||
|
||||
use App\Modules\Lemmy\LemmyRequest;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
class ThumbnailUploader
|
||||
{
|
||||
private const MAX_WIDTH = 600;
|
||||
|
||||
// A 4000x2256 JPEG decodes to ~27MB in GD; the worker runs with memory_limit=128M.
|
||||
private const MAX_SOURCE_BYTES = 10_485_760;
|
||||
|
||||
private const MAX_SOURCE_PIXELS = 50_000_000;
|
||||
|
||||
private const JPEG_QUALITY = 82;
|
||||
|
||||
public function __construct(private string $instance) {}
|
||||
|
||||
/**
|
||||
* Returns an instance-hosted URL for a downscaled copy, or null if anything fails.
|
||||
*/
|
||||
public function upload(?string $sourceUrl, string $token): ?string
|
||||
{
|
||||
if ($sourceUrl === null || $sourceUrl === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$source = $this->download($sourceUrl);
|
||||
|
||||
if ($source === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$resized = $this->resize($source);
|
||||
|
||||
if ($resized === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->store($resized, $token);
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function download(string $url): ?string
|
||||
{
|
||||
$response = Http::timeout(30)->get($url);
|
||||
|
||||
if (! $response->successful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$body = $response->body();
|
||||
|
||||
return strlen($body) > self::MAX_SOURCE_BYTES ? null : $body;
|
||||
}
|
||||
|
||||
private function resize(string $source): ?string
|
||||
{
|
||||
$info = @getimagesizefromstring($source);
|
||||
|
||||
if ($info === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$width, $height] = $info;
|
||||
|
||||
if ($width < 1 || $height < 1 || $width * $height > self::MAX_SOURCE_PIXELS) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($width <= self::MAX_WIDTH) {
|
||||
return $source;
|
||||
}
|
||||
|
||||
$image = @imagecreatefromstring($source);
|
||||
|
||||
if ($image === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$targetHeight = (int) max(1, round($height * (self::MAX_WIDTH / $width)));
|
||||
$resized = imagescale($image, self::MAX_WIDTH, $targetHeight);
|
||||
imagedestroy($image);
|
||||
|
||||
if ($resized === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ob_start();
|
||||
|
||||
try {
|
||||
imagejpeg($resized, null, self::JPEG_QUALITY);
|
||||
} finally {
|
||||
$bytes = (string) ob_get_clean();
|
||||
imagedestroy($resized);
|
||||
}
|
||||
|
||||
return $bytes === '' ? null : $bytes;
|
||||
}
|
||||
|
||||
private function store(string $bytes, string $token): ?string
|
||||
{
|
||||
$response = (new LemmyRequest($this->instance, $token))
|
||||
->postMultipart('pictrs/image', 'images[]', $bytes, 'thumbnail.jpg');
|
||||
|
||||
if (! $response->successful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$file = $response->json('files.0.file');
|
||||
|
||||
if (! is_string($file) || $file === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// $instance is a full scheme-qualified URL — platform_accounts.instance_url is validated as a URL.
|
||||
return sprintf('%s/pictrs/image/%s', rtrim($this->instance, '/'), $file);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,11 +2,62 @@
|
|||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Enums\LogLevelEnum;
|
||||
use App\Events\ActionPerformed;
|
||||
use App\Events\ExceptionOccurred;
|
||||
use App\Events\NewArticleFetched;
|
||||
use App\Events\RouteArticleApproved;
|
||||
use App\Listeners\LogActionListener;
|
||||
use App\Listeners\LogExceptionToDatabase;
|
||||
use App\Listeners\PublishApprovedArticleListener;
|
||||
use App\Listeners\ValidateArticleListener;
|
||||
use Error;
|
||||
use Illuminate\Contracts\Debug\ExceptionHandler;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use InvalidArgumentException;
|
||||
use Throwable;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void {}
|
||||
|
||||
public function boot(): void {}
|
||||
public function boot(): void
|
||||
{
|
||||
Event::listen(
|
||||
ActionPerformed::class,
|
||||
LogActionListener::class,
|
||||
);
|
||||
|
||||
Event::listen(
|
||||
ExceptionOccurred::class,
|
||||
LogExceptionToDatabase::class,
|
||||
);
|
||||
|
||||
Event::listen(
|
||||
NewArticleFetched::class,
|
||||
ValidateArticleListener::class,
|
||||
);
|
||||
|
||||
Event::listen(
|
||||
RouteArticleApproved::class,
|
||||
PublishApprovedArticleListener::class,
|
||||
);
|
||||
|
||||
app()->make(ExceptionHandler::class)
|
||||
->reportable(function (Throwable $e) {
|
||||
$level = $this->mapExceptionToLogLevel($e);
|
||||
|
||||
ExceptionOccurred::dispatch($e, $level, $e->getMessage(), []);
|
||||
});
|
||||
}
|
||||
|
||||
private function mapExceptionToLogLevel(Throwable $exception): LogLevelEnum
|
||||
{
|
||||
return match (true) {
|
||||
$exception instanceof Error => LogLevelEnum::CRITICAL,
|
||||
$exception instanceof InvalidArgumentException => LogLevelEnum::WARNING,
|
||||
default => LogLevelEnum::ERROR,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,34 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Activity;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Models\ActivityLog;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class ActivitySummary
|
||||
{
|
||||
/**
|
||||
* Counts per type since $since, including types with no rows.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function since(Carbon $since): array
|
||||
{
|
||||
/** @var array<string, int> $counts */
|
||||
$counts = ActivityLog::query()
|
||||
->since($since)
|
||||
->selectRaw('type, COUNT(*) as aggregate')
|
||||
->groupBy('type')
|
||||
->pluck('aggregate', 'type')
|
||||
->all();
|
||||
|
||||
$summary = [];
|
||||
|
||||
foreach (ActivityTypeEnum::cases() as $case) {
|
||||
$summary[$case->value] = (int) ($counts[$case->value] ?? 0);
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
}
|
||||
181
app/Services/Article/ArticleFetcher.php
Normal file
181
app/Services/Article/ArticleFetcher.php
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Article;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Feed;
|
||||
use App\Services\Factories\ArticleParserFactory;
|
||||
use App\Services\Factories\HomepageParserFactory;
|
||||
use App\Services\Http\HttpFetcher;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ArticleFetcher
|
||||
{
|
||||
public function __construct(
|
||||
private LogSaver $logSaver
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
public function getArticlesFromFeed(Feed $feed): Collection
|
||||
{
|
||||
if ($feed->type === 'rss') {
|
||||
return $this->getArticlesFromRssFeed($feed);
|
||||
} elseif ($feed->type === 'website') {
|
||||
return $this->getArticlesFromWebsiteFeed($feed);
|
||||
}
|
||||
|
||||
$this->logSaver->warning('Unsupported feed type', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_type' => $feed->type,
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
private function getArticlesFromRssFeed(Feed $feed): Collection
|
||||
{
|
||||
try {
|
||||
$xml = HttpFetcher::fetchHtml($feed->url);
|
||||
|
||||
$previousUseErrors = libxml_use_internal_errors(true);
|
||||
|
||||
try {
|
||||
$rss = simplexml_load_string($xml);
|
||||
} finally {
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previousUseErrors);
|
||||
}
|
||||
|
||||
if ($rss === false || ! isset($rss->channel->item)) {
|
||||
$this->logSaver->warning('Failed to parse RSS feed XML', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
|
||||
$articles = collect();
|
||||
foreach ($rss->channel->item as $item) {
|
||||
$link = (string) $item->link;
|
||||
if ($link !== '') {
|
||||
$articles->push($this->saveArticle($link, $feed->id));
|
||||
}
|
||||
}
|
||||
|
||||
return $articles;
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Failed to fetch articles from RSS feed', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Article>
|
||||
*/
|
||||
private 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, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
|
||||
$html = HttpFetcher::fetchHtml($feed->url);
|
||||
$urls = $parser->extractArticleUrls($html);
|
||||
|
||||
return collect($urls)
|
||||
->map(fn (string $url) => $this->saveArticle($url, $feed->id));
|
||||
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Failed to fetch articles from website feed', null, [
|
||||
'feed_id' => $feed->id,
|
||||
'feed_url' => $feed->url,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return collect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function fetchArticleData(Article $article): array
|
||||
{
|
||||
try {
|
||||
$html = HttpFetcher::fetchHtml($article->url);
|
||||
$parser = ArticleParserFactory::getParser($article->url);
|
||||
|
||||
return $parser->extractData($html);
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Exception while fetching article data', null, [
|
||||
'url' => $article->url,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private function saveArticle(string $url, ?int $feedId = null): Article
|
||||
{
|
||||
$fallbackTitle = $this->generateFallbackTitle($url);
|
||||
|
||||
try {
|
||||
$article = Article::firstOrCreate(
|
||||
['url' => $url],
|
||||
[
|
||||
'feed_id' => $feedId,
|
||||
'title' => $fallbackTitle,
|
||||
]
|
||||
);
|
||||
|
||||
if ($article->wasRecentlyCreated) {
|
||||
$article->dispatchFetchedEvent();
|
||||
}
|
||||
|
||||
return $article;
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->error('Failed to create article', null, [
|
||||
'url' => $url,
|
||||
'feed_id' => $feedId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
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';
|
||||
}
|
||||
}
|
||||
116
app/Services/Article/ValidationService.php
Normal file
116
app/Services/Article/ValidationService.php
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Article;
|
||||
|
||||
use App\Enums\ApprovalStatusEnum;
|
||||
use App\Models\Article;
|
||||
use App\Models\Keyword;
|
||||
use App\Models\Route;
|
||||
use App\Models\RouteArticle;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ValidationService
|
||||
{
|
||||
public function __construct(
|
||||
private ArticleFetcher $articleFetcher
|
||||
) {}
|
||||
|
||||
public function validate(Article $article): Article
|
||||
{
|
||||
logger('Validating article for routes: '.$article->id);
|
||||
|
||||
$articleData = $this->articleFetcher->fetchArticleData($article);
|
||||
|
||||
$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', [
|
||||
'article_id' => $article->id,
|
||||
'url' => $article->url,
|
||||
]);
|
||||
|
||||
$updateData['validated_at'] = now();
|
||||
$article->update($updateData);
|
||||
|
||||
return $article->refresh();
|
||||
}
|
||||
|
||||
$updateData['validated_at'] = now();
|
||||
$article->update($updateData);
|
||||
|
||||
$this->createRouteArticles($article, $articleData['full_article']);
|
||||
|
||||
return $article->refresh();
|
||||
}
|
||||
|
||||
private function createRouteArticles(Article $article, string $content): void
|
||||
{
|
||||
$activeRoutes = Route::where('feed_id', $article->feed_id)
|
||||
->where('is_active', true)
|
||||
->get();
|
||||
|
||||
// Batch-load all active keywords for this feed, grouped by channel
|
||||
$keywordsByChannel = Keyword::where('feed_id', $article->feed_id)
|
||||
->where('is_active', true)
|
||||
->get()
|
||||
->groupBy('platform_channel_id');
|
||||
|
||||
// Match keywords against full article content, title, and description
|
||||
$searchableContent = $content.' '.$article->title.' '.$article->description;
|
||||
|
||||
foreach ($activeRoutes as $route) {
|
||||
$routeKeywords = $keywordsByChannel->get($route->platform_channel_id, collect());
|
||||
$status = $this->evaluateKeywords($routeKeywords, $searchableContent);
|
||||
|
||||
if ($status === ApprovalStatusEnum::PENDING && $this->shouldAutoApprove($route)) {
|
||||
$status = ApprovalStatusEnum::APPROVED;
|
||||
}
|
||||
|
||||
RouteArticle::firstOrCreate(
|
||||
[
|
||||
'feed_id' => $route->feed_id,
|
||||
'platform_channel_id' => $route->platform_channel_id,
|
||||
'article_id' => $article->id,
|
||||
],
|
||||
[
|
||||
'approval_status' => $status,
|
||||
'validated_at' => now(),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Keyword> $keywords
|
||||
*/
|
||||
private function evaluateKeywords(Collection $keywords, string $content): ApprovalStatusEnum
|
||||
{
|
||||
if ($keywords->isEmpty()) {
|
||||
return ApprovalStatusEnum::PENDING;
|
||||
}
|
||||
|
||||
foreach ($keywords as $keyword) {
|
||||
if (stripos($content, $keyword->keyword) !== false) {
|
||||
return ApprovalStatusEnum::PENDING;
|
||||
}
|
||||
}
|
||||
|
||||
return ApprovalStatusEnum::REJECTED;
|
||||
}
|
||||
|
||||
private function shouldAutoApprove(Route $route): bool
|
||||
{
|
||||
if ($route->auto_approve !== null) {
|
||||
return $route->auto_approve;
|
||||
}
|
||||
|
||||
return ! Setting::isPublishingApprovalsEnabled();
|
||||
}
|
||||
}
|
||||
|
|
@ -8,25 +8,33 @@
|
|||
use App\Models\PlatformAccount;
|
||||
use App\Models\PlatformChannel;
|
||||
use App\Models\Route;
|
||||
use App\Support\DateRange;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DashboardStatsService
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getStats(DateRange $range): array
|
||||
public function getStats(string $period = 'today'): array
|
||||
{
|
||||
$bounds = [$range->from, $range->to];
|
||||
$dateRange = $this->getDateRange($period);
|
||||
|
||||
$articlesFetched = Article::query()
|
||||
->whereBetween('created_at', $bounds)
|
||||
->count();
|
||||
// Get articles fetched for the period
|
||||
$articlesFetchedQuery = Article::query();
|
||||
if ($dateRange) {
|
||||
$articlesFetchedQuery->whereBetween('created_at', $dateRange);
|
||||
}
|
||||
$articlesFetched = $articlesFetchedQuery->count();
|
||||
|
||||
$articlesPublished = ArticlePublication::query()
|
||||
->whereBetween('published_at', $bounds)
|
||||
->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;
|
||||
|
||||
return [
|
||||
|
|
@ -36,6 +44,37 @@ public function getStats(DateRange $range): array
|
|||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function getAvailablePeriods(): array
|
||||
{
|
||||
return [
|
||||
'today' => 'Today',
|
||||
'week' => 'This Week',
|
||||
'month' => 'This Month',
|
||||
'year' => 'This Year',
|
||||
'all' => 'All Time',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: Carbon, 1: Carbon}|null
|
||||
*/
|
||||
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()],
|
||||
'month' => [$now->copy()->startOfMonth(), $now->copy()->endOfMonth()],
|
||||
'year' => [$now->copy()->startOfYear(), $now->copy()->endOfYear()],
|
||||
'all' => null, // No date filtering for all-time stats
|
||||
default => [$now->copy()->startOfDay(), $now->copy()->endOfDay()],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -110,12 +110,12 @@ public static function extractThumbnail(string $html): ?string
|
|||
{
|
||||
// Try OpenGraph image first
|
||||
if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) {
|
||||
return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
// Try first image in article content
|
||||
if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) {
|
||||
return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -1,28 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Parsers;
|
||||
|
||||
class BelgaHomepageParser
|
||||
{
|
||||
private const ARTICLE_URL_TEMPLATE = 'https://www.belganewsagency.eu/press-releases/%s/';
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function extractArticleUrls(string $json): array
|
||||
{
|
||||
$decoded = json_decode($json, true);
|
||||
|
||||
if (! is_array($decoded) || ! isset($decoded['data']) || ! is_array($decoded['data'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect($decoded['data'])
|
||||
->pluck('id')
|
||||
->filter(fn ($id) => is_int($id) || (is_string($id) && ctype_digit($id)))
|
||||
->map(fn ($id) => sprintf(self::ARTICLE_URL_TEMPLATE, $id))
|
||||
->unique()
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Parsers;
|
||||
|
||||
use App\Contracts\HomepageParserInterface;
|
||||
|
||||
class BelgaHomepageParserAdapter implements HomepageParserInterface
|
||||
{
|
||||
/**
|
||||
* Belga is English-only for now (#124). The unused $language argument keeps
|
||||
* the constructor compatible with HomepageParserFactory, which passes one
|
||||
* positionally to every homepage parser.
|
||||
*
|
||||
* @phpstan-ignore constructor.unusedParameter
|
||||
*/
|
||||
public function __construct(string $language = 'en') {}
|
||||
|
||||
public function canParse(string $url): bool
|
||||
{
|
||||
return str_contains($url, 'belganewsagency.eu') || str_contains($url, 'capi.belga.press');
|
||||
}
|
||||
|
||||
public function extractArticleUrls(string $html): array
|
||||
{
|
||||
return BelgaHomepageParser::extractArticleUrls($html);
|
||||
}
|
||||
|
||||
public function getHomepageUrl(): string
|
||||
{
|
||||
$url = config('feed.providers.belga.languages.en.url');
|
||||
|
||||
return is_string($url) ? $url : '';
|
||||
}
|
||||
|
||||
public function getSourceName(): string
|
||||
{
|
||||
return 'Belga News Agency';
|
||||
}
|
||||
}
|
||||
|
|
@ -68,12 +68,12 @@ public static function extractThumbnail(string $html): ?string
|
|||
{
|
||||
// Try OpenGraph image first
|
||||
if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) {
|
||||
return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
// Try first image in content
|
||||
if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) {
|
||||
return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -67,11 +67,11 @@ public static function extractFullArticle(string $html): ?string
|
|||
public static function extractThumbnail(string $html): ?string
|
||||
{
|
||||
if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) {
|
||||
return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) {
|
||||
return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
|
|
|||
|
|
@ -1,51 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Platform;
|
||||
|
||||
use App\Models\PlatformInstance;
|
||||
use App\Modules\Lemmy\Services\LemmyApiService;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class CommunityDirectory
|
||||
{
|
||||
private const TTL_SECONDS = 86400;
|
||||
|
||||
/**
|
||||
* @return array<int, array{id: int, name: string, title: string}>
|
||||
*/
|
||||
public function forInstance(PlatformInstance $instance): array
|
||||
{
|
||||
return Cache::remember(
|
||||
self::cacheKey($instance),
|
||||
self::TTL_SECONDS,
|
||||
fn () => $this->makeApi($instance->url)->listCommunities()
|
||||
);
|
||||
}
|
||||
|
||||
public function forget(PlatformInstance $instance): void
|
||||
{
|
||||
Cache::forget(self::cacheKey($instance));
|
||||
}
|
||||
|
||||
public function has(PlatformInstance $instance, int $communityId): bool
|
||||
{
|
||||
return collect($this->forInstance($instance))
|
||||
->contains(fn (array $community) => $community['id'] === $communityId);
|
||||
}
|
||||
|
||||
public function name(PlatformInstance $instance, int $communityId): ?string
|
||||
{
|
||||
return collect($this->forInstance($instance))
|
||||
->firstWhere('id', $communityId)['name'] ?? null;
|
||||
}
|
||||
|
||||
protected function makeApi(string $instanceUrl): LemmyApiService
|
||||
{
|
||||
return new LemmyApiService($instanceUrl);
|
||||
}
|
||||
|
||||
private static function cacheKey(PlatformInstance $instance): string
|
||||
{
|
||||
return "platform:communities:{$instance->id}";
|
||||
}
|
||||
}
|
||||
|
|
@ -12,16 +12,10 @@
|
|||
use App\Modules\Lemmy\Services\LemmyPublisher;
|
||||
use App\Services\Log\LogSaver;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Cache\LockTimeoutException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use RuntimeException;
|
||||
|
||||
class ArticlePublishingService
|
||||
{
|
||||
private const LOCK_TTL_SECONDS = 180;
|
||||
|
||||
private const LOCK_WAIT_SECONDS = 15;
|
||||
|
||||
public function __construct(private LogSaver $logSaver) {}
|
||||
|
||||
/**
|
||||
|
|
@ -39,7 +33,7 @@ protected function makePublisher(mixed $account): LemmyPublisher
|
|||
*
|
||||
* @throws PublishException
|
||||
*/
|
||||
public function publishRouteArticle(RouteArticle $routeArticle, array $extractedData): PublishOutcome
|
||||
public function publishRouteArticle(RouteArticle $routeArticle, array $extractedData): ?ArticlePublication
|
||||
{
|
||||
$article = $routeArticle->article;
|
||||
$channel = $routeArticle->platformChannel;
|
||||
|
|
@ -60,7 +54,7 @@ public function publishRouteArticle(RouteArticle $routeArticle, array $extracted
|
|||
'route_article_id' => $routeArticle->id,
|
||||
]);
|
||||
|
||||
return PublishOutcome::failure('No active account for channel');
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->publishToChannel($article, $extractedData, $channel, $account);
|
||||
|
|
@ -69,51 +63,24 @@ public function publishRouteArticle(RouteArticle $routeArticle, array $extracted
|
|||
/**
|
||||
* @param array<string, mixed> $extractedData
|
||||
*/
|
||||
private function publishToChannel(Article $article, array $extractedData, PlatformChannel $channel, mixed $account): PublishOutcome
|
||||
{
|
||||
$lock = Cache::lock("publish:{$article->id}:{$channel->id}", self::LOCK_TTL_SECONDS);
|
||||
|
||||
try {
|
||||
return $lock->block(self::LOCK_WAIT_SECONDS, function () use ($article, $extractedData, $channel, $account) {
|
||||
$alreadyPublished = ArticlePublication::where('article_id', $article->id)
|
||||
->where('platform_channel_id', $channel->id)
|
||||
->exists();
|
||||
|
||||
if ($alreadyPublished) {
|
||||
$this->logSaver->info('Skipping duplicate: already published to channel', $channel, [
|
||||
'article_id' => $article->id,
|
||||
]);
|
||||
|
||||
return PublishOutcome::skipped('Already published to this channel');
|
||||
}
|
||||
|
||||
return $this->doPublishToChannel($article, $extractedData, $channel, $account);
|
||||
});
|
||||
} catch (LockTimeoutException $e) {
|
||||
$this->logSaver->info('Skipping publish: another worker holds the lock', $channel, [
|
||||
'article_id' => $article->id,
|
||||
]);
|
||||
|
||||
return PublishOutcome::skipped('Another worker is publishing this article');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $extractedData
|
||||
*/
|
||||
private function doPublishToChannel(Article $article, array $extractedData, PlatformChannel $channel, mixed $account): PublishOutcome
|
||||
private function publishToChannel(Article $article, array $extractedData, PlatformChannel $channel, mixed $account): ?ArticlePublication
|
||||
{
|
||||
try {
|
||||
// Check if this URL or title was already posted to this channel
|
||||
$title = $extractedData['title'] ?? $article->title;
|
||||
if (PlatformChannelPost::duplicateExists($channel, $article->url, $title)) {
|
||||
if (PlatformChannelPost::duplicateExists(
|
||||
$channel->platformInstance->platform,
|
||||
(string) $channel->channel_id,
|
||||
$article->url,
|
||||
$title
|
||||
)) {
|
||||
$this->logSaver->info('Skipping duplicate: URL or title already posted to channel', $channel, [
|
||||
'article_id' => $article->id,
|
||||
'url' => $article->url,
|
||||
'title' => $title,
|
||||
]);
|
||||
|
||||
return PublishOutcome::skipped('URL or title already posted to this channel');
|
||||
return null;
|
||||
}
|
||||
|
||||
$publisher = $this->makePublisher($account);
|
||||
|
|
@ -133,14 +100,14 @@ private function doPublishToChannel(Article $article, array $extractedData, Plat
|
|||
'article_id' => $article->id,
|
||||
]);
|
||||
|
||||
return PublishOutcome::published($publication);
|
||||
return $publication;
|
||||
} catch (Exception $e) {
|
||||
$this->logSaver->warning('Failed to publish to channel', $channel, [
|
||||
'article_id' => $article->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return PublishOutcome::failure($e->getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,49 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services\Publishing;
|
||||
|
||||
use App\Models\ArticlePublication;
|
||||
|
||||
/**
|
||||
* Publishing has three outcomes, not two: it can succeed, be deliberately
|
||||
* skipped, or fail. Returning a bare null for the last two made every skip
|
||||
* surface as a publish failure (#123).
|
||||
*/
|
||||
class PublishOutcome
|
||||
{
|
||||
private function __construct(
|
||||
public readonly ?ArticlePublication $publication,
|
||||
public readonly bool $skipped,
|
||||
public readonly ?string $reason = null,
|
||||
) {}
|
||||
|
||||
public static function published(ArticlePublication $publication): self
|
||||
{
|
||||
return new self($publication, false);
|
||||
}
|
||||
|
||||
public static function skipped(string $reason): self
|
||||
{
|
||||
return new self(null, true, $reason);
|
||||
}
|
||||
|
||||
public static function failure(string $reason): self
|
||||
{
|
||||
return new self(null, false, $reason);
|
||||
}
|
||||
|
||||
public function succeeded(): bool
|
||||
{
|
||||
return $this->publication !== null;
|
||||
}
|
||||
|
||||
public function wasSkipped(): bool
|
||||
{
|
||||
return $this->skipped;
|
||||
}
|
||||
|
||||
public function failed(): bool
|
||||
{
|
||||
return ! $this->succeeded() && ! $this->skipped;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class DateRange
|
||||
{
|
||||
public const MAX_DAYS = 731;
|
||||
|
||||
public function __construct(
|
||||
public readonly Carbon $from,
|
||||
public readonly Carbon $to,
|
||||
) {
|
||||
if ($to->lessThan($from)) {
|
||||
throw new InvalidArgumentException('The end of a date range cannot precede its start.');
|
||||
}
|
||||
}
|
||||
|
||||
public static function preset(string $preset): self
|
||||
{
|
||||
$now = Carbon::now();
|
||||
|
||||
return match ($preset) {
|
||||
'today' => new self($now->copy()->startOfDay(), $now->copy()->endOfDay()),
|
||||
'week' => new self($now->copy()->startOfWeek(), $now->copy()->endOfWeek()),
|
||||
'month' => new self($now->copy()->startOfMonth(), $now->copy()->endOfMonth()),
|
||||
'year' => new self($now->copy()->startOfYear(), $now->copy()->endOfYear()),
|
||||
'all' => new self(Carbon::createFromTimestamp(0), $now->copy()->endOfDay()),
|
||||
default => throw new InvalidArgumentException("Unknown date range preset [{$preset}]."),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function presets(): array
|
||||
{
|
||||
return [
|
||||
'today' => 'Today',
|
||||
'week' => 'This Week',
|
||||
'month' => 'This Month',
|
||||
'year' => 'This Year',
|
||||
'all' => 'All Time',
|
||||
];
|
||||
}
|
||||
|
||||
public function isBucketableByDay(): bool
|
||||
{
|
||||
return $this->from->copy()->startOfDay()->diffInDays($this->to->copy()->startOfDay()) < self::MAX_DAYS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every day the range touches, as Y-m-d, so callers can zero-fill empty buckets.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function days(): array
|
||||
{
|
||||
$days = [];
|
||||
$cursor = $this->from->copy()->startOfDay();
|
||||
$last = $this->to->copy()->startOfDay();
|
||||
|
||||
if (! $this->isBucketableByDay()) {
|
||||
throw new InvalidArgumentException(
|
||||
'A range wider than '.self::MAX_DAYS.' days cannot be bucketed by day; bucket by month instead.'
|
||||
);
|
||||
}
|
||||
|
||||
while ($cursor->lessThanOrEqualTo($last)) {
|
||||
$days[] = $cursor->toDateString();
|
||||
$cursor->addDay();
|
||||
}
|
||||
|
||||
return $days;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Models\Feed;
|
||||
use App\Models\RouteArticle;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class PendingFeedGroup
|
||||
{
|
||||
/**
|
||||
* @param Collection<int, RouteArticle>|null $routeArticles
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly Feed $feed,
|
||||
public readonly int $count,
|
||||
public readonly ?Collection $routeArticles,
|
||||
) {}
|
||||
|
||||
public function isExpanded(): bool
|
||||
{
|
||||
return $this->routeArticles !== null;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,36 +1,34 @@
|
|||
{
|
||||
"$schema": "https://getcomposer.org/schema.json",
|
||||
"name": "lvl0/fedi-feed-router",
|
||||
"name": "laravel/react-starter-kit",
|
||||
"type": "project",
|
||||
"description": "Routes news articles from RSS and scraped sources to Fediverse communities.",
|
||||
"description": "The skeleton application for the Laravel framework.",
|
||||
"keywords": [
|
||||
"fediverse",
|
||||
"lemmy",
|
||||
"rss",
|
||||
"atom",
|
||||
"laravel"
|
||||
"laravel",
|
||||
"framework"
|
||||
],
|
||||
"homepage": "https://forge.lvl0.xyz/lvl0/fedi-feed-router",
|
||||
"license": "AGPL-3.0-only",
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": "^8.2",
|
||||
"ext-gd": "*",
|
||||
"blade-ui-kit/blade-heroicons": "^2.6",
|
||||
"inertiajs/inertia-laravel": "^2.0",
|
||||
"laravel/framework": "^12.0",
|
||||
"laravel/horizon": "^5.29",
|
||||
"laravel/sanctum": "^4.2",
|
||||
"laravel/tinker": "^2.10.1",
|
||||
"livewire/livewire": "^4.0"
|
||||
"livewire/livewire": "^4.0",
|
||||
"tightenco/ziggy": "^2.4"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.23",
|
||||
"larastan/larastan": "^3.5",
|
||||
"laravel/breeze": "^2.3",
|
||||
"laravel/pail": "^1.2.2",
|
||||
"laravel/pint": "^1.18",
|
||||
"laravel/sail": "^1.43",
|
||||
"mockery/mockery": "^1.6",
|
||||
"nunomaduro/collision": "^8.6",
|
||||
"phpstan/phpstan": "^2.1.32 <2.2",
|
||||
"phpstan/phpstan": "^2.1",
|
||||
"phpstan/phpstan-mockery": "^2.0",
|
||||
"phpunit/phpunit": "^11.5.3"
|
||||
},
|
||||
|
|
@ -66,6 +64,11 @@
|
|||
"Composer\\Config::disableProcessTimeout",
|
||||
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
|
||||
],
|
||||
"dev:ssr": [
|
||||
"npm run build:ssr",
|
||||
"Composer\\Config::disableProcessTimeout",
|
||||
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"php artisan inertia:start-ssr\" --names=server,queue,logs,ssr --kill-others"
|
||||
],
|
||||
"test": [
|
||||
"@php artisan config:clear --ansi",
|
||||
"@php artisan test"
|
||||
|
|
|
|||
8755
composer.lock
generated
8755
composer.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -13,7 +13,7 @@
|
|||
|
|
||||
*/
|
||||
|
||||
'name' => 'Fedi Feed Router',
|
||||
'name' => env('APP_NAME', 'Laravel'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
use App\Services\Parsers\BelgaArticlePageParser;
|
||||
use App\Services\Parsers\BelgaArticleParser;
|
||||
use App\Services\Parsers\BelgaHomepageParserAdapter;
|
||||
use App\Services\Parsers\GuardianArticlePageParser;
|
||||
use App\Services\Parsers\GuardianArticleParser;
|
||||
use App\Services\Parsers\VrtArticlePageParser;
|
||||
|
|
@ -42,14 +41,12 @@
|
|||
'code' => 'belga',
|
||||
'name' => 'Belga News Agency',
|
||||
'description' => 'Belgian national news agency',
|
||||
'type' => 'website',
|
||||
'type' => 'rss',
|
||||
'is_active' => true,
|
||||
'languages' => [
|
||||
// offset is a 0-based item index; offset=1 skips the newest release (#158).
|
||||
'en' => ['url' => 'https://capi.belga.press/belgapress/api/public/pressreleases?offset=0&count=50&search=&start=&end=&newsroomId=70&language=EN'],
|
||||
'en' => ['url' => 'https://www.belganewsagency.eu/feed'],
|
||||
],
|
||||
'parsers' => [
|
||||
'homepage' => BelgaHomepageParserAdapter::class,
|
||||
'article' => BelgaArticleParser::class,
|
||||
'article_page' => BelgaArticlePageParser::class,
|
||||
],
|
||||
|
|
|
|||
|
|
@ -1,50 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Enums\ActivityTypeEnum;
|
||||
use App\Models\ActivityLog;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* @extends Factory<ActivityLog>
|
||||
*/
|
||||
class ActivityLogFactory extends Factory
|
||||
{
|
||||
protected $model = ActivityLog::class;
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'type' => fake()->randomElement(ActivityTypeEnum::cases()),
|
||||
'message' => fake()->sentence(4),
|
||||
'context' => null,
|
||||
'subject_type' => null,
|
||||
'subject_id' => null,
|
||||
'logged_at' => now(),
|
||||
];
|
||||
}
|
||||
|
||||
public function type(ActivityTypeEnum $type): static
|
||||
{
|
||||
return $this->state(['type' => $type]);
|
||||
}
|
||||
|
||||
public function loggedAt(Carbon $loggedAt): static
|
||||
{
|
||||
return $this->state(['logged_at' => $loggedAt]);
|
||||
}
|
||||
|
||||
public function forSubject(Model $subject): static
|
||||
{
|
||||
return $this->state([
|
||||
'subject_type' => $subject->getMorphClass(),
|
||||
'subject_id' => $subject->getKey(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -24,22 +24,9 @@ public function definition(): array
|
|||
'title' => $this->faker->sentence(),
|
||||
'description' => $this->faker->paragraph(),
|
||||
'content' => $this->faker->paragraphs(3, true),
|
||||
'image_url' => $this->faker->imageUrl(),
|
||||
'image_url' => $this->faker->optional()->imageUrl(),
|
||||
'published_at' => $this->faker->optional()->dateTimeBetween('-1 month', 'now'),
|
||||
'author' => $this->faker->optional()->name(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* An article discovered but never validated, so publishing must fetch its data live.
|
||||
*/
|
||||
public function unvalidated(): static
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'description' => null,
|
||||
'content' => null,
|
||||
'image_url' => null,
|
||||
'validated_at' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue