Compare commits

...

106 commits
v1.3.2 ... main

Author SHA1 Message Date
7270e3311c 157 - Add Changelog
All checks were successful
Build and Push Docker Image / build (push) Successful in 7m49s
2026-08-16 23:57:38 +02:00
c640d7a33a 150 - Add dev-test nix command
All checks were successful
Build and Push Docker Image / build (push) Successful in 5m28s
2026-08-16 23:37:50 +02:00
945a27b54f Merge pull request 'release/v1.4.2' (#159) from release/v1.4.2 into main
Some checks failed
Build and Push Docker Image / build (push) Has been cancelled
Reviewed-on: #159
2026-08-16 23:36:23 +02:00
aa00950543 157 - Backfill route articles when a route is activated
All checks were successful
CI / ci (push) Successful in 2m43s
CI / ci (pull_request) Successful in 1m58s
2026-08-16 23:18:09 +02:00
ba8513c256 158 - Fix Belga feed offset=1 skipping newest article
All checks were successful
CI / ci (push) Successful in 2m12s
2026-08-16 22:53:52 +02:00
79e70ada1b 150 - Bump the README compose example to v1.4.1
All checks were successful
Build and Push Docker Image / build (push) Successful in 8m47s
2026-08-15 12:04:26 +02:00
e78af42297 150 - Add the v1.4.1 changelog section
Some checks failed
Build and Push Docker Image / build (push) Has been cancelled
2026-08-15 12:02:30 +02:00
c460db2e5b Merge pull request 'release/v1.4.1' (#154) from release/v1.4.1 into main
All checks were successful
Build and Push Base Images / images (docker/build/Dockerfile.base, fedi-feed-router-base, php8.3-1) (push) Successful in 6m33s
Build and Push Base Images / images (docker/build/Dockerfile.ci, fedi-feed-router-ci, php8.3-3) (push) Successful in 8m1s
Build and Push Docker Image / build (push) Successful in 5m53s
Reviewed-on: #154
2026-08-15 11:20:04 +02:00
85fe585f8d 147 - Bump the CI image tag to force a fresh pull
All checks were successful
CI / ci (push) Successful in 2m12s
CI / ci (pull_request) Successful in 2m5s
2026-08-15 11:10:46 +02:00
d07e58207f 147 - Base the CI image on Debian instead of Alpine 2026-08-15 11:05:59 +02:00
7eaa32f7a0 147 - Pin the CI image to a version tag instead of latest 2026-08-15 11:05:59 +02:00
5400bb0582 147 - Add gd to the CI image and declare ext-gd 2026-08-15 11:05:59 +02:00
5cd51f9b43 147 - Run CI on pull requests into release branches 2026-08-15 11:05:59 +02:00
1e120a4bac 147 - Fix the Composer cache path so it caches anything 2026-08-15 11:05:59 +02:00
209efc31b2 147 - Run CI in a prebuilt image instead of installing PHP each run 2026-08-15 11:05:59 +02:00
20bc7655d6 147 - Drop coverage from CI and run PHPUnit directly 2026-08-15 11:05:59 +02:00
ddd560b204 150 - Delete unconvertible channels instead of resolving them via Lemmy
All checks were successful
CI / ci (push) Successful in 12m7s
2026-08-15 10:35:33 +02:00
d17d98a5ec 152 - Freeze time in the publish job tests and cover the midnight boundary
All checks were successful
CI / ci (push) Successful in 11m24s
2026-08-15 10:12:41 +02:00
e58badf70e 152 - Give factories unique values for constrained columns 2026-08-15 10:07:40 +02:00
de42bdca38 Merge pull request 'Release v1.4.0' (#146) from release/v1.4.0 into main
All checks were successful
Build and Push Docker Image / build (push) Successful in 8m17s
Reviewed-on: #146
2026-08-15 00:36:52 +02:00
4f79aac325 140 - Set the v1.4.0 release date in the CHANGELOG
All checks were successful
CI / ci (push) Successful in 15m25s
CI / ci (pull_request) Successful in 32m16s
2026-08-14 21:59:40 +02:00
ced6cfcaac 140 - Rewrite the README as a project page
All checks were successful
CI / ci (push) Successful in 15m47s
2026-08-14 21:54:03 +02:00
1b95e9f8aa 140 - Fix the fallback message describing a nonexistent React frontend 2026-08-14 21:41:45 +02:00
3c86b0637e 140 - Add CHANGELOG 2026-08-14 21:36:25 +02:00
0bfe8180bb 140 - Add CONTRIBUTING 2026-08-14 21:26:10 +02:00
f7982edafe 140 - Add license 2026-08-14 21:18:01 +02:00
8e9ca0e200 140 - Drop the unused Inertia, Ziggy and Breeze dependencies 2026-08-14 21:17:45 +02:00
4e3f83142e 140 - Remove the dead Jenkinsfile and Inertia middleware 2026-08-14 21:17:31 +02:00
812c663529 139 - Make the chart key uniqueness test assert real charts 2026-08-14 21:05:13 +02:00
90ecad22a7 139 - Fix PHPStan array-shape narrowing in DashboardTest 2026-08-14 20:57:30 +02:00
6485cabdae 139 - Commit composer.lock and pin PHPStan below 2.2 2026-08-14 20:57:20 +02:00
2b87f1f3a7 141 - Add channel deletion to the Channels page 2026-08-14 00:54:17 +02:00
6270c97c29 141 - Add a cascading foreign key to article publications 2026-08-14 00:28:09 +02:00
dc64dd83b8 144 - Replace ArticleFetcher with focused fetch actions 2026-08-14 00:07:08 +02:00
eefadff873 144 - Extract the RSS and website fetch actions from ArticleFetcher 2026-08-13 23:36:07 +02:00
d58fd8a231 144 - Rename ValidationService to ValidateArticleAction 2026-08-13 23:26:58 +02:00
dd8f799445 144 - Extract CreateRouteArticlesAction from ValidationService 2026-08-13 23:16:43 +02:00
d8b85f84ed 144 - Extract SaveArticleAction from ArticleFetcher 2026-08-13 21:59:56 +02:00
c7b9cd6d0c 142 - Surface failed publishes and replace auto-retry with a manual one
Some checks failed
CI / ci (push) Failing after 11m41s
2026-08-13 21:36:57 +02:00
e16368a662 138 - Upload the thumbnail once per publish, not per retry 2026-08-13 21:06:02 +02:00
34b78e6e54 138 - Resize and host article thumbnails on the instance 2026-08-13 20:58:49 +02:00
6ea3f922da 138 - Add multipart upload support to LemmyRequest 2026-08-13 20:46:06 +02:00
0163fa53b4 137 - Add an edit option to channel cards 2026-08-13 18:44:59 +02:00
41a1be7ca4 136 - Add an edit option to feed cards 2026-08-13 18:35:19 +02:00
a8d96554a7 83 - Tighten dashboard analytics after review 2026-08-13 18:06:49 +02:00
42fab63eaf 83 - Add a recent activity panel to the dashboard 2026-08-13 17:49:50 +02:00
bf734feb4a 83 - Add a publish success rate chart to the dashboard
Some checks failed
CI / ci (push) Failing after 12m22s
2026-08-13 17:34:57 +02:00
cc45b74a63 83 - Add an approval rate chart and rework the dashboard grid 2026-08-13 00:54:29 +02:00
df5013f86d 83 - Record approval decisions and rework the dashboard layout 2026-08-13 00:40:21 +02:00
8375c948c6 83 - Add a decision timestamp to route articles 2026-08-13 00:15:36 +02:00
4b895263e2 83 - Show the fetched-vs-published trend on the dashboard 2026-08-13 00:10:34 +02:00
7e6e6ce4e1 83 - Add Chart.js and register the trend chart component 2026-08-12 23:52:55 +02:00
5f4ef40a76 83 - Bundle Livewire through Vite instead of injected scripts 2026-08-12 23:42:59 +02:00
5b4e311d2d 83 - Add a daily fetched-vs-published trend stat 2026-08-12 23:29:36 +02:00
f6067eec38 83 - Add a SeriesStat contract for time-series dashboard panels 2026-08-12 23:14:19 +02:00
55f76d0d09 83 - Add a per-channel publication breakdown to the dashboard 2026-08-12 00:41:10 +02:00
8a1001d274 83 - Add a per-feed article breakdown to the dashboard 2026-08-12 00:32:46 +02:00
8a98990aea 83 - Isolate dashboard panels with Livewire islands 2026-08-12 00:20:46 +02:00
a6eff35586 83 - Drive dashboard and API stats from a date range 2026-08-12 00:00:49 +02:00
ef5346ed70 83 - Add a DateRange value object with named presets 2026-08-11 23:47:51 +02:00
c40e167ab5 95 - Add a platform credential health check 2026-08-11 00:44:26 +02:00
034d0f7eac 111 - Add keyboard accessibility to the shared form modal 2026-08-10 23:59:55 +02:00
b7ec75ff65 120 - Set the application name in the example environment 2026-08-10 23:41:07 +02:00
4257bd7e6e 121 - Replace logo and favicon 2026-08-10 23:34:48 +02:00
602173a0ad 91 - Ignore codewhale 2026-08-10 23:24:24 +02:00
cb63a05aa5 90 - Cap the number of articles published per day 2026-08-10 23:12:33 +02:00
3b4200a0e5 91 - Show the feed name on article activity entries 2026-08-10 21:43:47 +02:00
d3e589c36c 91 - Register event listeners once instead of twice 2026-08-10 21:16:34 +02:00
fbcf4faa9f 91 - Prune activity logs after 90 days 2026-08-10 20:46:07 +02:00
c986f000f6 91 - Summarize and display activity 2026-08-10 20:45:52 +02:00
f8084d144c 91 - Record activity from fetch, validate and publish paths 2026-08-10 20:44:57 +02:00
c7de5bc3df 91 - Add activity log table, model and event pipeline 2026-08-10 20:44:30 +02:00
6a9d909525 88 - Add dark theme with toggle and remove dead Breeze navigation 2026-08-10 19:40:22 +02:00
0626a546c9 109 - Replace deprecated flex-shrink-0 and backdrop-blur-sm aliases 2026-08-10 01:47:30 +02:00
b7d6e3b55b 109 - Replace focus:outline-none with focus:outline-hidden 2026-08-10 01:46:02 +02:00
f90d271735 109 - Rename bare rounded to rounded-sm 2026-08-10 01:43:41 +02:00
549f83a662 109 - Rename bare shadow to shadow-sm 2026-08-10 01:41:58 +02:00
2823c5eeb3 109 - Rename shadow-sm to shadow-xs 2026-08-10 01:37:18 +02:00
2f86326d5c 116 - Pin the premise that a fully-known feed still returns articles 2026-08-10 01:25:17 +02:00
548a55af05 116 - Warn when a feed fetch returns no articles 2026-08-10 01:02:16 +02:00
6f5b15a332 119 - Extract publish eligibility into a RouteArticle scope 2026-08-10 00:20:53 +02:00
ddd6514a77 119 - Back off and give up on repeatedly failing publishes 2026-08-10 00:05:17 +02:00
16353fe60a 119 - Fail publishing when article content cannot be recovered 2026-08-09 23:28:59 +02:00
ecb12ddfc7 119 - Publish articles from stored data instead of re-fetching 2026-08-09 20:41:07 +02:00
433aa79007 119 - Store article thumbnail in image_url during validation 2026-08-09 15:22:02 +02:00
798ddf9862 113 - Cover route eyebrow ordering and fix accordion labelling and filter width 2026-08-09 13:14:17 +02:00
36b46b4d2e 113 - Scope clearing pending articles to the active feed filter 2026-08-09 10:37:54 +02:00
817219df61 113 - Filter articles by feed on both tabs 2026-08-09 09:41:47 +02:00
03282d2463 113 - Collapse pending articles into per-feed accordions 2026-08-09 02:19:31 +02:00
e0056864af 113 - Add per-feed colour dots to article routing 2026-08-07 02:14:58 +02:00
4274b69018 113 - Promote article routing above the headline 2026-08-07 01:23:09 +02:00
ac8845e9c9 127 - Remove coverage PR comment from CI workflow
All checks were successful
CI / ci (push) Successful in 18m15s
CI / ci (pull_request) Successful in 31m17s
Build and Push Docker Image / build (push) Successful in 4m33s
2026-08-06 21:31:50 +02:00
d0d81e524e 114 - Select channel communities from the instance instead of typing a slug
Some checks failed
CI / ci (pull_request) Failing after 26m6s
CI / ci (push) Successful in 21m12s
2026-08-06 00:20:49 +02:00
358171c8cc 123 - Start the scheduler in the production container 2026-08-02 17:57:12 +02:00
b527813721 123 - Key duplicate mirror by local channel and distinguish skipped publishes 2026-08-02 17:16:30 +02:00
b2d504f503 123 - Prevent duplicate Lemmy posts from concurrent publish attempts 2026-08-02 15:45:26 +02:00
923a0736a8 115 - Add regression tests for the Belga feed migration
All checks were successful
CI / ci (push) Successful in 10m5s
CI / ci (pull_request) Successful in 11m44s
Build and Push Docker Image / build (push) Successful in 5m1s
2026-08-02 14:03:00 +02:00
1140e527f1 115 - Read Belga API url from config and sync the feed row via migration 2026-08-02 12:55:53 +02:00
7d745b036a 115 - Satisfy PHPStan on Belga parser and fixture helpers
All checks were successful
CI / ci (push) Successful in 1h26m46s
CI / ci (pull_request) Successful in 10m39s
Build and Push Docker Image / build (push) Successful in 4m22s
2026-08-02 02:04:23 +02:00
ac1b461e41 115 - Satisfy PHPStan on Belga parser and fixture helpers
Some checks failed
CI / ci (push) Failing after 31m11s
CI / ci (pull_request) Failing after 28m46s
2026-08-02 00:08:14 +02:00
3bded659d2 120 - Hardcode app display name instead of deriving it from APP_NAME
Some checks failed
CI / ci (push) Failing after 9m35s
CI / ci (pull_request) Failing after 19m44s
2026-08-01 23:43:52 +02:00
253700312e 117 - Decode HTML entities in extracted thumbnail URLs 2026-08-01 17:13:32 +02:00
299ec3151a 115 - Switch Belga provider to website discovery via JSON API 2026-08-01 16:05:45 +02:00
2a4d4ad84d 115 - Add Belga JSON discovery parser for press-release API 2026-08-01 13:43:50 +02:00
00366ffeaa 108 - Fix modal rendering and extract shared form modal component
All checks were successful
CI / ci (push) Successful in 31m55s
CI / ci (pull_request) Successful in 19m52s
Build and Push Docker Image / build (push) Successful in 5m2s
2026-08-01 00:11:06 +02:00
7ec5283b4c 108 - Fix modal backdrops by migrating Tailwind v3 opacity utilities to v4 2026-07-31 21:55:55 +02:00
273 changed files with 23440 additions and 2542 deletions

View file

@ -1,4 +1,4 @@
APP_NAME=Laravel APP_NAME="Fedi Feed Router"
APP_ENV=local APP_ENV=local
APP_KEY= APP_KEY=
APP_DEBUG=true APP_DEBUG=true

View file

@ -4,27 +4,20 @@ on:
push: push:
branches: ['release/*'] branches: ['release/*']
pull_request: pull_request:
branches: [main] branches: [main, 'release/*']
jobs: jobs:
ci: ci:
runs-on: docker runs-on: docker
container: container:
image: catthehacker/ubuntu:act-latest image: forge.lvl0.xyz/lvl0/fedi-feed-router-ci:php8.3-3
steps: steps:
- uses: https://data.forgejo.org/actions/checkout@v4 - 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 - name: Cache Composer dependencies
uses: https://data.forgejo.org/actions/cache@v4 uses: https://data.forgejo.org/actions/cache@v4
with: with:
path: ~/.composer/cache path: ~/.cache/composer
key: composer-${{ hashFiles('composer.lock') }} key: composer-${{ hashFiles('composer.lock') }}
restore-keys: composer- restore-keys: composer-
@ -38,76 +31,7 @@ jobs:
run: vendor/bin/pint --test run: vendor/bin/pint --test
- name: Static analysis - name: Static analysis
run: vendor/bin/phpstan analyse run: vendor/bin/phpstan analyse --memory-limit=1G
- name: Tests - name: Tests
run: php artisan test --coverage-clover coverage.xml --coverage-text run: php -d memory_limit=512M vendor/bin/phpunit
- 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

View file

@ -0,0 +1,47 @@
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
View file

@ -19,8 +19,10 @@ npm-debug.log
yarn-error.log yarn-error.log
/package-lock.json /package-lock.json
/auth.json /auth.json
/composer.lock
/.idea /.idea
/coverage-report* /coverage-report*
/coverage.xml /coverage.xml
/.php-cs-fixer.dist.php /.php-cs-fixer.dist.php
/.php-cs-fixer.cache
/.codewhale
.aider*

63
CHANGELOG.md Normal file
View file

@ -0,0 +1,63 @@
# 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)

95
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,95 @@
# 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.

View file

@ -101,6 +101,9 @@ php artisan db:seed --force || echo "Seeders failed or already run"
# Start Horizon in the background # Start Horizon in the background
php artisan horizon & php artisan horizon &
# Start the scheduler in the background
php artisan schedule:work &
# Start FrankenPHP # Start FrankenPHP
exec frankenphp run --config /etc/caddy/Caddyfile exec frankenphp run --config /etc/caddy/Caddyfile
EOF EOF

View file

@ -114,6 +114,9 @@ npm run dev &
# Start Horizon (queue worker) in background # Start Horizon (queue worker) in background
php artisan horizon & php artisan horizon &
# Scheduler left off in dev on purpose; run schedule:work by hand when needed.
# php artisan schedule:work &
# Start FrankenPHP # Start FrankenPHP
exec frankenphp run --config /etc/caddy/Caddyfile exec frankenphp run --config /etc/caddy/Caddyfile
EOF EOF

241
Jenkinsfile vendored
View file

@ -1,241 +0,0 @@
pipeline {
agent any
environment {
APP_ENV = 'testing'
DB_CONNECTION = 'mysql'
DB_HOST = 'mysql'
DB_PORT = '3306'
DB_DATABASE = 'ffr_testing'
DB_USERNAME = 'ffr_user'
DB_PASSWORD = 'ffr_password'
CACHE_STORE = 'array'
SESSION_DRIVER = 'array'
QUEUE_CONNECTION = 'sync'
}
stages {
stage('Checkout') {
steps {
checkout scm
}
}
stage('Setup Environment') {
steps {
script {
sh '''
echo "Setting up environment for testing..."
cp .env.example .env.testing
echo "APP_ENV=testing" >> .env.testing
echo "DB_CONNECTION=${DB_CONNECTION}" >> .env.testing
echo "DB_HOST=${DB_HOST}" >> .env.testing
echo "DB_PORT=${DB_PORT}" >> .env.testing
echo "DB_DATABASE=${DB_DATABASE}" >> .env.testing
echo "DB_USERNAME=${DB_USERNAME}" >> .env.testing
echo "DB_PASSWORD=${DB_PASSWORD}" >> .env.testing
echo "CACHE_STORE=${CACHE_STORE}" >> .env.testing
echo "SESSION_DRIVER=${SESSION_DRIVER}" >> .env.testing
echo "QUEUE_CONNECTION=${QUEUE_CONNECTION}" >> .env.testing
'''
}
}
}
stage('Install Dependencies') {
parallel {
stage('PHP Dependencies') {
steps {
sh '''
echo "Installing PHP dependencies..."
composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev
'''
}
}
stage('Node Dependencies') {
steps {
sh '''
echo "Installing Node.js dependencies..."
npm ci
'''
}
}
}
}
stage('Generate Application Key') {
steps {
sh '''
php artisan key:generate --env=testing --force
'''
}
}
stage('Database Setup') {
steps {
sh '''
echo "Setting up test database..."
php artisan migrate:fresh --env=testing --force
php artisan config:clear --env=testing
'''
}
}
stage('Code Quality Checks') {
parallel {
stage('PHP Syntax Check') {
steps {
sh '''
echo "Checking PHP syntax..."
find . -name "*.php" -not -path "./vendor/*" -not -path "./node_modules/*" -exec php -l {} \\;
'''
}
}
stage('PHPStan Analysis') {
steps {
script {
try {
sh '''
if [ -f "phpstan.neon" ]; then
echo "Running PHPStan static analysis..."
./vendor/bin/phpstan analyse --no-progress --error-format=table
else
echo "PHPStan configuration not found, skipping static analysis"
fi
'''
} catch (Exception e) {
unstable(message: "PHPStan found issues")
}
}
}
}
stage('Security Audit') {
steps {
script {
try {
sh '''
echo "Running security audit..."
composer audit
'''
} catch (Exception e) {
unstable(message: "Security vulnerabilities found")
}
}
}
}
}
}
stage('Unit Tests') {
steps {
sh '''
echo "Running Unit Tests..."
php artisan test tests/Unit/ --env=testing --stop-on-failure
'''
}
post {
always {
publishTestResults testResultsPattern: 'tests/Unit/results/*.xml'
}
}
}
stage('Feature Tests') {
steps {
sh '''
echo "Running Feature Tests..."
php artisan test tests/Feature/ --env=testing --stop-on-failure
'''
}
post {
always {
publishTestResults testResultsPattern: 'tests/Feature/results/*.xml'
}
}
}
stage('Full Regression Test Suite') {
steps {
sh '''
echo "Running comprehensive regression test suite..."
chmod +x ./run-regression-tests.sh
./run-regression-tests.sh
'''
}
post {
always {
// Archive test results
archiveArtifacts artifacts: 'tests/reports/**/*', allowEmptyArchive: true
// Publish coverage reports if available
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: 'coverage',
reportFiles: 'index.html',
reportName: 'Coverage Report'
])
}
}
}
stage('Performance Tests') {
steps {
script {
try {
sh '''
echo "Running performance tests..."
# Test memory usage
php -d memory_limit=256M artisan test tests/Feature/DatabaseIntegrationTest.php --env=testing
# Test response times for API endpoints
time php artisan test tests/Feature/ApiEndpointRegressionTest.php --env=testing
'''
} catch (Exception e) {
unstable(message: "Performance tests indicated potential issues")
}
}
}
}
stage('Build Assets') {
when {
anyOf {
branch 'main'
branch 'develop'
}
}
steps {
sh '''
echo "Building production assets..."
npm run build
'''
}
}
}
post {
always {
// Clean up
sh '''
echo "Cleaning up..."
rm -f .env.testing
'''
}
success {
echo '✅ All regression tests passed successfully!'
// Notify success (customize as needed)
// slackSend channel: '#dev-team', color: 'good', message: "Regression tests passed for ${env.JOB_NAME} - ${env.BUILD_NUMBER}"
}
failure {
echo '❌ Regression tests failed!'
// Notify failure (customize as needed)
// slackSend channel: '#dev-team', color: 'danger', message: "Regression tests failed for ${env.JOB_NAME} - ${env.BUILD_NUMBER}"
}
unstable {
echo '⚠️ Tests completed with warnings'
}
}
}

661
LICENSE Normal file
View file

@ -0,0 +1,661 @@
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
View file

@ -1,26 +1,77 @@
# FFR (Feed to Fediverse Router) # FFR: Feed to Fediverse Router
A Laravel-based application for routing RSS/Atom feeds to Fediverse platforms like Lemmy. Built with Laravel, Livewire, and FrankenPHP for a modern, single-container deployment. [![CI](https://forge.lvl0.xyz/lvl0/fedi-feed-router/badges/workflows/ci.yml/badge.svg)](https://forge.lvl0.xyz/lvl0/fedi-feed-router/actions)
[![Release](https://img.shields.io/gitea/v/release/lvl0/fedi-feed-router?gitea_url=https%3A%2F%2Fforge.lvl0.xyz)](https://forge.lvl0.xyz/lvl0/fedi-feed-router/releases)
[![License](https://img.shields.io/badge/license-AGPL--3.0-blue)](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
![Dashboard](docs/screenshots/dashboard-dark.png)
The dashboard, showing article volume over a selected range, approval and publish
success rates, and per-feed breakdowns.
![Articles](docs/screenshots/articles-light.png)
The review queue. Each row is one feed and community pairing, grouped by feed,
with the routing shown above the headline.
## Features ## Features
- **Feed aggregation** - Fetch articles from multiple RSS/Atom feeds - **Article routing**: map each source to one or more Lemmy communities, with
- **Fediverse publishing** - Automatically post to Lemmy communities optional keyword filtering
- **Route configuration** - Map feeds to specific channels with keywords - **Approval workflow**: review articles before they publish, or let them go out
- **Approval workflow** - Optional manual approval before publishing automatically
- **Queue processing** - Background job handling with Laravel Horizon - **Publishing controls**: a global interval and an optional daily cap, so a
- **Single container deployment** - Simplified hosting with FrankenPHP 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.
## Self-hosting ## Self-hosting
The production image is available at `forge.lvl0.xyz/lvl0/fedi-feed-router:latest`. 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.
### docker-compose.yml ### docker-compose.yml
```yaml ```yaml
services: services:
app: app:
image: forge.lvl0.xyz/lvl0/fedi-feed-router:latest image: forge.lvl0.xyz/lvl0/fedi-feed-router:v1.4.1
container_name: ffr_app container_name: ffr_app
restart: always restart: always
ports: ports:
@ -70,42 +121,59 @@ ### docker-compose.yml
app_storage: app_storage:
``` ```
### Environment Variables ### Environment variables
| Variable | Required | Description | | Variable | Required | Description |
|----------|----------|-------------| |----------|----------|-------------|
| `APP_KEY` | Yes | Encryption key. Generate with: `echo "base64:$(openssl rand -base64 32)"` | | `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_DATABASE` | Yes | Database name |
| `DB_USERNAME` | Yes | Database user | | `DB_USERNAME` | Yes | Database user |
| `DB_PASSWORD` | Yes | Database password | | `DB_PASSWORD` | Yes | Database password |
| `DB_ROOT_PASSWORD` | Yes | MariaDB root 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 ## Development
### NixOS / Nix ### NixOS / Nix
```bash ```bash
git clone https://forge.lvl0.xyz/lvl0/fedi-feed-router.git git clone https://forge.lvl0.xyz/lvl0/fedi-feed-router.git
cd ffr cd fedi-feed-router
nix-shell nix-shell
``` ```
The shell will display available commands and optionally start the containers for you. The shell prints the available commands and can start the containers for you.
#### Available Commands
| Command | Description | | Command | Description |
|---------|-------------| |---------|-------------|
| `dev-up` | Start development environment | | `dev-up` | Start the development environment |
| `dev-down` | Stop development environment | | `dev-down` | Stop the development environment |
| `dev-restart` | Restart containers | | `dev-restart` | Restart the containers |
| `dev-logs` | Follow app logs | | `dev-rebuild` | Rebuild the images |
| `dev-logs-db` | Follow database logs | | `dev-shell` | Enter the app container |
| `dev-shell` | Enter app container | | `dev-artisan <cmd>` | Run an artisan command |
| `dev-artisan <cmd>` | Run artisan commands | | `dev-logs` | Follow the application log |
| `dev-logs-db` | Follow the database log |
#### Services
| Service | URL | | Service | URL |
|---------|-----| |---------|-----|
@ -114,14 +182,22 @@ #### Services
| MariaDB | localhost:3307 | | MariaDB | localhost:3307 |
| Redis | localhost:6380 | | Redis | localhost:6380 |
### Other Platforms ### Other platforms
Contributions welcome for development setup instructions on 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 ## License
This project is open-source software licensed under the [AGPL-3.0 license](LICENSE). FFR is free software, licensed under the [GNU AGPL-3.0](LICENSE).
## Support
For issues and questions, please use [Issues](https://forge.lvl0.xyz/lvl0/fedi-feed-router/issues).

View file

@ -0,0 +1,35 @@
<?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);
});
}
}

View file

@ -10,7 +10,7 @@
class CreateChannelAction class CreateChannelAction
{ {
public function execute(string $name, int $platformInstanceId, ?int $languageId = null, ?string $description = null): PlatformChannel public function execute(string $name, int $communityId, int $platformInstanceId, ?int $languageId = null, ?string $description = null): PlatformChannel
{ {
$platformInstance = PlatformInstance::findOrFail($platformInstanceId); $platformInstance = PlatformInstance::findOrFail($platformInstanceId);
@ -22,10 +22,10 @@ public function execute(string $name, int $platformInstanceId, ?int $languageId
throw new RuntimeException('No active platform accounts found for this instance. Please create a platform account first.'); throw new RuntimeException('No active platform accounts found for this instance. Please create a platform account first.');
} }
return DB::transaction(function () use ($name, $platformInstanceId, $languageId, $description, $activeAccounts) { return DB::transaction(function () use ($name, $communityId, $platformInstanceId, $languageId, $description, $activeAccounts) {
$channel = PlatformChannel::create([ $channel = PlatformChannel::create([
'platform_instance_id' => $platformInstanceId, 'platform_instance_id' => $platformInstanceId,
'channel_id' => $name, 'channel_id' => $communityId,
'name' => $name, 'name' => $name,
'display_name' => ucfirst($name), 'display_name' => ucfirst($name),
'description' => $description, 'description' => $description,

View file

@ -2,6 +2,7 @@
namespace App\Actions; namespace App\Actions;
use App\Enums\AccountStatusEnum;
use App\Exceptions\PlatformAuthException; use App\Exceptions\PlatformAuthException;
use App\Models\PlatformAccount; use App\Models\PlatformAccount;
use App\Models\PlatformInstance; use App\Models\PlatformInstance;
@ -46,7 +47,7 @@ public function execute(string $instanceDomain, string $username, string $passwo
'api_token' => $authResponse['jwt'] ?? null, 'api_token' => $authResponse['jwt'] ?? null,
], ],
'is_active' => true, 'is_active' => true,
'status' => 'active', 'status' => AccountStatusEnum::HEALTHY,
]); ]);
}); });
} }

View file

@ -2,6 +2,7 @@
namespace App\Actions; namespace App\Actions;
use App\Events\RouteActivated;
use App\Models\Route; use App\Models\Route;
class CreateRouteAction class CreateRouteAction
@ -12,7 +13,7 @@ class CreateRouteAction
*/ */
public function execute(int $feedId, int $platformChannelId, int $priority = 0, bool $isActive = true): Route public function execute(int $feedId, int $platformChannelId, int $priority = 0, bool $isActive = true): Route
{ {
return Route::firstOrCreate( $route = Route::firstOrCreate(
[ [
'feed_id' => $feedId, 'feed_id' => $feedId,
'platform_channel_id' => $platformChannelId, 'platform_channel_id' => $platformChannelId,
@ -22,5 +23,11 @@ public function execute(int $feedId, int $platformChannelId, int $priority = 0,
'is_active' => $isActive, 'is_active' => $isActive,
] ]
); );
if ($route->wasRecentlyCreated && $route->is_active) {
RouteActivated::dispatch($route->feed_id, $route->platform_channel_id);
}
return $route;
} }
} }

View file

@ -0,0 +1,81 @@
<?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();
}
}

View file

@ -0,0 +1,36 @@
<?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 [];
}
}
}

View file

@ -0,0 +1,36 @@
<?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();
}
}

View file

@ -0,0 +1,64 @@
<?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();
}
}
}

View file

@ -0,0 +1,53 @@
<?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();
}
}
}

View file

@ -0,0 +1,167 @@
<?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,
);
}
}

View file

@ -0,0 +1,52 @@
<?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';
}
}

View file

@ -0,0 +1,48 @@
<?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();
}
}

View file

@ -0,0 +1,53 @@
<?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),
]);
}
}

View file

@ -0,0 +1,47 @@
<?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);
}
}

View file

@ -0,0 +1,51 @@
<?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,
);
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace App\Dashboard\Stats;
class Breakdown
{
public function __construct(
public readonly string $label,
public readonly int $count,
) {}
}

View file

@ -0,0 +1,25 @@
<?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;
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Dashboard\Stats;
use App\Support\DateRange;
interface BreakdownStat extends Stat
{
public function for(DateRange $range): BreakdownResult;
}

View file

@ -0,0 +1,22 @@
<?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;
}

View file

@ -0,0 +1,47 @@
<?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);
}
}

View file

@ -0,0 +1,53 @@
<?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),
]);
}
}

View file

@ -0,0 +1,31 @@
<?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;
}
}

View file

@ -0,0 +1,58 @@
<?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;
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Dashboard\Stats;
use App\Support\DateRange;
interface SeriesStat extends Stat
{
public function for(DateRange $range): SeriesResult;
}

View file

@ -0,0 +1,13 @@
<?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;
}

View file

@ -0,0 +1,19 @@
<?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',
};
}
}

View file

@ -0,0 +1,39 @@
<?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;
}
}

View file

@ -7,4 +7,20 @@ enum ApprovalStatusEnum: string
case PENDING = 'pending'; case PENDING = 'pending';
case APPROVED = 'approved'; case APPROVED = 'approved';
case REJECTED = 'rejected'; 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()),
));
}
} }

View file

@ -0,0 +1,36 @@
<?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)];
}
}

View file

@ -6,6 +6,7 @@ enum NotificationTypeEnum: string
{ {
case GENERAL = 'general'; case GENERAL = 'general';
case FEED_STALE = 'feed_stale'; case FEED_STALE = 'feed_stale';
case FEED_EMPTY = 'feed_empty';
case PUBLISH_FAILED = 'publish_failed'; case PUBLISH_FAILED = 'publish_failed';
case CREDENTIAL_EXPIRED = 'credential_expired'; case CREDENTIAL_EXPIRED = 'credential_expired';
@ -14,6 +15,7 @@ public function label(): string
return match ($this) { return match ($this) {
self::GENERAL => 'General', self::GENERAL => 'General',
self::FEED_STALE => 'Feed Stale', self::FEED_STALE => 'Feed Stale',
self::FEED_EMPTY => 'Feed Empty',
self::PUBLISH_FAILED => 'Publish Failed', self::PUBLISH_FAILED => 'Publish Failed',
self::CREDENTIAL_EXPIRED => 'Credential Expired', self::CREDENTIAL_EXPIRED => 'Credential Expired',
}; };

View file

@ -7,5 +7,23 @@ enum PublishStatusEnum: string
case UNPUBLISHED = 'unpublished'; case UNPUBLISHED = 'unpublished';
case PUBLISHING = 'publishing'; case PUBLISHING = 'publishing';
case PUBLISHED = 'published'; case PUBLISHED = 'published';
case SKIPPED = 'skipped';
case ERROR = 'error'; 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()),
));
}
} }

View file

@ -0,0 +1,20 @@
<?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,
) {}
}

View file

@ -0,0 +1,17 @@
<?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,
) {}
}

View file

@ -2,10 +2,11 @@
namespace App\Http\Controllers\Api\V1; namespace App\Http\Controllers\Api\V1;
use App\Models\Article;
use App\Services\DashboardStatsService; use App\Services\DashboardStatsService;
use App\Support\DateRange;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
class DashboardController extends BaseController class DashboardController extends BaseController
{ {
@ -18,23 +19,26 @@ public function __construct(
*/ */
public function stats(Request $request): JsonResponse public function stats(Request $request): JsonResponse
{ {
$period = $request->get('period', 'today'); $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');
try { 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([ return $this->sendResponse([
'article_stats' => $articleStats, 'article_stats' => $this->dashboardStatsService->getStats($range),
'system_stats' => $systemStats, 'system_stats' => $this->dashboardStatsService->getSystemStats(),
'available_periods' => $availablePeriods, 'range' => [
'current_period' => $period, 'from' => $range->from->toDateString(),
'to' => $range->to->toDateString(),
],
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
return $this->sendError('Failed to fetch dashboard stats: '.$e->getMessage(), [], 500); return $this->sendError('Failed to fetch dashboard stats: '.$e->getMessage(), [], 500);

View file

@ -7,6 +7,8 @@
use App\Http\Resources\PlatformChannelResource; use App\Http\Resources\PlatformChannelResource;
use App\Models\PlatformAccount; use App\Models\PlatformAccount;
use App\Models\PlatformChannel; use App\Models\PlatformChannel;
use App\Models\PlatformInstance;
use App\Services\Platform\CommunityDirectory;
use Exception; use Exception;
use Illuminate\Database\UniqueConstraintViolationException; use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@ -40,8 +42,12 @@ public function store(StorePlatformChannelRequest $request, CreateChannelAction
try { try {
$validated = $request->validated(); $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( $channel = $createChannelAction->execute(
$validated['name'], $name,
(int) $validated['channel_id'],
$validated['platform_instance_id'], $validated['platform_instance_id'],
$validated['language_id'] ?? null, $validated['language_id'] ?? null,
$validated['description'] ?? null, $validated['description'] ?? null,

View file

@ -71,7 +71,10 @@ public function reject(RouteArticle $routeArticle): JsonResponse
public function restore(RouteArticle $routeArticle): JsonResponse public function restore(RouteArticle $routeArticle): JsonResponse
{ {
try { try {
$routeArticle->update(['approval_status' => ApprovalStatusEnum::PENDING]); $routeArticle->update([
'approval_status' => ApprovalStatusEnum::PENDING,
'decided_at' => null,
]);
return $this->sendResponse( return $this->sendResponse(
new RouteArticleResource($routeArticle->fresh(['article.feed', 'feed', 'platformChannel'])), new RouteArticleResource($routeArticle->fresh(['article.feed', 'feed', 'platformChannel'])),
@ -88,7 +91,10 @@ public function clear(): JsonResponse
$count = RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)->count(); $count = RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)->count();
RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING) RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)
->update(['approval_status' => ApprovalStatusEnum::REJECTED]); ->update([
'approval_status' => ApprovalStatusEnum::REJECTED,
'decided_at' => now(),
]);
return $this->sendResponse( return $this->sendResponse(
['rejected_count' => $count], ['rejected_count' => $count],

View file

@ -19,6 +19,7 @@ public function index(): JsonResponse
'article_processing_enabled' => Setting::isArticleProcessingEnabled(), 'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(), 'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
'article_publishing_interval' => Setting::getArticlePublishingInterval(), 'article_publishing_interval' => Setting::getArticlePublishingInterval(),
'daily_publish_cap' => Setting::getDailyPublishCap(),
]; ];
return $this->sendResponse($settings, 'Settings retrieved successfully.'); return $this->sendResponse($settings, 'Settings retrieved successfully.');
@ -37,6 +38,7 @@ public function update(Request $request): JsonResponse
'article_processing_enabled' => 'boolean', 'article_processing_enabled' => 'boolean',
'publishing_approvals_enabled' => 'boolean', 'publishing_approvals_enabled' => 'boolean',
'article_publishing_interval' => 'integer|min:0', 'article_publishing_interval' => 'integer|min:0',
'daily_publish_cap' => 'integer|min:0',
]); ]);
if (isset($validated['article_processing_enabled'])) { if (isset($validated['article_processing_enabled'])) {
@ -51,10 +53,15 @@ public function update(Request $request): JsonResponse
Setting::setArticlePublishingInterval($validated['article_publishing_interval']); Setting::setArticlePublishingInterval($validated['article_publishing_interval']);
} }
if (isset($validated['daily_publish_cap'])) {
Setting::setDailyPublishCap($validated['daily_publish_cap']);
}
$updatedSettings = [ $updatedSettings = [
'article_processing_enabled' => Setting::isArticleProcessingEnabled(), 'article_processing_enabled' => Setting::isArticleProcessingEnabled(),
'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(), 'publishing_approvals_enabled' => Setting::isPublishingApprovalsEnabled(),
'article_publishing_interval' => Setting::getArticlePublishingInterval(), 'article_publishing_interval' => Setting::getArticlePublishingInterval(),
'daily_publish_cap' => Setting::getDailyPublishCap(),
]; ];
return $this->sendResponse( return $this->sendResponse(

View file

@ -1,42 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
/**
* The root template that's loaded on the first page visit.
*
* @see https://inertiajs.com/server-side-setup#root-template
*
* @var string
*/
protected $rootView = 'app';
/**
* Determines the current asset version.
*
* @see https://inertiajs.com/asset-versioning
*/
public function version(Request $request): ?string
{
return parent::version($request);
}
/**
* Define the props that are shared by default.
*
* @see https://inertiajs.com/shared-data
*
* @return array<string, mixed>
*/
public function share(Request $request): array
{
return array_merge(parent::share($request), [
//
]);
}
}

View file

@ -2,6 +2,9 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Models\PlatformInstance;
use App\Services\Platform\CommunityDirectory;
use Exception;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
@ -17,19 +20,22 @@ public function authorize(): bool
*/ */
public function rules(): array 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 [ return [
'platform_instance_id' => 'required|exists:platform_instances,id', 'platform_instance_id' => 'required|exists:platform_instances,id',
// name doubles as the Lemmy community slug (CreateChannelAction copies it 'channel_id' => ['required', 'integer', ...$communityRules],
// 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', 'language_id' => 'nullable|exists:languages,id',
'description' => 'nullable|string', 'description' => 'nullable|string',
]; ];
@ -41,8 +47,24 @@ public function rules(): array
public function messages(): array public function messages(): array
{ {
return [ return [
'name.regex' => 'The name must be a valid community slug (lowercase letters, numbers, and underscores only).', 'channel_id.in' => 'That community does not exist on the selected instance.',
'name.unique' => 'A channel with this name already exists for this instance.', 'channel_id.unique' => 'A channel for this community already exists.',
]; ];
} }
/**
* @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();
}
} }

View file

@ -2,9 +2,15 @@
namespace App\Jobs; 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\Feed;
use App\Services\Article\ArticleFetcher; use App\Models\Notification;
use App\Services\Log\LogSaver; use App\Services\Log\LogSaver;
use App\Services\Notification\NotificationService;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable; use Illuminate\Foundation\Queue\Queueable;
@ -20,7 +26,7 @@ public function __construct(
$this->onQueue('feed-discovery'); $this->onQueue('feed-discovery');
} }
public function handle(LogSaver $logSaver, ArticleFetcher $articleFetcher): void public function handle(LogSaver $logSaver, FetchFeedArticlesAction $fetchFeedArticles, NotificationService $notificationService): void
{ {
$logSaver->info('Starting feed article fetch', null, [ $logSaver->info('Starting feed article fetch', null, [
'feed_id' => $this->feed->id, 'feed_id' => $this->feed->id,
@ -28,7 +34,7 @@ public function handle(LogSaver $logSaver, ArticleFetcher $articleFetcher): void
'feed_url' => $this->feed->url, 'feed_url' => $this->feed->url,
]); ]);
$articles = $articleFetcher->getArticlesFromFeed($this->feed); $articles = $fetchFeedArticles->execute($this->feed);
$logSaver->info('Feed article fetch completed', null, [ $logSaver->info('Feed article fetch completed', null, [
'feed_id' => $this->feed->id, 'feed_id' => $this->feed->id,
@ -37,6 +43,48 @@ public function handle(LogSaver $logSaver, ArticleFetcher $articleFetcher): void
]); ]);
$this->feed->update(['last_fetched_at' => now()]); $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 public static function dispatchForAllActiveFeeds(): void

View file

@ -0,0 +1,79 @@
<?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,
);
}
}

View file

@ -0,0 +1,19 @@
<?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();
}
}

View file

@ -2,19 +2,14 @@
namespace App\Jobs; namespace App\Jobs;
use App\Actions\PublishRouteArticleAction;
use App\Enums\ApprovalStatusEnum; use App\Enums\ApprovalStatusEnum;
use App\Enums\LogLevelEnum; use App\Enums\LogLevelEnum;
use App\Enums\NotificationSeverityEnum;
use App\Enums\NotificationTypeEnum;
use App\Enums\PublishStatusEnum;
use App\Events\ActionPerformed; use App\Events\ActionPerformed;
use App\Exceptions\PublishException; use App\Exceptions\PublishException;
use App\Models\ArticlePublication; use App\Models\ArticlePublication;
use App\Models\RouteArticle; use App\Models\RouteArticle;
use App\Models\Setting; 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\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable; use Illuminate\Foundation\Queue\Queueable;
@ -38,8 +33,12 @@ public function __construct()
* *
* @throws PublishException * @throws PublishException
*/ */
public function handle(ArticleFetcher $articleFetcher, ArticlePublishingService $publishingService, NotificationService $notificationService): void public function handle(PublishRouteArticleAction $publishRouteArticle): void
{ {
if ($this->dailyCapReached()) {
return;
}
$interval = Setting::getArticlePublishingInterval(); $interval = Setting::getArticlePublishingInterval();
if ($interval > 0) { if ($interval > 0) {
@ -52,6 +51,7 @@ public function handle(ArticleFetcher $articleFetcher, ArticlePublishingService
// Get the oldest approved route_article that hasn't been published to its channel yet // Get the oldest approved route_article that hasn't been published to its channel yet
$routeArticle = RouteArticle::where('approval_status', ApprovalStatusEnum::APPROVED) $routeArticle = RouteArticle::where('approval_status', ApprovalStatusEnum::APPROVED)
->dueForPublishing()
->whereDoesntHave('article.articlePublications', function ($query) { ->whereDoesntHave('article.articlePublications', function ($query) {
$query->whereColumn('article_publications.platform_channel_id', 'route_articles.platform_channel_id'); $query->whereColumn('article_publications.platform_channel_id', 'route_articles.platform_channel_id');
}) })
@ -72,52 +72,17 @@ public function handle(ArticleFetcher $articleFetcher, ArticlePublishingService
'route' => $routeArticle->feed_id.'-'.$routeArticle->platform_channel_id, 'route' => $routeArticle->feed_id.'-'.$routeArticle->platform_channel_id,
]); ]);
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHING]); $publishRouteArticle->execute($routeArticle);
}
try { private function dailyCapReached(): bool
$extractedData = $articleFetcher->fetchArticleData($article); {
$publication = $publishingService->publishRouteArticle($routeArticle, $extractedData); $cap = Setting::getDailyPublishCap();
if ($publication) { if ($cap <= 0) {
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHED]); return false;
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;
} }
return ArticlePublication::where('published_at', '>=', now()->startOfDay())->count() >= $cap;
} }
} }

View file

@ -68,9 +68,7 @@ private function syncLemmyChannelPosts(LogSaver $logSaver): void
$api = $this->makeApiService($this->channel->platformInstance->url); $api = $this->makeApiService($this->channel->platformInstance->url);
$token = $this->getAuthToken($api, $account); $token = $this->getAuthToken($api, $account);
$communityId = $api->resolveCommunityId($this->channel->channel_id, $token); $api->syncChannelPosts($token, $this->channel, $this->channel->channel_id);
$api->syncChannelPosts($token, $communityId, $this->channel->name);
$logSaver->info('Channel posts synced successfully', $this->channel); $logSaver->info('Channel posts synced successfully', $this->channel);
} catch (Exception $e) { } catch (Exception $e) {

View file

@ -0,0 +1,31 @@
<?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);
}
}

View file

@ -2,15 +2,8 @@
namespace App\Listeners; namespace App\Listeners;
use App\Enums\LogLevelEnum; use App\Actions\PublishRouteArticleAction;
use App\Enums\NotificationSeverityEnum;
use App\Enums\NotificationTypeEnum;
use App\Enums\PublishStatusEnum;
use App\Events\ActionPerformed;
use App\Events\RouteArticleApproved; use App\Events\RouteArticleApproved;
use App\Services\Article\ArticleFetcher;
use App\Services\Notification\NotificationService;
use App\Services\Publishing\ArticlePublishingService;
use Exception; use Exception;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
@ -19,9 +12,7 @@ class PublishApprovedArticleListener implements ShouldQueue
public string $queue = 'publishing'; public string $queue = 'publishing';
public function __construct( public function __construct(
private ArticleFetcher $articleFetcher, private PublishRouteArticleAction $publishRouteArticle,
private ArticlePublishingService $publishingService,
private NotificationService $notificationService,
) {} ) {}
public function handle(RouteArticleApproved $event): void public function handle(RouteArticleApproved $event): void
@ -29,7 +20,6 @@ public function handle(RouteArticleApproved $event): void
$routeArticle = $event->routeArticle; $routeArticle = $event->routeArticle;
$article = $routeArticle->article; $article = $routeArticle->article;
// Skip if already published to this channel
if ($article->articlePublications() if ($article->articlePublications()
->where('platform_channel_id', $routeArticle->platform_channel_id) ->where('platform_channel_id', $routeArticle->platform_channel_id)
->exists() ->exists()
@ -37,50 +27,10 @@ public function handle(RouteArticleApproved $event): void
return; return;
} }
$routeArticle->update(['publish_status' => PublishStatusEnum::PUBLISHING]);
try { try {
$extractedData = $this->articleFetcher->fetchArticleData($article); $this->publishRouteArticle->execute($routeArticle);
$publication = $this->publishingService->publishRouteArticle($routeArticle, $extractedData); } catch (Exception) {
// The action has already recorded the failure and notified.
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,
);
} }
} }
} }

View file

@ -0,0 +1,29 @@
<?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());
}
}
}

View file

@ -2,10 +2,12 @@
namespace App\Listeners; namespace App\Listeners;
use App\Actions\ValidateArticleAction;
use App\Enums\ActivityTypeEnum;
use App\Enums\LogLevelEnum; use App\Enums\LogLevelEnum;
use App\Events\ActionPerformed; use App\Events\ActionPerformed;
use App\Events\ActivityLogged;
use App\Events\NewArticleFetched; use App\Events\NewArticleFetched;
use App\Services\Article\ValidationService;
use Exception; use Exception;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
@ -14,7 +16,7 @@ class ValidateArticleListener implements ShouldQueue
public string $queue = 'default'; public string $queue = 'default';
public function __construct( public function __construct(
private ValidationService $validationService private ValidateArticleAction $validateArticle
) {} ) {}
public function handle(NewArticleFetched $event): void public function handle(NewArticleFetched $event): void
@ -31,12 +33,26 @@ public function handle(NewArticleFetched $event): void
} }
try { try {
$this->validationService->validate($article); $this->validateArticle->execute($article);
ActivityLogged::dispatch(
ActivityTypeEnum::VALIDATE,
"Validated \"{$article->title}\"",
[],
$article,
);
} catch (Exception $e) { } catch (Exception $e) {
ActionPerformed::dispatch('Article validation failed', LogLevelEnum::ERROR, [ ActionPerformed::dispatch('Article validation failed', LogLevelEnum::ERROR, [
'article_id' => $article->id, 'article_id' => $article->id,
'error' => $e->getMessage(), 'error' => $e->getMessage(),
]); ]);
ActivityLogged::dispatch(
ActivityTypeEnum::ERROR,
"Validation failed for \"{$article->title}\"",
['error' => $e->getMessage()],
$article,
);
} }
} }
} }

55
app/Livewire/Activity.php Normal file
View file

@ -0,0 +1,55 @@
<?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');
}
}

View file

@ -2,10 +2,17 @@
namespace App\Livewire; namespace App\Livewire;
use App\Enums\ActivityTypeEnum;
use App\Enums\ApprovalStatusEnum; use App\Enums\ApprovalStatusEnum;
use App\Events\ActivityLogged;
use App\Jobs\ArticleDiscoveryJob; use App\Jobs\ArticleDiscoveryJob;
use App\Models\Feed;
use App\Models\RouteArticle; use App\Models\RouteArticle;
use App\Support\PendingFeedGroup;
use Illuminate\Contracts\View\View; 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\Component;
use Livewire\WithPagination; use Livewire\WithPagination;
@ -17,15 +24,38 @@ class Articles extends Component
public string $search = ''; public string $search = '';
public ?int $feedId = null;
public bool $isRefreshing = false; public bool $isRefreshing = false;
/** @var array<int, bool> */
public array $expandedFeeds = [];
public function setTab(string $tab): void public function setTab(string $tab): void
{ {
$this->tab = $tab; $this->tab = $tab;
$this->search = ''; $this->search = '';
$this->expandedFeeds = [];
$this->resetPage(); $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 public function updatedSearch(): void
{ {
$this->resetPage(); $this->resetPage();
@ -44,13 +74,42 @@ public function reject(int $routeArticleId): void
public function restore(int $routeArticleId): void public function restore(int $routeArticleId): void
{ {
$routeArticle = RouteArticle::findOrFail($routeArticleId); $routeArticle = RouteArticle::findOrFail($routeArticleId);
$routeArticle->update(['approval_status' => ApprovalStatusEnum::PENDING]); $routeArticle->update([
'approval_status' => ApprovalStatusEnum::PENDING,
'decided_at' => null,
]);
} }
public function clear(): void public function clear(): void
{ {
RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING) $feed = $this->feedId !== null ? Feed::find($this->feedId) : null;
->update(['approval_status' => ApprovalStatusEnum::REJECTED]); $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));
} }
public function refresh(): void public function refresh(): void
@ -62,14 +121,52 @@ public function refresh(): void
$this->dispatch('refresh-started'); $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 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']) $query = RouteArticle::with(['article.feed', 'feed', 'platformChannel'])
->orderBy('created_at', 'desc'); ->orderBy('created_at', 'desc');
if ($this->tab === 'pending') { if ($this->tab === 'failed') {
$query->where('approval_status', ApprovalStatusEnum::PENDING); $query->failed();
} elseif ($this->search !== '') { }
if ($this->feedId !== null) {
$query->where('feed_id', $this->feedId);
}
if ($this->search !== '') {
$search = $this->search; $search = $this->search;
$query->whereHas('article', function ($q) use ($search) { $query->whereHas('article', function ($q) use ($search) {
$q->where('title', 'like', "%{$search}%") $q->where('title', 'like', "%{$search}%")
@ -77,13 +174,59 @@ public function render(): View
}); });
} }
$routeArticles = $query->paginate(15);
$pendingCount = RouteArticle::where('approval_status', ApprovalStatusEnum::PENDING)->count();
return view('livewire.articles', [ return view('livewire.articles', [
'routeArticles' => $routeArticles, 'routeArticles' => $query->paginate(15),
'pendingFeeds' => null,
'feedOptions' => $this->feedOptions(),
'pendingCount' => $pendingCount, 'pendingCount' => $pendingCount,
'failedCount' => $failedCount,
'clearableCount' => 0,
])->layout('layouts.app'); ])->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();
}
} }

View file

@ -3,10 +3,16 @@
namespace App\Livewire; namespace App\Livewire;
use App\Actions\CreateChannelAction; use App\Actions\CreateChannelAction;
use App\Enums\LogLevelEnum;
use App\Events\ActionPerformed;
use App\Models\ArticlePublication;
use App\Models\Language; use App\Models\Language;
use App\Models\PlatformAccount; use App\Models\PlatformAccount;
use App\Models\PlatformChannel; use App\Models\PlatformChannel;
use App\Models\PlatformInstance; use App\Models\PlatformInstance;
use App\Models\RouteArticle;
use App\Services\Platform\CommunityDirectory;
use Exception;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
use Illuminate\Database\UniqueConstraintViolationException; use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
@ -19,14 +25,27 @@ class Channels extends Component
public bool $showCreateModal = false; public bool $showCreateModal = false;
public string $newName = ''; public ?int $newCommunityId = null;
public ?int $newPlatformInstanceId = null; 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 ?int $newLanguageId = null;
public string $newDescription = ''; public string $newDescription = '';
public ?int $editingChannelId = null;
public string $editDisplayName = '';
public ?int $editLanguageId = null;
public string $editDescription = '';
public function toggle(int $channelId): void public function toggle(int $channelId): void
{ {
$channel = PlatformChannel::findOrFail($channelId); $channel = PlatformChannel::findOrFail($channelId);
@ -34,13 +53,74 @@ public function toggle(int $channelId): void
$channel->save(); $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 public function openCreateModal(): void
{ {
$this->reset(['newName', 'newPlatformInstanceId', 'newLanguageId', 'newDescription']); $this->reset(['newCommunityId', 'newPlatformInstanceId', 'newLanguageId', 'newDescription', 'availableCommunities', 'communityLoadError']);
$this->resetErrorBag(); $this->resetErrorBag();
$this->showCreateModal = true; $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 public function closeCreateModal(): void
{ {
$this->showCreateModal = false; $this->showCreateModal = false;
@ -49,36 +129,33 @@ public function closeCreateModal(): void
public function createChannel(CreateChannelAction $action): void public function createChannel(CreateChannelAction $action): void
{ {
$this->validate([ $this->validate([
// name doubles as the Lemmy community slug (used verbatim as channel_id for 'newCommunityId' => [
// community lookup at publish time), so it must be lowercase slug format.
'newName' => [
'required', 'required',
'string', 'integer',
'max:255', Rule::in(collect($this->availableCommunities)->pluck('id')->all()),
'regex:/^[a-z0-9_]+$/', Rule::unique('platform_channels', 'channel_id')
Rule::unique('platform_channels', 'name')
->where('platform_instance_id', $this->newPlatformInstanceId), ->where('platform_instance_id', $this->newPlatformInstanceId),
], ],
'newPlatformInstanceId' => 'required|integer|exists:platform_instances,id', 'newPlatformInstanceId' => 'required|integer|exists:platform_instances,id',
'newLanguageId' => 'nullable|integer|exists:languages,id', 'newLanguageId' => 'nullable|integer|exists:languages,id',
], [ ], [
'newName.regex' => 'The name must be a valid community slug (lowercase letters, numbers, and underscores only).', 'newCommunityId.in' => 'Select a community from this instance.',
'newName.unique' => 'A channel with this name already exists for this instance.', 'newCommunityId.unique' => 'A channel for this community already exists.',
]); ]);
$name = collect($this->availableCommunities)->firstWhere('id', $this->newCommunityId)['name'] ?? null;
try { try {
$action->execute( $action->execute(
$this->newName, $name,
$this->newCommunityId,
$this->newPlatformInstanceId, $this->newPlatformInstanceId,
$this->newLanguageId, $this->newLanguageId,
// Blade textarea binds an empty string when blank; the action expects null for "no description". // Blade textarea binds an empty string when blank; the action expects null for "no description".
$this->newDescription !== '' ? $this->newDescription : null, $this->newDescription !== '' ? $this->newDescription : null,
); );
} catch (UniqueConstraintViolationException $e) { } catch (UniqueConstraintViolationException $e) {
// Unreachable via this form (the unique rule above catches duplicates first), $this->addError('newCommunityId', 'A channel for this community already exists.');
// 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; return;
} catch (RuntimeException $e) { } catch (RuntimeException $e) {
@ -90,6 +167,45 @@ public function createChannel(CreateChannelAction $action): void
$this->closeCreateModal(); $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 public function openAccountModal(int $channelId): void
{ {
$this->managingChannelId = $channelId; $this->managingChannelId = $channelId;
@ -124,6 +240,39 @@ public function detachAccount(int $channelId, int $accountId): void
$channel->platformAccounts()->detach($accountId); $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 public function render(): View
{ {
$channels = PlatformChannel::with(['platformInstance', 'platformAccounts'])->orderBy('name')->get(); $channels = PlatformChannel::with(['platformInstance', 'platformAccounts'])->orderBy('name')->get();
@ -140,7 +289,11 @@ public function render(): View
return view('livewire.channels', [ return view('livewire.channels', [
'channels' => $channels, 'channels' => $channels,
'managingChannel' => $managingChannel, 'managingChannel' => $managingChannel,
'editingChannel' => $this->editingChannelId !== null
? PlatformChannel::with('platformInstance')->find($this->editingChannelId)
: null,
'availableAccounts' => $availableAccounts, 'availableAccounts' => $availableAccounts,
'deletionImpact' => $this->deletionImpact(),
'platformInstances' => PlatformInstance::where('is_active', true)->orderBy('name')->get(), 'platformInstances' => PlatformInstance::where('is_active', true)->orderBy('name')->get(),
'languages' => Language::where('is_active', true)->orderBy('name')->get(), 'languages' => Language::where('is_active', true)->orderBy('name')->get(),
])->layout('layouts.app'); ])->layout('layouts.app');

View file

@ -2,36 +2,243 @@
namespace App\Livewire; 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\Services\DashboardStatsService;
use App\Support\DateRange;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use InvalidArgumentException;
use Livewire\Attributes\Computed;
use Livewire\Component; use Livewire\Component;
class Dashboard extends Component class Dashboard extends Component
{ {
public string $period = 'today'; public string $from = '';
public string $to = '';
public function mount(): void public function mount(): void
{ {
// Default period $this->applyPreset('month');
} }
public function setPeriod(string $period): void /**
* 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
{ {
$this->period = $period; 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;
} }
public function render(): View public function render(): View
{ {
$service = app(DashboardStatsService::class); return view('livewire.dashboard')->layout('layouts.app');
$articleStats = $service->getStats($this->period);
$systemStats = $service->getSystemStats();
$availablePeriods = $service->getAvailablePeriods();
return view('livewire.dashboard', [
'articleStats' => $articleStats,
'systemStats' => $systemStats,
'availablePeriods' => $availablePeriods,
])->layout('layouts.app');
} }
} }

View file

@ -21,6 +21,12 @@ class Feeds extends Component
public string $newDescription = ''; public string $newDescription = '';
public ?int $editingFeedId = null;
public string $editName = '';
public string $editDescription = '';
public function toggle(int $feedId): void public function toggle(int $feedId): void
{ {
$feed = Feed::findOrFail($feedId); $feed = Feed::findOrFail($feedId);
@ -67,6 +73,41 @@ public function createFeed(CreateFeedAction $action): void
$this->closeCreateModal(); $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>> * @return array<string, array<string, mixed>>
*/ */
@ -86,6 +127,9 @@ public function render(): View
'feeds' => $feeds, 'feeds' => $feeds,
'providers' => $this->activeProviders(), 'providers' => $this->activeProviders(),
'languages' => Language::where('is_active', true)->orderBy('name')->get(), 'languages' => Language::where('is_active', true)->orderBy('name')->get(),
'editingFeed' => $this->editingFeedId !== null
? Feed::with('language')->find($this->editingFeedId)
: null,
])->layout('layouts.app'); ])->layout('layouts.app');
} }
} }

View file

@ -17,8 +17,10 @@
use App\Models\Route; use App\Models\Route;
use App\Models\Setting; use App\Models\Setting;
use App\Services\OnboardingService; use App\Services\OnboardingService;
use App\Services\Platform\CommunityDirectory;
use Exception; use Exception;
use Illuminate\Contracts\View\View; use Illuminate\Contracts\View\View;
use Illuminate\Validation\Rule;
use InvalidArgumentException; use InvalidArgumentException;
use Livewire\Attributes\Locked; use Livewire\Attributes\Locked;
use Livewire\Component; use Livewire\Component;
@ -49,7 +51,12 @@ class Onboarding extends Component
public string $feedDescription = ''; public string $feedDescription = '';
// Channel form // Channel form
public string $channelName = ''; public ?int $channelCommunityId = null;
/** @var array<int, array{id: int, name: string, title: string}> */
public array $availableCommunities = [];
public ?string $communityLoadError = null;
public ?int $platformInstanceId = null; public ?int $platformInstanceId = null;
@ -117,10 +124,11 @@ public function mount(): void
// Pre-fill channel form if exists // Pre-fill channel form if exists
$channel = PlatformChannel::where('is_active', true)->first(); $channel = PlatformChannel::where('is_active', true)->first();
if ($channel) { if ($channel) {
$this->channelName = $channel->name;
$this->platformInstanceId = $channel->platform_instance_id; $this->platformInstanceId = $channel->platform_instance_id;
$this->channelLanguageId = $channel->language_id; $this->channelLanguageId = $channel->language_id;
$this->channelDescription = $channel->description ?? ''; $this->channelDescription = $channel->description ?? '';
$this->loadCommunities();
$this->channelCommunityId = $channel->channel_id;
} }
// Pre-fill route form if exists // Pre-fill route form if exists
@ -252,16 +260,61 @@ 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 public function createChannel(): void
{ {
$this->formErrors = []; $this->formErrors = [];
$this->isLoading = true; $this->isLoading = true;
$this->validate([ $this->validate([
'channelName' => 'required|string|max:255', 'channelCommunityId' => [
'required',
'integer',
Rule::in(collect($this->availableCommunities)->pluck('id')->all()),
],
'platformInstanceId' => 'required|exists:platform_instances,id', 'platformInstanceId' => 'required|exists:platform_instances,id',
'channelLanguageId' => 'required|exists:languages,id', 'channelLanguageId' => 'required|exists:languages,id',
'channelDescription' => 'nullable|string|max:1000', 'channelDescription' => 'nullable|string|max:1000',
], [
'channelCommunityId.in' => 'Select a community from this instance.',
]); ]);
// If language changed, reset feed form // If language changed, reset feed form
@ -274,11 +327,14 @@ public function createChannel(): void
} }
$this->previousChannelLanguageId = $this->channelLanguageId; $this->previousChannelLanguageId = $this->channelLanguageId;
$name = collect($this->availableCommunities)->firstWhere('id', $this->channelCommunityId)['name'] ?? null;
try { try {
$channel = $this->createChannelAction->execute( $channel = $this->createChannelAction->execute(
$this->channelName, $name,
$this->platformInstanceId, (int) $this->channelCommunityId,
$this->channelLanguageId, (int) $this->platformInstanceId,
$this->channelLanguageId !== null ? (int) $this->channelLanguageId : null,
$this->channelDescription ?: null, $this->channelDescription ?: null,
); );

View file

@ -2,6 +2,7 @@
namespace App\Livewire; namespace App\Livewire;
use App\Events\RouteActivated;
use App\Models\Feed; use App\Models\Feed;
use App\Models\Keyword; use App\Models\Keyword;
use App\Models\PlatformChannel; use App\Models\PlatformChannel;
@ -72,6 +73,8 @@ public function createRoute(): void
'is_active' => true, 'is_active' => true,
]); ]);
RouteActivated::dispatch($this->newFeedId, $this->newChannelId);
$this->closeCreateModal(); $this->closeCreateModal();
} }
@ -129,6 +132,10 @@ public function toggle(int $feedId, int $channelId): void
$route->is_active = ! $route->is_active; $route->is_active = ! $route->is_active;
$route->save(); $route->save();
if ($route->is_active) {
RouteActivated::dispatch($route->feed_id, $route->platform_channel_id);
}
} }
public function delete(int $feedId, int $channelId): void public function delete(int $feedId, int $channelId): void

View file

@ -16,6 +16,8 @@ class Settings extends Component
public int $feedStalenessThreshold = 48; public int $feedStalenessThreshold = 48;
public int $dailyPublishCap = 0;
public ?string $successMessage = null; public ?string $successMessage = null;
public ?string $errorMessage = null; public ?string $errorMessage = null;
@ -26,6 +28,7 @@ public function mount(): void
$this->publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled(); $this->publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();
$this->articlePublishingInterval = Setting::getArticlePublishingInterval(); $this->articlePublishingInterval = Setting::getArticlePublishingInterval();
$this->feedStalenessThreshold = Setting::getFeedStalenessThreshold(); $this->feedStalenessThreshold = Setting::getFeedStalenessThreshold();
$this->dailyPublishCap = Setting::getDailyPublishCap();
} }
public function toggleArticleProcessing(): void public function toggleArticleProcessing(): void
@ -62,6 +65,16 @@ public function updateFeedStalenessThreshold(): void
$this->showSuccess(); $this->showSuccess();
} }
public function updateDailyPublishCap(): void
{
$this->validate([
'dailyPublishCap' => 'required|integer|min:0',
]);
Setting::setDailyPublishCap($this->dailyPublishCap);
$this->showSuccess();
}
protected function showSuccess(): void protected function showSuccess(): void
{ {
$this->successMessage = 'Settings updated successfully!'; $this->successMessage = 'Settings updated successfully!';

View file

@ -0,0 +1,94 @@
<?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']]);
}
}]);
}
}

View file

@ -17,11 +17,12 @@
* @method static create(array<string, mixed> $array) * @method static create(array<string, mixed> $array)
* *
* @property int $id * @property int $id
* @property int $feed_id * @property int|null $feed_id
* @property Feed $feed * @property Feed $feed
* @property string $url * @property string $url
* @property string $title * @property string $title
* @property string|null $description * @property string|null $description
* @property string|null $content
* @property Carbon|null $validated_at * @property Carbon|null $validated_at
* @property Carbon $created_at * @property Carbon $created_at
* @property Carbon $updated_at * @property Carbon $updated_at

View file

@ -2,6 +2,7 @@
namespace App\Models; namespace App\Models;
use App\Enums\FeedColorEnum;
use Database\Factories\FeedFactory; use Database\Factories\FeedFactory;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
@ -19,7 +20,8 @@
* @property string $provider * @property string $provider
* @property int|null $language_id * @property int|null $language_id
* @property Language|null $language * @property Language|null $language
* @property string $description * @property string|null $description
* @property FeedColorEnum|null $color
* @property array<string, mixed> $settings * @property array<string, mixed> $settings
* @property bool $is_active * @property bool $is_active
* @property Carbon|null $last_fetched_at * @property Carbon|null $last_fetched_at
@ -46,6 +48,7 @@ class Feed extends Model
'provider', 'provider',
'language_id', 'language_id',
'description', 'description',
'color',
'settings', 'settings',
'is_active', 'is_active',
'last_fetched_at', 'last_fetched_at',
@ -55,8 +58,14 @@ class Feed extends Model
'settings' => 'array', 'settings' => 'array',
'is_active' => 'boolean', 'is_active' => 'boolean',
'last_fetched_at' => 'datetime', 'last_fetched_at' => 'datetime',
'color' => FeedColorEnum::class,
]; ];
public function displayColor(): FeedColorEnum
{
return $this->color ?? FeedColorEnum::forId($this->id);
}
public function getTypeDisplayAttribute(): string public function getTypeDisplayAttribute(): string
{ {
return match ($this->type) { return match ($this->type) {

View file

@ -2,6 +2,7 @@
namespace App\Models; namespace App\Models;
use App\Enums\AccountStatusEnum;
use App\Enums\PlatformEnum; use App\Enums\PlatformEnum;
use Database\Factories\PlatformAccountFactory; use Database\Factories\PlatformAccountFactory;
use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Casts\Attribute;
@ -21,7 +22,8 @@
* @property array<string, mixed> $settings * @property array<string, mixed> $settings
* @property bool $is_active * @property bool $is_active
* @property Carbon|null $last_tested_at * @property Carbon|null $last_tested_at
* @property string $status * @property AccountStatusEnum $status
* @property int $consecutive_failures
* @property Carbon $created_at * @property Carbon $created_at
* @property Carbon $updated_at * @property Carbon $updated_at
* @property Collection<int, PlatformChannel> $activeChannels * @property Collection<int, PlatformChannel> $activeChannels
@ -44,10 +46,12 @@ class PlatformAccount extends Model
'is_active', 'is_active',
'last_tested_at', 'last_tested_at',
'status', 'status',
'consecutive_failures',
]; ];
protected $casts = [ protected $casts = [
'platform' => PlatformEnum::class, 'platform' => PlatformEnum::class,
'status' => AccountStatusEnum::class,
'settings' => 'array', 'settings' => 'array',
'is_active' => 'boolean', 'is_active' => 'boolean',
'last_tested_at' => 'datetime', 'last_tested_at' => 'datetime',
@ -136,4 +140,33 @@ public function activeChannels(): BelongsToMany
->wherePivot('is_active', true) ->wherePivot('is_active', true)
->orderByPivot('priority', 'desc'); ->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;
}
} }

View file

@ -15,9 +15,11 @@
* @property int $id * @property int $id
* @property int $platform_instance_id * @property int $platform_instance_id
* @property PlatformInstance $platformInstance * @property PlatformInstance $platformInstance
* @property string $channel_id * @property int $channel_id
* @property string $name * @property string $name
* @property int $language_id * @property string $display_name
* @property string|null $description
* @property int|null $language_id
* @property Language|null $language * @property Language|null $language
* @property bool $is_active * @property bool $is_active
*/ */
@ -40,6 +42,7 @@ class PlatformChannel extends Model
protected $casts = [ protected $casts = [
'is_active' => 'boolean', 'is_active' => 'boolean',
'channel_id' => 'integer',
]; ];
/** /**

View file

@ -2,13 +2,12 @@
namespace App\Models; namespace App\Models;
use App\Enums\PlatformEnum;
use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; 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) * @method static updateOrCreate(array<string, mixed> $array, array<string, mixed> $array1)
*/ */
class PlatformChannelPost extends Model class PlatformChannelPost extends Model
@ -17,9 +16,7 @@ class PlatformChannelPost extends Model
use HasFactory; use HasFactory;
protected $fillable = [ protected $fillable = [
'platform', 'platform_channel_id',
'channel_id',
'channel_name',
'post_id', 'post_id',
'url', 'url',
'title', 'title',
@ -33,26 +30,24 @@ protected function casts(): array
{ {
return [ return [
'posted_at' => 'datetime', 'posted_at' => 'datetime',
'platform' => PlatformEnum::class,
]; ];
} }
public static function urlExists(PlatformEnum $platform, string $channelId, string $url): bool /**
* @return BelongsTo<PlatformChannel, $this>
*/
public function platformChannel(): BelongsTo
{ {
return self::where('platform', $platform) return $this->belongsTo(PlatformChannel::class);
->where('channel_id', $channelId)
->where('url', $url)
->exists();
} }
public static function duplicateExists(PlatformEnum $platform, string $channelId, ?string $url, ?string $title): bool public static function duplicateExists(PlatformChannel $channel, ?string $url, ?string $title): bool
{ {
if (! $url && ! $title) { if (! $url && ! $title) {
return false; return false;
} }
return self::where('platform', $platform) return self::where('platform_channel_id', $channel->id)
->where('channel_id', $channelId)
->where(function ($query) use ($url, $title) { ->where(function ($query) use ($url, $title) {
if ($url) { if ($url) {
$query->orWhere('url', $url); $query->orWhere('url', $url);
@ -64,16 +59,14 @@ public static function duplicateExists(PlatformEnum $platform, string $channelId
->exists(); ->exists();
} }
public static function storePost(PlatformEnum $platform, string $channelId, ?string $channelName, string $postId, ?string $url, ?string $title, ?\DateTime $postedAt = null): self public static function storePost(PlatformChannel $channel, string $postId, ?string $url, ?string $title, ?\DateTime $postedAt = null): self
{ {
return self::updateOrCreate( return self::updateOrCreate(
[ [
'platform' => $platform, 'platform_channel_id' => $channel->id,
'channel_id' => $channelId,
'post_id' => $postId, 'post_id' => $postId,
], ],
[ [
'channel_name' => $channelName,
'url' => $url, 'url' => $url,
'title' => $title, 'title' => $title,
'posted_at' => $postedAt ?? now(), 'posted_at' => $postedAt ?? now(),

View file

@ -2,10 +2,13 @@
namespace App\Models; namespace App\Models;
use App\Enums\ActivityTypeEnum;
use App\Enums\ApprovalStatusEnum; use App\Enums\ApprovalStatusEnum;
use App\Enums\PublishStatusEnum; use App\Enums\PublishStatusEnum;
use App\Events\ActivityLogged;
use App\Events\RouteArticleApproved; use App\Events\RouteArticleApproved;
use Database\Factories\RouteArticleFactory; use Database\Factories\RouteArticleFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@ -18,7 +21,9 @@
* @property int $article_id * @property int $article_id
* @property ApprovalStatusEnum $approval_status * @property ApprovalStatusEnum $approval_status
* @property PublishStatusEnum $publish_status * @property PublishStatusEnum $publish_status
* @property string|null $publish_error
* @property Carbon|null $validated_at * @property Carbon|null $validated_at
* @property Carbon|null $decided_at
* @property Carbon $created_at * @property Carbon $created_at
* @property Carbon $updated_at * @property Carbon $updated_at
*/ */
@ -33,13 +38,16 @@ class RouteArticle extends Model
'article_id', 'article_id',
'approval_status', 'approval_status',
'publish_status', 'publish_status',
'publish_error',
'validated_at', 'validated_at',
'decided_at',
]; ];
protected $casts = [ protected $casts = [
'approval_status' => ApprovalStatusEnum::class, 'approval_status' => ApprovalStatusEnum::class,
'publish_status' => PublishStatusEnum::class, 'publish_status' => PublishStatusEnum::class,
'validated_at' => 'datetime', 'validated_at' => 'datetime',
'decided_at' => 'datetime',
]; ];
/** /**
@ -92,13 +100,77 @@ public function isRejected(): bool
public function approve(): void public function approve(): void
{ {
$this->update(['approval_status' => ApprovalStatusEnum::APPROVED]); 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,
);
event(new RouteArticleApproved($this)); event(new RouteArticleApproved($this));
} }
public function reject(): void public function reject(): void
{ {
$this->update(['approval_status' => ApprovalStatusEnum::REJECTED]); 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);
} }
} }

View file

@ -81,4 +81,14 @@ public static function setFeedStalenessThreshold(int $hours): void
{ {
static::set('feed_staleness_threshold', (string) $hours); 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);
}
} }

View file

@ -7,6 +7,9 @@
class LemmyRequest 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 $instance;
private ?string $token; private ?string $token;
@ -83,6 +86,27 @@ public function post(string $endpoint, array $data = []): Response
return $request->post($url, $data); 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 public function withToken(string $token): self
{ {
$this->token = $token; $this->token = $token;

View file

@ -2,7 +2,7 @@
namespace App\Modules\Lemmy\Services; namespace App\Modules\Lemmy\Services;
use App\Enums\PlatformEnum; use App\Models\PlatformChannel;
use App\Models\PlatformChannelPost; use App\Models\PlatformChannelPost;
use App\Modules\Lemmy\LemmyRequest; use App\Modules\Lemmy\LemmyRequest;
use Exception; use Exception;
@ -84,18 +84,35 @@ public function login(string $username, string $password): ?string
} }
/** /**
* Resolve a PlatformChannel.channel_id to a numeric Lemmy community id. * @return array<int, array{id: int, name: string, title: string}>
*
* 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 resolveCommunityId(string $channelId, string $token): int public function listCommunities(?string $token = null): array
{ {
return is_numeric($channelId) $request = new LemmyRequest($this->instance, $token);
? (int) $channelId $response = $request->get('community/list', [
: $this->getCommunityId($channelId, $token); '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();
} }
public function getCommunityId(string $communityName, string $token): int public function getCommunityId(string $communityName, string $token): int
@ -117,12 +134,12 @@ public function getCommunityId(string $communityName, string $token): int
} }
} }
public function syncChannelPosts(string $token, int $platformChannelId, string $communityName): void public function syncChannelPosts(string $token, PlatformChannel $channel, int $communityId): void
{ {
try { try {
$request = new LemmyRequest($this->instance, $token); $request = new LemmyRequest($this->instance, $token);
$response = $request->get('post/list', [ $response = $request->get('post/list', [
'community_id' => $platformChannelId, 'community_id' => $communityId,
'limit' => 50, 'limit' => 50,
'sort' => 'New', 'sort' => 'New',
]); ]);
@ -130,7 +147,7 @@ public function syncChannelPosts(string $token, int $platformChannelId, string $
if (! $response->successful()) { if (! $response->successful()) {
logger()->warning('Failed to sync channel posts', [ logger()->warning('Failed to sync channel posts', [
'status' => $response->status(), 'status' => $response->status(),
'platform_channel_id' => $platformChannelId, 'platform_channel_id' => $channel->id,
]); ]);
return; return;
@ -143,9 +160,7 @@ public function syncChannelPosts(string $token, int $platformChannelId, string $
$post = $postData['post']; $post = $postData['post'];
PlatformChannelPost::storePost( PlatformChannelPost::storePost(
PlatformEnum::LEMMY, $channel,
(string) $platformChannelId,
$communityName,
(string) $post['id'], (string) $post['id'],
$post['url'] ?? null, $post['url'] ?? null,
$post['name'] ?? null, $post['name'] ?? null,
@ -154,14 +169,14 @@ public function syncChannelPosts(string $token, int $platformChannelId, string $
} }
logger()->info('Synced channel posts', [ logger()->info('Synced channel posts', [
'platform_channel_id' => $platformChannelId, 'platform_channel_id' => $channel->id,
'posts_count' => count($posts), 'posts_count' => count($posts),
]); ]);
} catch (Exception $e) { } catch (Exception $e) {
logger()->error('Exception while syncing channel posts', [ logger()->error('Exception while syncing channel posts', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'platform_channel_id' => $platformChannelId, 'platform_channel_id' => $channel->id,
]); ]);
} }
} }

View file

@ -7,6 +7,7 @@
use App\Models\PlatformAccount; use App\Models\PlatformAccount;
use App\Models\PlatformChannel; use App\Models\PlatformChannel;
use App\Services\Auth\LemmyAuthService; use App\Services\Auth\LemmyAuthService;
use App\Services\Log\LogSaver;
use Exception; use Exception;
class LemmyPublisher class LemmyPublisher
@ -15,10 +16,13 @@ class LemmyPublisher
private PlatformAccount $account; private PlatformAccount $account;
private ThumbnailUploader $thumbnailUploader;
public function __construct(PlatformAccount $account) public function __construct(PlatformAccount $account)
{ {
$this->api = new LemmyApiService($account->instance_url); $this->api = new LemmyApiService($account->instance_url);
$this->account = $account; $this->account = $account;
$this->thumbnailUploader = new ThumbnailUploader($account->instance_url);
} }
/** /**
@ -33,36 +37,63 @@ public function publishToChannel(Article $article, array $extractedData, Platfor
$authService = resolve(LemmyAuthService::class); $authService = resolve(LemmyAuthService::class);
$token = $authService->getToken($this->account); $token = $authService->getToken($this->account);
$thumbnail = $this->hostedThumbnail($extractedData, $channel, $article, $token);
try { try {
return $this->createPost($token, $extractedData, $channel, $article); return $this->createPost($token, $extractedData, $channel, $article, $thumbnail);
} catch (Exception $e) { } catch (Exception $e) {
// If the cached token was stale, refresh and retry once // If the cached token was stale, refresh and retry once
if (str_contains($e->getMessage(), 'not_logged_in') || str_contains($e->getMessage(), 'Unauthorized')) { if (str_contains($e->getMessage(), 'not_logged_in') || str_contains($e->getMessage(), 'Unauthorized')) {
$token = $authService->refreshToken($this->account); $token = $authService->refreshToken($this->account);
return $this->createPost($token, $extractedData, $channel, $article); return $this->createPost($token, $extractedData, $channel, $article, $thumbnail);
} }
throw $e; 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 * @param array<string, mixed> $extractedData
* @return array<string, mixed> * @return array<string, mixed>
*/ */
private function createPost(string $token, array $extractedData, PlatformChannel $channel, Article $article): array private function createPost(string $token, array $extractedData, PlatformChannel $channel, Article $article, ?string $thumbnail = null): array
{ {
$languageId = $extractedData['language_id'] ?? null; $languageId = $extractedData['language_id'] ?? null;
$communityId = $this->api->resolveCommunityId($channel->channel_id, $token);
return $this->api->createPost( return $this->api->createPost(
$token, $token,
$extractedData['title'] ?? 'Untitled', $extractedData['title'] ?? 'Untitled',
$extractedData['description'] ?? '', $extractedData['description'] ?? '',
$communityId, $channel->channel_id,
$article->url, $article->url,
$extractedData['thumbnail'] ?? null, $thumbnail,
$languageId $languageId
); );
} }

View file

@ -0,0 +1,125 @@
<?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);
}
}

View file

@ -2,62 +2,11 @@
namespace App\Providers; 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 Illuminate\Support\ServiceProvider;
use InvalidArgumentException;
use Throwable;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
{ {
public function register(): void {} 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,
};
}
} }

View file

@ -0,0 +1,34 @@
<?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;
}
}

View file

@ -1,181 +0,0 @@
<?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';
}
}

View file

@ -1,116 +0,0 @@
<?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();
}
}

View file

@ -8,33 +8,25 @@
use App\Models\PlatformAccount; use App\Models\PlatformAccount;
use App\Models\PlatformChannel; use App\Models\PlatformChannel;
use App\Models\Route; use App\Models\Route;
use Carbon\Carbon; use App\Support\DateRange;
class DashboardStatsService class DashboardStatsService
{ {
/** /**
* @return array<string, mixed> * @return array<string, mixed>
*/ */
public function getStats(string $period = 'today'): array public function getStats(DateRange $range): array
{ {
$dateRange = $this->getDateRange($period); $bounds = [$range->from, $range->to];
// Get articles fetched for the period $articlesFetched = Article::query()
$articlesFetchedQuery = Article::query(); ->whereBetween('created_at', $bounds)
if ($dateRange) { ->count();
$articlesFetchedQuery->whereBetween('created_at', $dateRange);
}
$articlesFetched = $articlesFetchedQuery->count();
// Get articles published for the period $articlesPublished = ArticlePublication::query()
$articlesPublishedQuery = ArticlePublication::query() ->whereBetween('published_at', $bounds)
->whereNotNull('published_at'); ->count();
if ($dateRange) {
$articlesPublishedQuery->whereBetween('published_at', $dateRange);
}
$articlesPublished = $articlesPublishedQuery->count();
// Calculate published percentage
$publishedPercentage = $articlesFetched > 0 ? round(($articlesPublished / $articlesFetched) * 100, 1) : 0.0; $publishedPercentage = $articlesFetched > 0 ? round(($articlesPublished / $articlesFetched) * 100, 1) : 0.0;
return [ return [
@ -44,37 +36,6 @@ public function getStats(string $period = 'today'): 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> * @return array<string, int>
*/ */

View file

@ -110,12 +110,12 @@ public static function extractThumbnail(string $html): ?string
{ {
// Try OpenGraph image first // Try OpenGraph image first
if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) { if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) {
return $matches[1]; return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
} }
// Try first image in article content // Try first image in article content
if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) { if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) {
return $matches[1]; return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
} }
return null; return null;

View file

@ -0,0 +1,28 @@
<?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();
}
}

View file

@ -0,0 +1,39 @@
<?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';
}
}

View file

@ -68,12 +68,12 @@ public static function extractThumbnail(string $html): ?string
{ {
// Try OpenGraph image first // Try OpenGraph image first
if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) { if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) {
return $matches[1]; return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
} }
// Try first image in content // Try first image in content
if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) { if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) {
return $matches[1]; return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
} }
return null; return null;

View file

@ -67,11 +67,11 @@ public static function extractFullArticle(string $html): ?string
public static function extractThumbnail(string $html): ?string public static function extractThumbnail(string $html): ?string
{ {
if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) { if (preg_match('/<meta property="og:image" content="([^"]+)"/i', $html, $matches)) {
return $matches[1]; return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
} }
if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) { if (preg_match('/<img[^>]+src="([^"]+)"/i', $html, $matches)) {
return $matches[1]; return html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
} }
return null; return null;

View file

@ -0,0 +1,51 @@
<?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}";
}
}

View file

@ -12,10 +12,16 @@
use App\Modules\Lemmy\Services\LemmyPublisher; use App\Modules\Lemmy\Services\LemmyPublisher;
use App\Services\Log\LogSaver; use App\Services\Log\LogSaver;
use Exception; use Exception;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Facades\Cache;
use RuntimeException; use RuntimeException;
class ArticlePublishingService class ArticlePublishingService
{ {
private const LOCK_TTL_SECONDS = 180;
private const LOCK_WAIT_SECONDS = 15;
public function __construct(private LogSaver $logSaver) {} public function __construct(private LogSaver $logSaver) {}
/** /**
@ -33,7 +39,7 @@ protected function makePublisher(mixed $account): LemmyPublisher
* *
* @throws PublishException * @throws PublishException
*/ */
public function publishRouteArticle(RouteArticle $routeArticle, array $extractedData): ?ArticlePublication public function publishRouteArticle(RouteArticle $routeArticle, array $extractedData): PublishOutcome
{ {
$article = $routeArticle->article; $article = $routeArticle->article;
$channel = $routeArticle->platformChannel; $channel = $routeArticle->platformChannel;
@ -54,7 +60,7 @@ public function publishRouteArticle(RouteArticle $routeArticle, array $extracted
'route_article_id' => $routeArticle->id, 'route_article_id' => $routeArticle->id,
]); ]);
return null; return PublishOutcome::failure('No active account for channel');
} }
return $this->publishToChannel($article, $extractedData, $channel, $account); return $this->publishToChannel($article, $extractedData, $channel, $account);
@ -63,24 +69,51 @@ public function publishRouteArticle(RouteArticle $routeArticle, array $extracted
/** /**
* @param array<string, mixed> $extractedData * @param array<string, mixed> $extractedData
*/ */
private function publishToChannel(Article $article, array $extractedData, PlatformChannel $channel, mixed $account): ?ArticlePublication 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
{ {
try { try {
// Check if this URL or title was already posted to this channel // Check if this URL or title was already posted to this channel
$title = $extractedData['title'] ?? $article->title; $title = $extractedData['title'] ?? $article->title;
if (PlatformChannelPost::duplicateExists( if (PlatformChannelPost::duplicateExists($channel, $article->url, $title)) {
$channel->platformInstance->platform,
(string) $channel->channel_id,
$article->url,
$title
)) {
$this->logSaver->info('Skipping duplicate: URL or title already posted to channel', $channel, [ $this->logSaver->info('Skipping duplicate: URL or title already posted to channel', $channel, [
'article_id' => $article->id, 'article_id' => $article->id,
'url' => $article->url, 'url' => $article->url,
'title' => $title, 'title' => $title,
]); ]);
return null; return PublishOutcome::skipped('URL or title already posted to this channel');
} }
$publisher = $this->makePublisher($account); $publisher = $this->makePublisher($account);
@ -100,14 +133,14 @@ private function publishToChannel(Article $article, array $extractedData, Platfo
'article_id' => $article->id, 'article_id' => $article->id,
]); ]);
return $publication; return PublishOutcome::published($publication);
} catch (Exception $e) { } catch (Exception $e) {
$this->logSaver->warning('Failed to publish to channel', $channel, [ $this->logSaver->warning('Failed to publish to channel', $channel, [
'article_id' => $article->id, 'article_id' => $article->id,
'error' => $e->getMessage(), 'error' => $e->getMessage(),
]); ]);
return null; return PublishOutcome::failure($e->getMessage());
} }
} }
} }

View file

@ -0,0 +1,49 @@
<?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;
}
}

78
app/Support/DateRange.php Normal file
View file

@ -0,0 +1,78 @@
<?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;
}
}

View file

@ -0,0 +1,24 @@
<?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;
}
}

View file

@ -1,34 +1,36 @@
{ {
"$schema": "https://getcomposer.org/schema.json", "$schema": "https://getcomposer.org/schema.json",
"name": "laravel/react-starter-kit", "name": "lvl0/fedi-feed-router",
"type": "project", "type": "project",
"description": "The skeleton application for the Laravel framework.", "description": "Routes news articles from RSS and scraped sources to Fediverse communities.",
"keywords": [ "keywords": [
"laravel", "fediverse",
"framework" "lemmy",
"rss",
"atom",
"laravel"
], ],
"license": "MIT", "homepage": "https://forge.lvl0.xyz/lvl0/fedi-feed-router",
"license": "AGPL-3.0-only",
"require": { "require": {
"php": "^8.2", "php": "^8.2",
"ext-gd": "*",
"blade-ui-kit/blade-heroicons": "^2.6", "blade-ui-kit/blade-heroicons": "^2.6",
"inertiajs/inertia-laravel": "^2.0",
"laravel/framework": "^12.0", "laravel/framework": "^12.0",
"laravel/horizon": "^5.29", "laravel/horizon": "^5.29",
"laravel/sanctum": "^4.2", "laravel/sanctum": "^4.2",
"laravel/tinker": "^2.10.1", "laravel/tinker": "^2.10.1",
"livewire/livewire": "^4.0", "livewire/livewire": "^4.0"
"tightenco/ziggy": "^2.4"
}, },
"require-dev": { "require-dev": {
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",
"larastan/larastan": "^3.5", "larastan/larastan": "^3.5",
"laravel/breeze": "^2.3",
"laravel/pail": "^1.2.2", "laravel/pail": "^1.2.2",
"laravel/pint": "^1.18", "laravel/pint": "^1.18",
"laravel/sail": "^1.43", "laravel/sail": "^1.43",
"mockery/mockery": "^1.6", "mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6", "nunomaduro/collision": "^8.6",
"phpstan/phpstan": "^2.1", "phpstan/phpstan": "^2.1.32 <2.2",
"phpstan/phpstan-mockery": "^2.0", "phpstan/phpstan-mockery": "^2.0",
"phpunit/phpunit": "^11.5.3" "phpunit/phpunit": "^11.5.3"
}, },
@ -64,11 +66,6 @@
"Composer\\Config::disableProcessTimeout", "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" "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": [ "test": [
"@php artisan config:clear --ansi", "@php artisan config:clear --ansi",
"@php artisan test" "@php artisan test"

8755
composer.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -13,7 +13,7 @@
| |
*/ */
'name' => env('APP_NAME', 'Laravel'), 'name' => 'Fedi Feed Router',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View file

@ -2,6 +2,7 @@
use App\Services\Parsers\BelgaArticlePageParser; use App\Services\Parsers\BelgaArticlePageParser;
use App\Services\Parsers\BelgaArticleParser; use App\Services\Parsers\BelgaArticleParser;
use App\Services\Parsers\BelgaHomepageParserAdapter;
use App\Services\Parsers\GuardianArticlePageParser; use App\Services\Parsers\GuardianArticlePageParser;
use App\Services\Parsers\GuardianArticleParser; use App\Services\Parsers\GuardianArticleParser;
use App\Services\Parsers\VrtArticlePageParser; use App\Services\Parsers\VrtArticlePageParser;
@ -41,12 +42,14 @@
'code' => 'belga', 'code' => 'belga',
'name' => 'Belga News Agency', 'name' => 'Belga News Agency',
'description' => 'Belgian national news agency', 'description' => 'Belgian national news agency',
'type' => 'rss', 'type' => 'website',
'is_active' => true, 'is_active' => true,
'languages' => [ 'languages' => [
'en' => ['url' => 'https://www.belganewsagency.eu/feed'], // 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'],
], ],
'parsers' => [ 'parsers' => [
'homepage' => BelgaHomepageParserAdapter::class,
'article' => BelgaArticleParser::class, 'article' => BelgaArticleParser::class,
'article_page' => BelgaArticlePageParser::class, 'article_page' => BelgaArticlePageParser::class,
], ],

View file

@ -0,0 +1,50 @@
<?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(),
]);
}
}

View file

@ -24,9 +24,22 @@ public function definition(): array
'title' => $this->faker->sentence(), 'title' => $this->faker->sentence(),
'description' => $this->faker->paragraph(), 'description' => $this->faker->paragraph(),
'content' => $this->faker->paragraphs(3, true), 'content' => $this->faker->paragraphs(3, true),
'image_url' => $this->faker->optional()->imageUrl(), 'image_url' => $this->faker->imageUrl(),
'published_at' => $this->faker->optional()->dateTimeBetween('-1 month', 'now'), 'published_at' => $this->faker->optional()->dateTimeBetween('-1 month', 'now'),
'author' => $this->faker->optional()->name(), '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