Compare commits
85 Commits
74f606459f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| aa14b4c185 | |||
| 06a18eac3d | |||
| a8debe2f51 | |||
| 548f2350d2 | |||
| 3f5803d4fc | |||
| 60bd906251 | |||
| 7d888ea4cb | |||
| 3b14c3453c | |||
| 842943e7e8 | |||
| aa6de883be | |||
| 26a35719eb | |||
| 3844a32751 | |||
| b41e67fe1a | |||
| 9bcb21910d | |||
| a116ec2614 | |||
| 6f204d4164 | |||
| de803dea9f | |||
| a520944fe3 | |||
| 22a836cb95 | |||
| 12967c573b | |||
| 14233e88a8 | |||
| 2bcb47a1a1 | |||
| 8636dfedb9 | |||
| c20b1c2691 | |||
| 0b6ffedb70 | |||
| a14b78a1b9 | |||
| 254541a370 | |||
| f390bf82cc | |||
| b96b7d7a93 | |||
| 37171478b1 | |||
| 00364aca23 | |||
| 3d97ccf38c | |||
| 1e22bacdc9 | |||
| 8d10f75f2b | |||
| 68dca953f2 | |||
| c684fcb858 | |||
| 2b5745b946 | |||
| b56f8253d9 | |||
| 798c8e7f50 | |||
| 0e7f34edc7 | |||
| 7aff171ef8 | |||
| cc6a423ef0 | |||
| 759614e92d | |||
| 81c5684102 | |||
| a911e6ca69 | |||
| 66f32cdbd2 | |||
| 390f69858c | |||
| c3db00abf2 | |||
| 4a0300d4b4 | |||
| 18b50f1ce6 | |||
| 4d154ff837 | |||
| 869d9a168e | |||
| fc9d3c97bf | |||
| 0dc1c278c2 | |||
| a0f99d9fba | |||
| 8f3c369ed8 | |||
| 81f5fafb61 | |||
| c335bf14d6 | |||
| d344497393 | |||
| ee97ec9b23 | |||
| 34934e7d13 | |||
| 1d472d382b | |||
| 4ebe886579 | |||
| dd5412cb79 | |||
| 4000baf755 | |||
| a15aa040f4 | |||
| a03cce3e04 | |||
| 400d100426 | |||
| 7afd1be81b | |||
| cdcef5ba96 | |||
| 494f61f9c6 | |||
| 67771777cd | |||
| c4c642073d | |||
| 8da6364e6e | |||
| 6f2a32aabb | |||
| 75f4608d34 | |||
| 2e3d5f4dbe | |||
| 258d97757c | |||
| 4edc5b1b22 | |||
| bfefbb1d2a | |||
| 5d3c73d537 | |||
| 4c8573767d | |||
| 4d16dd8d17 | |||
| d04496ad11 | |||
| 6edca785ff |
@@ -10,9 +10,12 @@ jobs:
|
||||
steps:
|
||||
- name: Pull changes
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
run: |
|
||||
git config --global --add safe.directory /home/adamf/deploy/web_server
|
||||
git pull http://gitea:3000/adamf/web_server.git main
|
||||
git fetch ssh://git@localhost:2222/adamf/web_server.git main
|
||||
git reset --hard FETCH_HEAD
|
||||
|
||||
- name: Run docker compose up
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
|
||||
11
.gitignore
vendored
11
.gitignore
vendored
@@ -6,14 +6,20 @@ certbot/www
|
||||
backend/token/
|
||||
.env
|
||||
|
||||
gitea/config/app.ini
|
||||
gitea/data/*
|
||||
gitea/config/app.ini
|
||||
|
||||
gitea-runner/data/*
|
||||
# Gitea runner
|
||||
gitea-runner/.runner
|
||||
gitea-runner/act_runner
|
||||
gitea-runner/nohup.out
|
||||
|
||||
# Rust build artifacts
|
||||
**/target/
|
||||
|
||||
# Generated WASM output
|
||||
vue/src/wasm/
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
@@ -55,3 +61,4 @@ __screenshots__/
|
||||
|
||||
.deploy
|
||||
*.xcf
|
||||
sync-secrets.sh
|
||||
|
||||
359
README.md
Normal file
359
README.md
Normal file
@@ -0,0 +1,359 @@
|
||||
# My Web
|
||||
|
||||

|
||||
|
||||
Welcome to the source code for my website! Please contact me if you would like to collaborate and thank you for visiting.
|
||||
|
||||
This website is self-hosted on my Raspberry Pi. Any interference or hax and the killswitch will activate and stop the UK national grid power system so please don't tamper with my domain :).
|
||||
|
||||
## The use of AI
|
||||
|
||||
This has been created with a heavy amount of AI. Initially, I began with articles from [medium](https://medium.com/) informing me of how to use Nginx to host static sites and reverse proxy to other services. They were incredible helpful and I wish I were able to give credit them, but sadly they were read too long ago.
|
||||
|
||||
After hearing all the hype on LinkedIn and feeling the pressure to keep up a high output without AI, I eventually caved in. There is an immense advantage not having to scan though documentation to find relevant functions, asking how other developers implement their infrastructure and finding what command will achieve your outcome quickly. Sure, it would be good to have that already cached in your own human memory. But my reasoning is that you _will_ have cached it after being reminded by AI enough times, similar to how flashcards work. I may not be an expert in the specific tool, though I've been able to get good enough at it for my own purposes.
|
||||
|
||||
## Architecture
|
||||
|
||||
All services run in Docker containers orchestrated by Docker Compose behind Nginx as a reverse proxy on a single bridge network.
|
||||
|
||||
```
|
||||
vue ── Frontend build (outputs dist to shared volume)
|
||||
nginx (80, 443) ── Frontend SPA + Reverse Proxy
|
||||
backend (8080) ── Go API (GraphQL + REST)
|
||||
db (5432) ── PostgreSQL 16
|
||||
icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap)
|
||||
gitea (3000) ── Self-Hosted Git
|
||||
quartz (8080) ── Obsidian Notes Publisher (Quartz v4.4.0)
|
||||
searxng (8080) ── Meta Search Engine
|
||||
hasura (8080) ── Hasura GraphQL Engine (Docker profile: hasura)
|
||||
autoheal ── Auto-restart unhealthy containers
|
||||
certbot ── SSL Certificate Management (disabled in dev)
|
||||
```
|
||||
|
||||
## Tech Stack
|
||||
|
||||
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), Rust/WASM
|
||||
|
||||
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
|
||||
|
||||
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
|
||||
|
||||
**Infrastructure** - Docker Compose, Nginx, Let's Encrypt (Certbot), Gitea + Act Runner
|
||||
|
||||
## Features
|
||||
|
||||
- Spotify integration (currently playing, recently played)
|
||||
- Steam integration (online status, recent games)
|
||||
- Obsidian note viewer via Quartz
|
||||
- Live radio streaming via Icecast2 + Liquidsoap
|
||||
- Real-time chat over WebSockets with image/video uploads
|
||||
- Blog with admin panel (CRUD)
|
||||
- Activity and rowing session tracking
|
||||
- AI image processing integration to extract rowing data from images (will be superseeded by openCV scanning)
|
||||
- Fan shrines (GTO, Evangelion, Demoman, Skip Skip Benben)
|
||||
- Self-hosted Git (Gitea) with CI/CD and commit feed on homepage
|
||||
- Printable CV with role-specific sections
|
||||
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
|
||||
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
|
||||
- SearXNG meta search engine (admin-only)
|
||||
- Hasura GraphQL console (admin-only)
|
||||
- Admin-gated routes: `/searxng`, `/notes`, `/hasura` require admin JWT via Nginx `auth_request`
|
||||
- Landing page with animated stamps section
|
||||
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
||||
- Backend healthcheck with autoheal container for automatic recovery
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | Description |
|
||||
| -------------- | -------------------------------------------------- |
|
||||
| `/` | Landing page |
|
||||
| `/stp` | Home dashboard with grid layout |
|
||||
| `/admin` | Admin login + panel (authenticated) |
|
||||
| `/cv` | Curriculum Vitae (printable) |
|
||||
| `/cv/jobs` | Job application tracker (admin-only, hidden print) |
|
||||
| `/bookmarks` | Bookmarks (database-backed, grouped by category) |
|
||||
| `/notes/:path` | Obsidian note viewer (via Quartz, admin-only) |
|
||||
| `/shrines` | Fan shrine index + individual shrines |
|
||||
|
||||
## API
|
||||
|
||||
### GraphQL
|
||||
|
||||
**Endpoint:** `POST /api/graphql`
|
||||
**Playground:** `GET /api/graphql` (when `GQL_PLAYGROUND=true`)
|
||||
|
||||
| Operation | Type | Description |
|
||||
| ------------------------------------------ | -------- | ----------------------- |
|
||||
| `users` | Query | Get all users |
|
||||
| `user(id)` | Query | Get user by ID |
|
||||
| `me` | Query | Get authenticated user |
|
||||
| `posts` | Query | Get all posts |
|
||||
| `post(id)` | Query | Get post by ID |
|
||||
| `activities` | Query | Get all activities |
|
||||
| `favorites` | Query | Get all favorites |
|
||||
| `rowingSessions` | Query | Get all rowing sessions |
|
||||
| `post(id)` | Query | Get post by ID |
|
||||
| `activities` | Query | Get all activities |
|
||||
| `favorites` | Query | Get all favorites |
|
||||
| `rowingSessions` | Query | Get all rowing sessions |
|
||||
| `messages` | Query | Get all messages |
|
||||
| `spotifyListening` | Query | Currently playing track |
|
||||
| `spotifyRecent` | Query | Recently played tracks |
|
||||
| `giteaFeed` | Query | Latest Gitea activity |
|
||||
| `steamStatus` | Query | Steam online status |
|
||||
| `login` | Mutation | Authenticate user |
|
||||
| `logout` | Mutation | Logout |
|
||||
| `refreshToken` | Mutation | Refresh auth token |
|
||||
| `createPost` / `updatePost` / `deletePost` | Mutation | Post CRUD (admin) |
|
||||
| `createUser` / `deleteUser` | Mutation | User management (admin) |
|
||||
| `setUserAdmin` | Mutation | Toggle admin status |
|
||||
| `createFavorite` | Mutation | Add favorite (admin) |
|
||||
| `createActivity` | Mutation | Add activity (admin) |
|
||||
| `bookmarks` | Query | Get all bookmarks |
|
||||
| `createBookmark` / `deleteBookmark` | Mutation | Bookmark CRUD (admin) |
|
||||
| `jobApplications` | Query | Get all job applications (admin) |
|
||||
| `createJobApplication` / `updateJobApplication` / `deleteJobApplication` | Mutation | Job application CRUD (admin) |
|
||||
|
||||
### REST Endpoints
|
||||
|
||||
**Auth**
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/auth/login` | Login (rate limited: 5/min) |
|
||||
| POST | `/api/auth/refresh` | Refresh token |
|
||||
| GET | `/api/auth/check` | Check token validity |
|
||||
| POST | `/api/auth/logout` | Logout |
|
||||
| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Nginx auth_request) |
|
||||
|
||||
Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry.
|
||||
|
||||
**Spotify**
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/spotify/callback` | OAuth callback |
|
||||
| GET | `/api/spotify/listening` | Currently playing |
|
||||
| GET | `/api/spotify/recent` | Recently played |
|
||||
|
||||
**Public**
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/favorites` | Get all favorites |
|
||||
| GET | `/api/rowing` | Get all rowing sessions |
|
||||
| GET | `/api/activity` | Get all activities |
|
||||
| GET | `/api/posts` | Get all posts |
|
||||
| GET | `/api/posts/:id` | Get post by ID |
|
||||
| GET | `/api/user` | Get all users |
|
||||
| GET | `/api/user/:id` | Get user by ID |
|
||||
|
||||
**Protected (auth required)**
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/messages/upload` | Upload message file (rate limited: 5/min) |
|
||||
|
||||
**Admin (auth + admin required)**
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/favorites` | Create favorite |
|
||||
| POST | `/api/rowing` | Create rowing session |
|
||||
| POST | `/api/activity` | Create activity |
|
||||
| POST | `/api/posts` | Create post |
|
||||
| PUT | `/api/posts/:id` | Update post |
|
||||
| DELETE | `/api/posts/:id` | Delete post |
|
||||
| POST | `/api/user` | Create user |
|
||||
| PUT | `/api/user/:id` | Update user |
|
||||
| DELETE | `/api/user/:id` | Delete user |
|
||||
| PATCH | `/api/user/:id/admin` | Set/unset admin |
|
||||
| POST | `/api/radio/upload` | Upload radio song |
|
||||
| GET | `/api/radio/songs` | List radio songs |
|
||||
| DELETE | `/api/radio/songs/:filename` | Delete radio song |
|
||||
| PATCH | `/api/radio/songs/:filename/disable` | Disable radio song |
|
||||
| PATCH | `/api/radio/songs/:filename/enable` | Enable radio song |
|
||||
|
||||
**WebSocket**
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/ws` | WebSocket chat (10s ping keepalive) |
|
||||
|
||||
### Nginx Proxy Routes
|
||||
|
||||
| Route | Target | Notes |
|
||||
| ---------- | ------------ | ------------------------------------------ |
|
||||
| `/api` | backend:8080 | API (rate limited: 30r/s) |
|
||||
| `/radio` | icecast:8000 | Audio streaming |
|
||||
| `/gitea` | gitea:3000 | Git service |
|
||||
| `/hasura` | hasura:8080 | GraphQL console + WebSocket (admin-only) |
|
||||
| `/notes` | quartz:8080 | Obsidian notes (admin-only) |
|
||||
| `/searxng` | searxng:8080 | Search engine (admin-only) |
|
||||
| `/uploads` | local alias | User-uploaded files |
|
||||
|
||||
`/hasura`, `/notes`, and `/searxng` are protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
|
||||
|
||||
### Deprecated Endpoints
|
||||
|
||||
**Backend note API** (`GET /api/notes/*path`) - The backend has a REST endpoint that serves note files directly from the mounted Obsidian vault. This is superseded by the Quartz service which now handles note rendering at `/notes/`. The backend endpoint still exists in code but is no longer the primary note serving path.
|
||||
|
||||
## Setup
|
||||
|
||||
### `.env`
|
||||
|
||||
Create a `.env` file in the project root. All services read from this file.
|
||||
|
||||
| Variable | Description |
|
||||
| --------------------------------- | ------------------------------------------------------------------------------- |
|
||||
| `POSTGRES_USER` | PostgreSQL username |
|
||||
| `POSTGRES_PASSWORD` | PostgreSQL password |
|
||||
| `POSTGRES_DB` | Main app database name |
|
||||
| `POSTGRES_PORT` | PostgreSQL port (typically `5432`) |
|
||||
| `POSTGRES_HOST` | PostgreSQL hostname (use `db` for Docker) |
|
||||
| `GITEA_HOST` | Gitea hostname (use `gitea` for Docker) |
|
||||
| `GITEA_PORT` | Gitea HTTP port (typically `3000`) |
|
||||
| `GITEA_INTERNAL_TOKEN` | Gitea internal API token (generate with `gitea generate secret INTERNAL_TOKEN`) |
|
||||
| `GITEA_LFS_JWT_SECRET` | Gitea LFS JWT secret (generate with `gitea generate secret LFS_JWT_SECRET`) |
|
||||
| `GITEA_OAUTH2_JWT_SECRET` | Gitea OAuth2 JWT secret (generate with `gitea generate secret JWT_SECRET`) |
|
||||
| `POSTGRES_GITEA_DB` | Gitea database name |
|
||||
| `UPTIMEKUMA_HOST` | Uptime Kuma hostname (planned) |
|
||||
| `UPTIMEKUMA_PORT` | Uptime Kuma port (planned) |
|
||||
| `SEARXNG_HOST` | SearXNG hostname (use `searxng` for Docker) |
|
||||
| `SEARXNG_PORT` | SearXNG port (typically `8080`) |
|
||||
| `SEARXNG_SECRET_KEY` | SearXNG secret key (random hex string) |
|
||||
| `WALLABAG_HOST` | Wallabag hostname (planned) |
|
||||
| `WALLABAG_PORT` | Wallabag port (planned) |
|
||||
| `QUARTZ_HOST` | Quartz hostname (use `quartz` for Docker) |
|
||||
| `QUARTZ_PORT` | Quartz port (typically `8080`) |
|
||||
| `GITEA_RUNNER_HOST` | Gitea runner hostname |
|
||||
| `GITEA_RUNNER_NAME` | Gitea runner display name |
|
||||
| `GITEA_RUNNER_REGISTRATION_TOKEN` | Token to register Gitea Actions runner |
|
||||
| `BACKEND_PORT` | Backend port (typically `8080`) |
|
||||
| `BACKEND_HOST` | Backend hostname (use `backend` for Docker) |
|
||||
| `BACKEND_SECRET` | JWT signing secret |
|
||||
| `BACKEND_ENDPOINT` | API path prefix (typically `/api`) |
|
||||
| `OBSIDIAN_DIR` | Absolute path to Obsidian vault on host machine |
|
||||
| `SPOTIFY_CLIENT_ID` | Spotify app client ID |
|
||||
| `SPOTIFY_CLIENT_SECRET` | Spotify app client secret |
|
||||
| `SPOTIFY_REDIRECT_URI` | Spotify OAuth redirect (e.g. `https://www.<DOMAIN>/api/spotify/callback`) |
|
||||
| `SPOTIFY_AUTH_STATE` | Arbitrary state string for Spotify OAuth |
|
||||
| `ICECAST_SOURCE_PASSWORD` | Icecast source connection password |
|
||||
| `ICECAST_RELAY_PASSWORD` | Icecast relay password |
|
||||
| `ICECAST_ADMIN_USER` | Icecast admin username |
|
||||
| `ICECAST_ADMIN_PASSWORD` | Icecast admin password |
|
||||
| `ICECAST_HOST` | Icecast hostname (use `icecast` for Docker) |
|
||||
| `ICECAST_PORT` | Icecast port (typically `8000`) |
|
||||
| `ICECAST_MOUNT` | Icecast mount point (e.g. `/stream`) |
|
||||
| `LIQUIDSOAP_HARBOR_MOUNT` | Liquidsoap live input mount (e.g. `/live`) |
|
||||
| `LIQUIDSOAP_HARBOR_PORT` | Liquidsoap harbor port (e.g. `8005`) |
|
||||
| `DOMAIN` | Production domain name |
|
||||
| `EMAIL` | Email for Let's Encrypt registration |
|
||||
| `CLAUDE_API_KEY` | Anthropic Claude API key |
|
||||
| `STEAM_API_KEY` | Steam Web API key |
|
||||
| `STEAM_ID` | Steam user ID |
|
||||
| `HASURA_GRAPHQL_ADMIN_SECRET` | Hasura admin secret |
|
||||
| `HASURA_HOST` | Hasura hostname (use `hasura` for Docker) |
|
||||
| `HASURA_PORT` | Hasura port (typically `8080`) |
|
||||
| `SEED_DB` | Set to `true` to seed test data on startup |
|
||||
|
||||
### Gitea Config
|
||||
|
||||
Copy from the template and fill in secrets:
|
||||
|
||||
```sh
|
||||
cp gitea/config/app.ini.template gitea/config/app.ini
|
||||
```
|
||||
|
||||
Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the database `PASSWD`. Alternatively, the Gitea entrypoint generates `app.ini` from the template using environment variables.
|
||||
|
||||
### SearXNG Config
|
||||
|
||||
Copy from the template:
|
||||
|
||||
```sh
|
||||
cp searxng/settings.yml.template searxng/settings.yml
|
||||
```
|
||||
|
||||
The Docker entrypoint handles environment variable substitution (`${BASE_URL}`, `${SEARXNG_SECRET_KEY}`) automatically, so manual setup is only needed when running outside Docker.
|
||||
|
||||
### Spotify Token Setup
|
||||
|
||||
4. After authorization, Spotify redirects to the callback endpoint which stores tokens at `/backend/token/spotify_token.json`
|
||||
5. Tokens are refreshed automatically; the file persists across container restarts via volume mount
|
||||
|
||||
### Obsidian Notes Setup
|
||||
|
||||
1. Set `OBSIDIAN_DIR` in `.env` to the absolute path of your Obsidian vault on the host machine
|
||||
2. The vault is mounted read-only into the Quartz container at `/quartz/content`
|
||||
3. Quartz builds a static site from the vault on startup and serves it at `/notes/`
|
||||
4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above)
|
||||
|
||||
### SSL Certificates (Certbot)
|
||||
|
||||
**Initial setup (production):**
|
||||
|
||||
1. Set `DOMAIN` and `EMAIL` in `.env`
|
||||
2. On first run, Nginx starts with `nginx_setup.conf.template` which only serves the ACME challenge route at `/.well-known/acme-challenge/`
|
||||
3. Certbot requests a certificate via `certbot certonly --webroot`
|
||||
4. Once the certificate is issued to `certbot/conf/live/<DOMAIN>/`, restart Nginx — it will detect the certs and switch to the full `nginx.conf.template`
|
||||
5. Certbot checks for renewal every 12 hours automatically
|
||||
|
||||
**Dev mode:** Nginx generates a self-signed certificate for localhost automatically.
|
||||
|
||||
### Icecast Radio
|
||||
|
||||
Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays these as fallback when no live source is connected. Connect a live source to port 8001 on the `LIQUIDSOAP_HARBOR_MOUNT`.
|
||||
|
||||
### Gitea Runner
|
||||
|
||||
1. Download the `act_runner` binary from [Gitea releases](https://gitea.com/gitea/act_runner/releases) and place in `gitea-runner/`
|
||||
2. Set `GITEA_RUNNER_REGISTRATION_TOKEN` in `.env`
|
||||
3. The runner registers automatically on first startup
|
||||
|
||||
## Dev Mode
|
||||
|
||||
Run the full stack over plain HTTP without SSL certificates:
|
||||
|
||||
```sh
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
```
|
||||
|
||||
This:
|
||||
|
||||
- Uses an HTTP-only Nginx config with all routing (SPA, backend proxy, radio, gitea, etc.)
|
||||
- Generates a self-signed certificate for localhost
|
||||
- Disables certbot
|
||||
- Seeds the database with test data (`SEED_DB=true`)
|
||||
- Enables GraphQL playground and introspection
|
||||
- Enables Hasura console and dev mode
|
||||
|
||||
Visit `http://localhost` to test.
|
||||
|
||||
### Frontend only (hot reload)
|
||||
|
||||
```sh
|
||||
cd vue && npm run dev
|
||||
```
|
||||
|
||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
||||
|
||||
## Untracked Files
|
||||
|
||||
These files are git-ignored and must be created manually:
|
||||
|
||||
| File | Notes |
|
||||
| ------------------------------- | --------------------------------------------------------------- |
|
||||
| `.env` | See setup section above |
|
||||
| `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it |
|
||||
| `searxng/settings.yml` | Copy from `settings.yml.template` or let entrypoint generate it |
|
||||
| `certbot/conf/`, `certbot/www/` | Created automatically by certbot; use dev mode to skip |
|
||||
| `backend/token/` | Created automatically by Docker volume mount |
|
||||
| `icecast2/fallback_music/*.mp3` | Place at least one MP3 file |
|
||||
| `gitea-runner/act_runner` | Download from Gitea releases |
|
||||
| `gitea-runner/.runner` | Generated on first runner startup |
|
||||
|
||||
## Future Ideas
|
||||
|
||||
- More Rust to WASM
|
||||
- ML for chatboards
|
||||
- Cache requests
|
||||
- Design more webpages
|
||||
- Calendar to show radio times
|
||||
- Nice smooth function background and transitions
|
||||
- Design shrines
|
||||
- Redis (not really but practical experience)
|
||||
@@ -22,6 +22,7 @@ require (
|
||||
github.com/bytedance/sonic v1.14.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
|
||||
@@ -66,6 +66,15 @@ github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7c
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
github.com/emersion/go-imap v1.2.1 h1:+s9ZjMEjOB8NzZMVTM3cCenz2JrQIGGo5j1df19WjTA=
|
||||
github.com/emersion/go-imap v1.2.1/go.mod h1:Qlx1FSx2FTxjnjWpIlVNEuX+ylerZQNFE5NsmKFSejY=
|
||||
github.com/emersion/go-message v0.15.0/go.mod h1:wQUEfE+38+7EW8p8aZ96ptg6bAb1iwdgej19uXASlE4=
|
||||
github.com/emersion/go-message v0.18.2 h1:rl55SQdjd9oJcIoQNhubD2Acs1E6IzlZISRTK7x/Lpg=
|
||||
github.com/emersion/go-message v0.18.2/go.mod h1:XpJyL70LwRvq2a8rVbHXikPgKj8+aI0kGdHlg16ibYA=
|
||||
github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21/go.mod h1:iL2twTeMvZnrg54ZoPDNfJaJaqy0xIQFuBdrLsmspwQ=
|
||||
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 h1:oP4q0fw+fOSWn3DfFi4EXdT+B+gTtzx8GC9xsc26Znk=
|
||||
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6/go.mod h1:iL2twTeMvZnrg54ZoPDNfJaJaqy0xIQFuBdrLsmspwQ=
|
||||
github.com/emersion/go-textwrapper v0.0.0-20200911093747-65d896831594/go.mod h1:aqO8z8wPrjkscevZJFVE1wXJrLpC5LtJG7fqLOsPb2U=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -388,6 +397,7 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
|
||||
@@ -57,3 +57,21 @@ models:
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
Bookmark:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Bookmark
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobApplication:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobApplication
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobAppReference:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobAppReference
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
|
||||
@@ -7,7 +7,9 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
@@ -16,6 +18,33 @@ func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, e
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &activity, nil
|
||||
}
|
||||
|
||||
// Activities is the resolver for the activities field.
|
||||
func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, error) {
|
||||
var activities []models.Activity
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Activity, len(activities))
|
||||
for i := range activities {
|
||||
result[i] = &activities[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Activity returns ActivityResolver implementation.
|
||||
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
|
||||
|
||||
|
||||
146
backend/graph/auth.resolvers.go
Normal file
146
backend/graph/auth.resolvers.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// Login is the resolver for the login field.
|
||||
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
if !r.Store.LoginLimiter.Allow(gc.ClientIP()) {
|
||||
return nil, fmt.Errorf("too many login attempts, please try again later")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(input.Password)); err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
tokens, err := r.Store.Auth.GenerateJWT(&user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
// Logout is the resolver for the logout field.
|
||||
func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return false, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "/", r.Store.Auth.Config.Domain, true, true)
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RefreshToken is the resolver for the refreshToken field.
|
||||
func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload, error) {
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
refreshToken, err := gc.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
claims, err := r.Store.Auth.VerifyJWT(refreshToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
user.ID = uint(userIDF)
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
tokens, err := r.Store.Auth.GenerateJWT(&user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
// Me is the resolver for the me field.
|
||||
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
user.ID = userID
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
64
backend/graph/bookmark.resolvers.go
Normal file
64
backend/graph/bookmark.resolvers.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateBookmark is the resolver for the createBookmark field.
|
||||
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &bookmark, nil
|
||||
}
|
||||
|
||||
// DeleteBookmark is the resolver for the deleteBookmark field.
|
||||
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var bookmark models.Bookmark
|
||||
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.DB.Delete(&bookmark).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &bookmark, nil
|
||||
}
|
||||
|
||||
// Bookmarks is the resolver for the bookmarks field.
|
||||
func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, error) {
|
||||
var bookmarks []models.Bookmark
|
||||
if err := r.Store.DB.Order("category ASC, created_at ASC").Find(&bookmarks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Bookmark, len(bookmarks))
|
||||
for i := range bookmarks {
|
||||
result[i] = &bookmarks[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Bookmark returns BookmarkResolver implementation.
|
||||
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
|
||||
|
||||
type bookmarkResolver struct{ *Resolver }
|
||||
@@ -7,7 +7,9 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
@@ -16,6 +18,33 @@ func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, e
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateFavorite is the resolver for the createFavorite field.
|
||||
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &favorite, nil
|
||||
}
|
||||
|
||||
// Favorites is the resolver for the favorites field.
|
||||
func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, error) {
|
||||
var favorites []models.Favorite
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Favorite, len(favorites))
|
||||
for i := range favorites {
|
||||
result[i] = &favorites[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Favorite returns FavoriteResolver implementation.
|
||||
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
34
backend/graph/gitea.resolvers.go
Normal file
34
backend/graph/gitea.resolvers.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// GiteaFeed is the resolver for the giteaFeed field.
|
||||
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
|
||||
if r.Store.GiteaFeedFresh() {
|
||||
return mapGiteaFeed(r.Store.GiteaFeed), nil
|
||||
}
|
||||
|
||||
feed, err := services.FetchLatestFeed(r.Store.GiteaHost, r.Store.GiteaPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if feed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
r.Store.GiteaFeed = feed
|
||||
r.Store.GiteaFeedFetchedAt = time.Now()
|
||||
|
||||
return mapGiteaFeed(feed), nil
|
||||
}
|
||||
93
backend/graph/job_app_reference.resolvers.go
Normal file
93
backend/graph/job_app_reference.resolvers.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobAppReference is the resolver for the createJobAppReference field.
|
||||
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
ref := models.JobAppReference{
|
||||
Category: input.Category,
|
||||
Label: input.Label,
|
||||
Value: input.Value,
|
||||
}
|
||||
if input.SortOrder != nil {
|
||||
ref.SortOrder = *input.SortOrder
|
||||
}
|
||||
if err := r.Store.DB.Create(&ref).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ref, nil
|
||||
}
|
||||
|
||||
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
|
||||
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var ref models.JobAppReference
|
||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Category != nil {
|
||||
ref.Category = *input.Category
|
||||
}
|
||||
if input.Label != nil {
|
||||
ref.Label = *input.Label
|
||||
}
|
||||
if input.Value != nil {
|
||||
ref.Value = *input.Value
|
||||
}
|
||||
if input.SortOrder != nil {
|
||||
ref.SortOrder = *input.SortOrder
|
||||
}
|
||||
if err := r.Store.DB.Save(&ref).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ref, nil
|
||||
}
|
||||
|
||||
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
|
||||
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// JobAppReferences is the resolver for the jobAppReferences field.
|
||||
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var refs []*models.JobAppReference
|
||||
if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
|
||||
// JobAppReference returns JobAppReferenceResolver implementation.
|
||||
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
|
||||
|
||||
type jobAppReferenceResolver struct{ *Resolver }
|
||||
115
backend/graph/job_application.resolvers.go
Normal file
115
backend/graph/job_application.resolvers.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobApplication is the resolver for the createJobApplication field.
|
||||
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
app := models.JobApplication{
|
||||
JobTitle: input.JobTitle,
|
||||
Company: input.Company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: input.Status,
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
}
|
||||
if err := r.Store.DB.Create(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// UpdateJobApplication is the resolver for the updateJobApplication field.
|
||||
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.JobTitle != nil {
|
||||
app.JobTitle = *input.JobTitle
|
||||
}
|
||||
if input.Company != nil {
|
||||
app.Company = *input.Company
|
||||
}
|
||||
if input.Location != nil {
|
||||
app.Location = input.Location
|
||||
}
|
||||
if input.URL != nil {
|
||||
app.URL = input.URL
|
||||
}
|
||||
if input.Status != nil {
|
||||
app.Status = *input.Status
|
||||
}
|
||||
if input.Notes != nil {
|
||||
app.Notes = input.Notes
|
||||
}
|
||||
if input.AppliedAt != nil {
|
||||
app.AppliedAt = input.AppliedAt
|
||||
}
|
||||
if err := r.Store.DB.Save(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// DeleteJobApplication is the resolver for the deleteJobApplication field.
|
||||
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// JobApplications is the resolver for the jobApplications field.
|
||||
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var apps []*models.JobApplication
|
||||
if err := r.Store.DB.Order("created_at desc").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return apps, nil
|
||||
}
|
||||
|
||||
// JobApplication is the resolver for the jobApplication field.
|
||||
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// JobApplication returns JobApplicationResolver implementation.
|
||||
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
|
||||
|
||||
type jobApplicationResolver struct{ *Resolver }
|
||||
@@ -21,6 +21,19 @@ func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (in
|
||||
return int(obj.AuthorID), nil
|
||||
}
|
||||
|
||||
// Messages is the resolver for the messages field.
|
||||
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
||||
var messages []models.Message
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Message, len(messages))
|
||||
for i := range messages {
|
||||
result[i] = &messages[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Message returns MessageResolver implementation.
|
||||
func (r *Resolver) Message() MessageResolver { return &messageResolver{r} }
|
||||
|
||||
|
||||
@@ -18,12 +18,35 @@ type CreateActivityInput struct {
|
||||
Link *string `json:"link,omitempty"`
|
||||
}
|
||||
|
||||
type CreateBookmarkInput struct {
|
||||
Category string `json:"category"`
|
||||
Name string `json:"name"`
|
||||
Link string `json:"link"`
|
||||
}
|
||||
|
||||
type CreateFavoriteInput struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Link *string `json:"link,omitempty"`
|
||||
}
|
||||
|
||||
type CreateJobAppReferenceInput struct {
|
||||
Category string `json:"category"`
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
SortOrder *int `json:"sortOrder,omitempty"`
|
||||
}
|
||||
|
||||
type CreateJobApplicationInput struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
}
|
||||
|
||||
type CreatePostInput struct {
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
@@ -96,6 +119,23 @@ type SteamStatus struct {
|
||||
RecentGames []*SteamGame `json:"recentGames"`
|
||||
}
|
||||
|
||||
type UpdateJobAppReferenceInput struct {
|
||||
Category *string `json:"category,omitempty"`
|
||||
Label *string `json:"label,omitempty"`
|
||||
Value *string `json:"value,omitempty"`
|
||||
SortOrder *int `json:"sortOrder,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateJobApplicationInput struct {
|
||||
JobTitle *string `json:"jobTitle,omitempty"`
|
||||
Company *string `json:"company,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
}
|
||||
|
||||
type UpdatePostInput struct {
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
|
||||
@@ -7,15 +7,111 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// CreatePost is the resolver for the createPost field.
|
||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
|
||||
if err := r.Store.DB.Create(&post).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// UpdatePost is the resolver for the updatePost field.
|
||||
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
var post models.Post
|
||||
if err := r.Store.DB.First(&post, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
|
||||
post.Title = input.Title
|
||||
post.Content = input.Content
|
||||
if err := r.Store.DB.Save(&post).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// DeletePost is the resolver for the deletePost field.
|
||||
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
var post models.Post
|
||||
if err := r.Store.DB.First(&post, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only delete your own posts")
|
||||
}
|
||||
|
||||
r.Store.DB.Delete(&post)
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Posts is the resolver for the posts field.
|
||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
var posts []models.Post
|
||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Post, len(posts))
|
||||
for i := range posts {
|
||||
result[i] = &posts[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Post is the resolver for the post field.
|
||||
func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error) {
|
||||
var post models.Post
|
||||
if err := r.Store.DB.Preload("Author").First(&post, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Post returns PostResolver implementation.
|
||||
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
||||
|
||||
|
||||
@@ -11,6 +11,19 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// RowingSessions is the resolver for the rowingSessions field.
|
||||
func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, error) {
|
||||
var rows []models.Rowing
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Rowing, len(rows))
|
||||
for i := range rows {
|
||||
result[i] = &rows[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
|
||||
@@ -5,505 +5,6 @@ package graph
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
spotify "github.com/zmb3/spotify/v2"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// Login is the resolver for the login field.
|
||||
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(input.Password)); err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
tokens, err := r.Store.Auth.GenerateJWT(&user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
r.Store.Auth.Config.Endpoint,
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
r.Store.Auth.Config.Endpoint,
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
// Logout is the resolver for the logout field.
|
||||
func (r *mutationResolver) Logout(ctx context.Context) (bool, error) {
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return false, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie("access_token", "", -1, "", "", true, true)
|
||||
gc.SetCookie("refresh_token", "", -1, "", "", true, true)
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RefreshToken is the resolver for the refreshToken field.
|
||||
func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload, error) {
|
||||
gc := GinContextFromCtx(ctx)
|
||||
if gc == nil {
|
||||
return nil, fmt.Errorf("could not get gin context")
|
||||
}
|
||||
|
||||
refreshToken, err := gc.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
claims, err := r.Store.Auth.VerifyJWT(refreshToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
user.ID = uint(userIDF)
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
tokens, err := r.Store.Auth.GenerateJWT(&user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate tokens")
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteLaxMode)
|
||||
gc.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(r.Store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
r.Store.Auth.Config.Endpoint,
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
gc.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(r.Store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
r.Store.Auth.Config.Endpoint,
|
||||
r.Store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
return &model.AuthPayload{User: &user}, nil
|
||||
}
|
||||
|
||||
// CreatePost is the resolver for the createPost field.
|
||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
|
||||
if err := r.Store.DB.Create(&post).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// UpdatePost is the resolver for the updatePost field.
|
||||
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
var post models.Post
|
||||
if err := r.Store.DB.First(&post, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
|
||||
post.Title = input.Title
|
||||
post.Content = input.Content
|
||||
if err := r.Store.DB.Save(&post).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// DeletePost is the resolver for the deletePost field.
|
||||
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
var post models.Post
|
||||
if err := r.Store.DB.First(&post, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only delete your own posts")
|
||||
}
|
||||
|
||||
r.Store.DB.Delete(&post)
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// CreateUser is the resolver for the createUser field.
|
||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user := models.User{Username: input.Username, Password: hashedPassword}
|
||||
if err := r.Store.DB.Create(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// DeleteUser is the resolver for the deleteUser field.
|
||||
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
if err := r.Store.DB.Delete(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// SetUserAdmin is the resolver for the setUserAdmin field.
|
||||
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
callerID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
if uint(id) == callerID {
|
||||
return nil, fmt.Errorf("cannot change your own admin status")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
user.Admin = admin
|
||||
if err := r.Store.DB.Save(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// CreateFavorite is the resolver for the createFavorite field.
|
||||
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &favorite, nil
|
||||
}
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &activity, nil
|
||||
}
|
||||
|
||||
// Users is the resolver for the users field.
|
||||
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
var users []models.User
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.User, len(users))
|
||||
for i := range users {
|
||||
result[i] = &users[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// User is the resolver for the user field.
|
||||
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Posts is the resolver for the posts field.
|
||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
var posts []models.Post
|
||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Post, len(posts))
|
||||
for i := range posts {
|
||||
result[i] = &posts[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Post is the resolver for the post field.
|
||||
func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error) {
|
||||
var post models.Post
|
||||
if err := r.Store.DB.Preload("Author").First(&post, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Activities is the resolver for the activities field.
|
||||
func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, error) {
|
||||
var activities []models.Activity
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&activities).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Activity, len(activities))
|
||||
for i := range activities {
|
||||
result[i] = &activities[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Favorites is the resolver for the favorites field.
|
||||
func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, error) {
|
||||
var favorites []models.Favorite
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&favorites).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Favorite, len(favorites))
|
||||
for i := range favorites {
|
||||
result[i] = &favorites[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// RowingSessions is the resolver for the rowingSessions field.
|
||||
func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, error) {
|
||||
var rows []models.Rowing
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Rowing, len(rows))
|
||||
for i := range rows {
|
||||
result[i] = &rows[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Messages is the resolver for the messages field.
|
||||
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
||||
var messages []models.Message
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.Message, len(messages))
|
||||
for i := range messages {
|
||||
result[i] = &messages[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SpotifyListening is the resolver for the spotifyListening field.
|
||||
func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error) {
|
||||
if r.Store.SpotifyClient == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
playing, err := r.Store.SpotifyClient.PlayerCurrentlyPlaying(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := &model.SpotifyPlaying{Playing: playing.Playing}
|
||||
if playing.Item != nil {
|
||||
result.Track = mapSpotifyTrack(playing.Item)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SpotifyRecent is the resolver for the spotifyRecent field.
|
||||
func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRecentItem, error) {
|
||||
if r.Store.SpotifyClient == nil {
|
||||
return []*model.SpotifyRecentItem{}, nil
|
||||
}
|
||||
|
||||
if r.Store.RecentSongsFresh() {
|
||||
return mapRecentItems(*r.Store.RecentSongs), nil
|
||||
}
|
||||
|
||||
opts := spotify.RecentlyPlayedOptions{Limit: 3}
|
||||
played, err := r.Store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
r.Store.RecentSongs = &played
|
||||
r.Store.RecentSongsFetchedAt = time.Now()
|
||||
|
||||
return mapRecentItems(played), nil
|
||||
}
|
||||
|
||||
// GiteaFeed is the resolver for the giteaFeed field.
|
||||
func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, error) {
|
||||
if r.Store.GiteaFeedFresh() {
|
||||
return mapGiteaFeed(r.Store.GiteaFeed), nil
|
||||
}
|
||||
|
||||
feed, err := services.FetchLatestFeed(r.Store.GiteaHost, r.Store.GiteaPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if feed == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
r.Store.GiteaFeed = feed
|
||||
r.Store.GiteaFeedFetchedAt = time.Now()
|
||||
|
||||
return mapGiteaFeed(feed), nil
|
||||
}
|
||||
|
||||
// SteamStatus is the resolver for the steamStatus field.
|
||||
func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, error) {
|
||||
if r.Store.SteamAPIKey == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if r.Store.SteamFresh() {
|
||||
return &model.SteamStatus{
|
||||
Online: r.Store.SteamOnline,
|
||||
RecentGames: mapSteamGames(r.Store.SteamRecentGames),
|
||||
}, nil
|
||||
}
|
||||
|
||||
games, err := services.FetchRecentlyPlayedGames(r.Store.SteamAPIKey, r.Store.SteamID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
summary, err := services.FetchPlayerSummary(r.Store.SteamAPIKey, r.Store.SteamID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
online := false
|
||||
if summary != nil {
|
||||
online = summary.PersonaState > 0
|
||||
}
|
||||
|
||||
r.Store.SteamRecentGames = games
|
||||
r.Store.SteamOnline = online
|
||||
r.Store.SteamFetchedAt = time.Now()
|
||||
|
||||
return &model.SteamStatus{
|
||||
Online: online,
|
||||
RecentGames: mapSteamGames(games),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Me is the resolver for the me field.
|
||||
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
user.ID = userID
|
||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Mutation returns MutationResolver implementation.
|
||||
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
|
||||
|
||||
|
||||
@@ -12,3 +12,11 @@ input CreateActivityInput {
|
||||
name: String!
|
||||
link: String
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
activities: [Activity!]!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createActivity(input: CreateActivityInput!): Activity!
|
||||
}
|
||||
|
||||
@@ -6,3 +6,13 @@ input LoginInput {
|
||||
type AuthPayload {
|
||||
user: User!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
me: User
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
login(input: LoginInput!): AuthPayload!
|
||||
logout: Boolean!
|
||||
refreshToken: AuthPayload!
|
||||
}
|
||||
|
||||
23
backend/graph/schema/bookmark.graphql
Normal file
23
backend/graph/schema/bookmark.graphql
Normal file
@@ -0,0 +1,23 @@
|
||||
type Bookmark {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
category: String!
|
||||
name: String!
|
||||
link: String!
|
||||
}
|
||||
|
||||
input CreateBookmarkInput {
|
||||
category: String!
|
||||
name: String!
|
||||
link: String!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
bookmarks: [Bookmark!]!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark!
|
||||
deleteBookmark(id: ID!): Bookmark!
|
||||
}
|
||||
@@ -12,3 +12,11 @@ input CreateFavoriteInput {
|
||||
name: String!
|
||||
link: String
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
favorites: [Favorite!]!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite!
|
||||
}
|
||||
|
||||
@@ -6,3 +6,7 @@ type GiteaFeedItem {
|
||||
commitMessage: String!
|
||||
createdAt: Time!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
giteaFeed: GiteaFeedItem
|
||||
}
|
||||
|
||||
33
backend/graph/schema/job_app_reference.graphql
Normal file
33
backend/graph/schema/job_app_reference.graphql
Normal file
@@ -0,0 +1,33 @@
|
||||
type JobAppReference {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
category: String!
|
||||
label: String!
|
||||
value: String!
|
||||
sortOrder: Int!
|
||||
}
|
||||
|
||||
input CreateJobAppReferenceInput {
|
||||
category: String!
|
||||
label: String!
|
||||
value: String!
|
||||
sortOrder: Int
|
||||
}
|
||||
|
||||
input UpdateJobAppReferenceInput {
|
||||
category: String
|
||||
label: String
|
||||
value: String
|
||||
sortOrder: Int
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobAppReferences: [JobAppReference!]!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
|
||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
|
||||
deleteJobAppReference(id: ID!): Boolean!
|
||||
}
|
||||
43
backend/graph/schema/job_application.graphql
Normal file
43
backend/graph/schema/job_application.graphql
Normal file
@@ -0,0 +1,43 @@
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
jobTitle: String!
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
}
|
||||
|
||||
input CreateJobApplicationInput {
|
||||
jobTitle: String!
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
}
|
||||
|
||||
input UpdateJobApplicationInput {
|
||||
jobTitle: String
|
||||
company: String
|
||||
location: String
|
||||
url: String
|
||||
status: String
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobApplications: [JobApplication!]!
|
||||
jobApplication(id: ID!): JobApplication
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
|
||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
|
||||
deleteJobApplication(id: ID!): Boolean!
|
||||
}
|
||||
@@ -5,3 +5,7 @@ type Message {
|
||||
fileUrl: String
|
||||
createdAt: Time!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
messages: [Message!]!
|
||||
}
|
||||
|
||||
@@ -16,3 +16,14 @@ input UpdatePostInput {
|
||||
title: String!
|
||||
content: String!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
posts: [Post!]!
|
||||
post(id: ID!): Post
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createPost(input: CreatePostInput!): Post!
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post!
|
||||
deletePost(id: ID!): Post!
|
||||
}
|
||||
|
||||
@@ -7,3 +7,7 @@ type Rowing {
|
||||
timePer500m: Float!
|
||||
calories: Float!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
rowingSessions: [Rowing!]!
|
||||
}
|
||||
|
||||
@@ -1,31 +1,4 @@
|
||||
scalar Time
|
||||
|
||||
type Query {
|
||||
users: [User!]!
|
||||
user(id: ID!): User
|
||||
posts: [Post!]!
|
||||
post(id: ID!): Post
|
||||
activities: [Activity!]!
|
||||
favorites: [Favorite!]!
|
||||
rowingSessions: [Rowing!]!
|
||||
messages: [Message!]!
|
||||
spotifyListening: SpotifyPlaying
|
||||
spotifyRecent: [SpotifyRecentItem!]
|
||||
giteaFeed: GiteaFeedItem
|
||||
steamStatus: SteamStatus
|
||||
me: User
|
||||
}
|
||||
|
||||
type Mutation {
|
||||
login(input: LoginInput!): AuthPayload!
|
||||
logout: Boolean!
|
||||
refreshToken: AuthPayload!
|
||||
createPost(input: CreatePostInput!): Post!
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post!
|
||||
deletePost(id: ID!): Post!
|
||||
createUser(input: CreateUserInput!): User!
|
||||
deleteUser(id: ID!): User!
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User!
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite!
|
||||
createActivity(input: CreateActivityInput!): Activity!
|
||||
}
|
||||
type Query
|
||||
type Mutation
|
||||
|
||||
@@ -26,3 +26,8 @@ type SpotifyRecentItem {
|
||||
track: SpotifyTrack!
|
||||
playedAt: Time!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
spotifyListening: SpotifyPlaying
|
||||
spotifyRecent: [SpotifyRecentItem!]
|
||||
}
|
||||
|
||||
@@ -10,3 +10,7 @@ type SteamStatus {
|
||||
online: Boolean!
|
||||
recentGames: [SteamGame!]!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
steamStatus: SteamStatus
|
||||
}
|
||||
|
||||
@@ -10,3 +10,14 @@ input CreateUserInput {
|
||||
username: String!
|
||||
password: String!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
users: [User!]!
|
||||
user(id: ID!): User
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createUser(input: CreateUserInput!): User!
|
||||
deleteUser(id: ID!): User!
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User!
|
||||
}
|
||||
|
||||
55
backend/graph/spotify.resolvers.go
Normal file
55
backend/graph/spotify.resolvers.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
spotify "github.com/zmb3/spotify/v2"
|
||||
)
|
||||
|
||||
// SpotifyListening is the resolver for the spotifyListening field.
|
||||
func (r *queryResolver) SpotifyListening(ctx context.Context) (*model.SpotifyPlaying, error) {
|
||||
if r.Store.SpotifyClient == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
playing, err := r.Store.SpotifyClient.PlayerCurrentlyPlaying(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := &model.SpotifyPlaying{Playing: playing.Playing}
|
||||
if playing.Item != nil {
|
||||
result.Track = mapSpotifyTrack(playing.Item)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// SpotifyRecent is the resolver for the spotifyRecent field.
|
||||
func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRecentItem, error) {
|
||||
if r.Store.SpotifyClient == nil {
|
||||
return []*model.SpotifyRecentItem{}, nil
|
||||
}
|
||||
|
||||
if r.Store.RecentSongsFresh() {
|
||||
return mapRecentItems(*r.Store.RecentSongs), nil
|
||||
}
|
||||
|
||||
opts := spotify.RecentlyPlayedOptions{Limit: 3}
|
||||
played, err := r.Store.SpotifyClient.PlayerRecentlyPlayedOpt(ctx, &opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
r.Store.RecentSongs = &played
|
||||
r.Store.RecentSongsFetchedAt = time.Now()
|
||||
|
||||
return mapRecentItems(played), nil
|
||||
}
|
||||
52
backend/graph/steam.resolvers.go
Normal file
52
backend/graph/steam.resolvers.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.88
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// SteamStatus is the resolver for the steamStatus field.
|
||||
func (r *queryResolver) SteamStatus(ctx context.Context) (*model.SteamStatus, error) {
|
||||
if r.Store.SteamAPIKey == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if r.Store.SteamFresh() {
|
||||
return &model.SteamStatus{
|
||||
Online: r.Store.SteamOnline,
|
||||
RecentGames: mapSteamGames(r.Store.SteamRecentGames),
|
||||
}, nil
|
||||
}
|
||||
|
||||
games, err := services.FetchRecentlyPlayedGames(r.Store.SteamAPIKey, r.Store.SteamID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
summary, err := services.FetchPlayerSummary(r.Store.SteamAPIKey, r.Store.SteamID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
online := false
|
||||
if summary != nil {
|
||||
online = summary.PersonaState > 0
|
||||
}
|
||||
|
||||
r.Store.SteamRecentGames = games
|
||||
r.Store.SteamOnline = online
|
||||
r.Store.SteamFetchedAt = time.Now()
|
||||
|
||||
return &model.SteamStatus{
|
||||
Online: online,
|
||||
RecentGames: mapSteamGames(games),
|
||||
}, nil
|
||||
}
|
||||
@@ -7,10 +7,106 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// CreateUser is the resolver for the createUser field.
|
||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user := models.User{Username: input.Username, Password: hashedPassword}
|
||||
if err := r.Store.DB.Create(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// DeleteUser is the resolver for the deleteUser field.
|
||||
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
if err := r.Store.DB.Delete(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// SetUserAdmin is the resolver for the setUserAdmin field.
|
||||
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
callerID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
if uint(id) == callerID {
|
||||
return nil, fmt.Errorf("cannot change your own admin status")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
user.Admin = admin
|
||||
if err := r.Store.DB.Save(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Users is the resolver for the users field.
|
||||
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var users []models.User
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*models.User, len(users))
|
||||
for i := range users {
|
||||
result[i] = &users[i]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// User is the resolver for the user field.
|
||||
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type CreateActivityInput struct {
|
||||
Type string `json:"type" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Link *string `json:"link"`
|
||||
}
|
||||
|
||||
func (store *Store) GetActivity(ctx *gin.Context) {
|
||||
var activitys []models.Activity
|
||||
if err := store.DB.Order("Created_At DESC").Find(&activitys).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, activitys)
|
||||
}
|
||||
|
||||
func (store *Store) CreateActivity(ctx *gin.Context) {
|
||||
var input CreateActivityInput
|
||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
tx := store.DB.Create(&activity)
|
||||
if tx.Error != nil {
|
||||
log.Println(tx.Error)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusCreated, activity)
|
||||
}
|
||||
@@ -10,6 +10,11 @@ import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type UserCredentials struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||
access_token, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -50,6 +55,87 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||
accessToken, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
// No access token — try refreshing
|
||||
if !store.tryRefreshAndValidateAdmin(ctx) {
|
||||
ctx.Status(http.StatusUnauthorized)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := store.Auth.VerifyJWT(accessToken)
|
||||
if err != nil {
|
||||
// Expired/invalid access token — try refreshing
|
||||
if !store.tryRefreshAndValidateAdmin(ctx) {
|
||||
ctx.Status(http.StatusUnauthorized)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
admin, ok := (*claims)["admin"].(bool)
|
||||
if !ok || !admin {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
claims, err := store.Auth.VerifyJWT(refreshToken)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
user := models.User{ID: uint(userIDF)}
|
||||
if err := store.DB.First(&user).Error; err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if !user.Admin {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return true
|
||||
}
|
||||
|
||||
tokens, err := store.Auth.GenerateJWT(&user)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
return true
|
||||
}
|
||||
|
||||
func (store *Store) CheckToken(ctx *gin.Context) {
|
||||
access_token, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
@@ -123,7 +209,7 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
store.Auth.Config.Endpoint,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
@@ -131,7 +217,7 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
store.Auth.Config.Endpoint,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
@@ -140,6 +226,11 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
func (store *Store) Login(ctx *gin.Context) {
|
||||
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
|
||||
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
|
||||
return
|
||||
}
|
||||
|
||||
var input UserCredentials
|
||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
@@ -169,7 +260,7 @@ func (store *Store) Login(ctx *gin.Context) {
|
||||
"access_token",
|
||||
tokens.AccessToken,
|
||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||
store.Auth.Config.Endpoint,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
@@ -177,7 +268,7 @@ func (store *Store) Login(ctx *gin.Context) {
|
||||
"refresh_token",
|
||||
tokens.RefreshToken,
|
||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||
store.Auth.Config.Endpoint,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
@@ -197,7 +288,7 @@ func (store *Store) removeCookies(ctx *gin.Context) {
|
||||
"access_token",
|
||||
"",
|
||||
-1,
|
||||
store.Auth.Config.Endpoint,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
@@ -205,7 +296,7 @@ func (store *Store) removeCookies(ctx *gin.Context) {
|
||||
"refresh_token",
|
||||
"",
|
||||
-1,
|
||||
store.Auth.Config.Endpoint,
|
||||
"/",
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
45
backend/handlers/handle_email_sync.go
Normal file
45
backend/handlers/handle_email_sync.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
||||
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
|
||||
return
|
||||
}
|
||||
|
||||
err := store.EmailSync.SyncEmails(ctx.Request.Context())
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Manual sync error: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "sync failed", "details": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
|
||||
}
|
||||
|
||||
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
|
||||
if store.EmailSync == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
|
||||
return
|
||||
}
|
||||
|
||||
code := ctx.Query("code")
|
||||
if code == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "missing authorization code"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := store.EmailSync.CompleteAuth(ctx.Request.Context(), code); err != nil {
|
||||
log.Printf("[EmailSync] Auth completion error: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "email authentication successful"})
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type CreateFavoriteInput struct {
|
||||
Type string `json:"type" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Link *string `json:"link"`
|
||||
}
|
||||
|
||||
func (store *Store) GetFavorites(ctx *gin.Context) {
|
||||
var favorites []models.Favorite
|
||||
if err := store.DB.Order("Created_At DESC").Find(&favorites).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, favorites)
|
||||
}
|
||||
|
||||
func (store *Store) CreateFavorite(ctx *gin.Context) {
|
||||
var input CreateFavoriteInput
|
||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
tx := store.DB.Create(&favorite)
|
||||
if tx.Error != nil {
|
||||
log.Println(tx.Error)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusCreated, favorite)
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type CreatePostInput struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
Content string `json:"content" binding:"required"`
|
||||
}
|
||||
|
||||
func (store *Store) GetPosts(ctx *gin.Context) {
|
||||
var posts []models.Post
|
||||
if err := store.DB.Preload("Author").Order("Created_At DESC").Find(&posts).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, posts)
|
||||
}
|
||||
|
||||
func (store *Store) GetPost(ctx *gin.Context) {
|
||||
postIDStr := ctx.Param("id")
|
||||
|
||||
postID, err := strconv.ParseUint(postIDStr, 10, 64)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
post := models.Post{ID: uint(postID)}
|
||||
if err := store.DB.First(&post).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, post)
|
||||
}
|
||||
|
||||
func (store *Store) CreatePost(ctx *gin.Context) {
|
||||
var input CreatePostInput
|
||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
claimsVal, ok := ctx.Get("userClaims")
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := claimsVal.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
userID := uint(userIDF)
|
||||
|
||||
// Create post
|
||||
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
|
||||
tx := store.DB.Create(&post)
|
||||
if tx.Error != nil {
|
||||
log.Println(tx.Error)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusCreated, post)
|
||||
}
|
||||
|
||||
func (store *Store) UpdatePost(ctx *gin.Context) {
|
||||
postID := ctx.Param("id")
|
||||
var post models.Post
|
||||
if err := store.DB.First(&post, postID).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
claimsVal, ok := ctx.Get("userClaims")
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := claimsVal.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
userID := uint(userIDF)
|
||||
|
||||
if !(userID == post.AuthorID) {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
var input CreatePostInput
|
||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
post.Title = input.Title
|
||||
post.Content = input.Content
|
||||
tx := store.DB.Save(&post)
|
||||
if tx.Error != nil {
|
||||
log.Println(tx.Error)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, post)
|
||||
}
|
||||
|
||||
func (store *Store) DeletePost(ctx *gin.Context) {
|
||||
postID := ctx.Param("id")
|
||||
var post models.Post
|
||||
if err := store.DB.First(&post, postID).Error; err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
claimsVal, ok := ctx.Get("userClaims")
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := claimsVal.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
|
||||
return
|
||||
}
|
||||
userID := uint(userIDF)
|
||||
|
||||
if !(userID == post.AuthorID) {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
store.DB.Delete(&post)
|
||||
ctx.JSON(http.StatusOK, post)
|
||||
}
|
||||
@@ -37,6 +37,13 @@ func (store *Store) UploadRadioSong(ctx *gin.Context) {
|
||||
filename := filepath.Base(file.Filename)
|
||||
dest := filepath.Join(fallbackMusicDir, filename)
|
||||
|
||||
// Verify the resolved path stays within the music directory
|
||||
absDest, err := filepath.Abs(dest)
|
||||
if err != nil || !strings.HasPrefix(absDest, fallbackMusicDir+string(os.PathSeparator)) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid filename"})
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := os.Stat(dest); err == nil {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
|
||||
return
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type UserCredentials struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type SetAdminInput struct {
|
||||
Admin *bool `json:"admin" binding:"required"`
|
||||
}
|
||||
|
||||
func (store *Store) CreateUser(ctx *gin.Context) {
|
||||
var input UserCredentials
|
||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
user := models.User{Username: input.Username, Password: hashedPassword}
|
||||
tx := store.DB.Create(&user)
|
||||
if tx.Error != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (store *Store) GetUser(ctx *gin.Context) {
|
||||
userID := ctx.Param("id")
|
||||
var user models.User
|
||||
if err := store.DB.First(&user, userID).Error; err != nil {
|
||||
ctx.JSON(http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (store *Store) GetUsers(ctx *gin.Context) {
|
||||
var users []models.User
|
||||
if err := store.DB.Find(&users).Error; err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, users)
|
||||
}
|
||||
|
||||
func (store *Store) UpdateUser(ctx *gin.Context) {
|
||||
claimsVal, ok := ctx.Get("userClaims")
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := claimsVal.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
|
||||
return
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
|
||||
return
|
||||
}
|
||||
userID := uint(userIDF)
|
||||
|
||||
var user models.User
|
||||
if err := store.DB.First(&user, userID).Error; err != nil {
|
||||
ctx.JSON(http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "will be implemented"})
|
||||
}
|
||||
|
||||
func (store *Store) SetUserAdmin(ctx *gin.Context) {
|
||||
claimsVal, ok := ctx.Get("userClaims")
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
|
||||
return
|
||||
}
|
||||
claims, ok := claimsVal.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
|
||||
return
|
||||
}
|
||||
callerIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
|
||||
return
|
||||
}
|
||||
callerID := uint(callerIDF)
|
||||
|
||||
targetID := ctx.Param("id")
|
||||
|
||||
var input SetAdminInput
|
||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := store.DB.First(&user, targetID).Error; err != nil {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
|
||||
if user.ID == callerID {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "cannot change your own admin status"})
|
||||
return
|
||||
}
|
||||
|
||||
user.Admin = *input.Admin
|
||||
if err := store.DB.Save(&user).Error; err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (store *Store) DeleteUser(ctx *gin.Context) {
|
||||
claimsVal, ok := ctx.Get("userClaims")
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "user claims could not be found"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := claimsVal.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid claims"})
|
||||
return
|
||||
}
|
||||
|
||||
userIDF, ok := (*claims)["id"].(float64)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid user id in claims"})
|
||||
return
|
||||
}
|
||||
userID := uint(userIDF)
|
||||
|
||||
var user models.User
|
||||
if err := store.DB.First(&user, userID).Error; err != nil {
|
||||
ctx.JSON(http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
tx := store.DB.Delete(&user)
|
||||
if tx.Error != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, tx.Error.Error())
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetSameSite(http.SameSiteLaxMode)
|
||||
ctx.SetCookie(
|
||||
"access_token",
|
||||
"",
|
||||
-1,
|
||||
store.Auth.Config.Endpoint,
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
ctx.SetCookie(
|
||||
"refresh_token",
|
||||
"",
|
||||
-1,
|
||||
store.Auth.Config.Endpoint,
|
||||
store.Auth.Config.Domain,
|
||||
true, true,
|
||||
)
|
||||
|
||||
ctx.JSON(http.StatusOK, user)
|
||||
}
|
||||
@@ -17,6 +17,8 @@ type Store struct {
|
||||
ClaudeClient *anthropic.Client
|
||||
Auth *services.Auth
|
||||
Notes *services.Notes
|
||||
LoginLimiter *services.RateLimiter
|
||||
EmailSync *services.EmailSyncService
|
||||
|
||||
RecentSongs *[]spotify.RecentlyPlayedItem
|
||||
RecentSongsFetchedAt time.Time
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
@@ -28,6 +29,10 @@ func main() {
|
||||
}
|
||||
gin.DefaultWriter = io.MultiWriter(os.Stdout, logFile)
|
||||
|
||||
if os.Getenv("DEV_MODE") != "true" {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
r := gin.Default()
|
||||
|
||||
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
|
||||
@@ -66,7 +71,7 @@ func main() {
|
||||
|
||||
authSecret := os.Getenv("BACKEND_SECRET")
|
||||
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
||||
accessTokenLifetime := 24 * time.Hour
|
||||
accessTokenLifetime := 7 * 24 * time.Hour
|
||||
refreshTokenLifetime := 365 * 24 * time.Hour
|
||||
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
|
||||
auth := services.InitAuth(&authConfig)
|
||||
@@ -81,43 +86,51 @@ func main() {
|
||||
steamAPIKey := os.Getenv("STEAM_API_KEY")
|
||||
steamID := os.Getenv("STEAM_ID")
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID}
|
||||
// EMAIL SYNC
|
||||
emailSyncInterval := 30 * time.Minute
|
||||
if interval := os.Getenv("EMAIL_SYNC_INTERVAL"); interval != "" {
|
||||
if parsed, err := time.ParseDuration(interval); err == nil {
|
||||
emailSyncInterval = parsed
|
||||
}
|
||||
}
|
||||
emailSyncConfig := services.EmailSyncConfig{
|
||||
Backend: os.Getenv("EMAIL_BACKEND"),
|
||||
ClientID: os.Getenv("MSGRAPH_CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("MSGRAPH_CLIENT_SECRET"),
|
||||
TenantID: os.Getenv("MSGRAPH_TENANT_ID"),
|
||||
RedirectURI: os.Getenv("MSGRAPH_REDIRECT_URI"),
|
||||
IMAP: &services.IMAPConfig{
|
||||
Host: os.Getenv("IMAP_HOST"),
|
||||
Port: os.Getenv("IMAP_PORT"),
|
||||
Email: os.Getenv("IMAP_EMAIL"),
|
||||
Password: os.Getenv("IMAP_PASSWORD"),
|
||||
},
|
||||
SyncInterval: emailSyncInterval,
|
||||
Enabled: os.Getenv("EMAIL_SYNC_ENABLED") == "true",
|
||||
}
|
||||
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
|
||||
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID}
|
||||
|
||||
protected := r.Group("/", store.AuthMiddlewear)
|
||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||
|
||||
// FAVORITES
|
||||
r.GET("/favorites", store.GetFavorites)
|
||||
admin.POST("/favorites", store.CreateFavorite)
|
||||
|
||||
// ROWING
|
||||
r.GET("/rowing", store.GetRowing)
|
||||
admin.POST("/rowing", store.CreateRowing)
|
||||
|
||||
// ACTIVITIES
|
||||
r.GET("/activity", store.GetActivity)
|
||||
admin.POST("/activity", store.CreateActivity)
|
||||
|
||||
// POSTS
|
||||
r.GET("/posts", store.GetPosts)
|
||||
admin.POST("/posts", store.CreatePost)
|
||||
r.GET("/posts/:id", store.GetPost)
|
||||
admin.PUT("/posts/:id", store.UpdatePost)
|
||||
admin.DELETE("/posts/:id", store.DeletePost)
|
||||
|
||||
// USERS
|
||||
r.GET("/user/:id", store.GetUser)
|
||||
admin.PUT("/user/:id", store.UpdateUser)
|
||||
admin.DELETE("/user/:id", store.DeleteUser)
|
||||
r.GET("/user", store.GetUsers)
|
||||
admin.POST("/user", store.CreateUser)
|
||||
admin.PATCH("/user/:id/admin", store.SetUserAdmin)
|
||||
|
||||
// AUTH
|
||||
r.POST("/auth/login", store.Login)
|
||||
r.POST("/auth/refresh", store.RefreshToken)
|
||||
r.GET("/auth/check", store.CheckToken)
|
||||
r.POST("/auth/logout", store.Logout)
|
||||
r.GET("/auth/validate-admin", store.ValidateAdmin)
|
||||
|
||||
// EMAIL SYNC
|
||||
r.GET("/email/callback", store.CompleteEmailAuth)
|
||||
admin.POST("/email/sync", store.TriggerEmailSync)
|
||||
|
||||
// SPOTIFY
|
||||
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
|
||||
@@ -137,7 +150,7 @@ func main() {
|
||||
protected.POST("/messages/upload", store.UploadMessageFile)
|
||||
|
||||
// NOTES
|
||||
r.GET("/notes/*path", store.GetNoteFile)
|
||||
admin.GET("/notes/*path", store.GetNoteFile)
|
||||
|
||||
// GRAPHQL
|
||||
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
||||
@@ -145,18 +158,18 @@ func main() {
|
||||
}))
|
||||
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
|
||||
gqlSrv.AddTransport(transport.Options{})
|
||||
gqlSrv.AddTransport(transport.GET{})
|
||||
gqlSrv.AddTransport(transport.POST{})
|
||||
gqlSrv.AddTransport(transport.MultipartForm{})
|
||||
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
|
||||
gqlSrv.Use(extension.FixedComplexityLimit(200))
|
||||
if os.Getenv("GQL_INTROSPECTION") == "true" {
|
||||
devMode := os.Getenv("DEV_MODE") == "true"
|
||||
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
|
||||
gqlSrv.Use(extension.Introspection{})
|
||||
}
|
||||
r.POST("/graphql", graph.AuthContextMiddleware(auth), func(c *gin.Context) {
|
||||
gqlSrv.ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
if os.Getenv("GQL_PLAYGROUND") == "true" {
|
||||
if devMode && os.Getenv("GQL_PLAYGROUND") == "true" {
|
||||
r.GET("/graphql", func(c *gin.Context) {
|
||||
playground.Handler("GraphQL Playground", "/graphql").ServeHTTP(c.Writer, c.Request)
|
||||
})
|
||||
@@ -167,6 +180,11 @@ func main() {
|
||||
c.JSON(200, gin.H{"message": "Hello World"})
|
||||
})
|
||||
|
||||
// Launch email sync scheduler
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go store.EmailSync.StartScheduler(ctx)
|
||||
|
||||
port := os.Getenv("BACKEND_PORT")
|
||||
r.Run(fmt.Sprintf(":%s", port))
|
||||
}
|
||||
|
||||
@@ -66,3 +66,47 @@ type Rowing struct {
|
||||
TimePer500m float64 `json:"timePer500m"`
|
||||
Calories float64 `json:"calories"`
|
||||
}
|
||||
|
||||
type Bookmark struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Category string `gorm:"not null" json:"category"`
|
||||
Name string `gorm:"not null" json:"name"`
|
||||
Link string `gorm:"not null" json:"link"`
|
||||
}
|
||||
|
||||
type JobAppReference struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Category string `gorm:"not null" json:"category"`
|
||||
Label string `gorm:"not null" json:"label"`
|
||||
Value string `gorm:"not null" json:"value"`
|
||||
SortOrder int `gorm:"default:0" json:"sortOrder"`
|
||||
}
|
||||
|
||||
type ProcessedEmail struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
|
||||
Subject string `gorm:"not null" json:"subject"`
|
||||
Action string `gorm:"not null" json:"action"`
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
}
|
||||
|
||||
type JobApplication struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
Status string `gorm:"not null" json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
AppliedAt *time.Time `json:"appliedAt"`
|
||||
}
|
||||
|
||||
@@ -38,6 +38,10 @@ func migrateDatabase(db *gorm.DB) error {
|
||||
&models.Favorite{},
|
||||
&models.Rowing{},
|
||||
&models.Message{},
|
||||
&models.JobApplication{},
|
||||
&models.JobAppReference{},
|
||||
&models.Bookmark{},
|
||||
&models.ProcessedEmail{},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
337
backend/services/email_imap.go
Normal file
337
backend/services/email_imap.go
Normal file
@@ -0,0 +1,337 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type IMAPConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
// imapClient is a minimal, lenient IMAP client that tolerates
|
||||
// Outlook's non-standard response formatting.
|
||||
type imapClient struct {
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
tag atomic.Int64
|
||||
}
|
||||
|
||||
func imapDial(addr string) (*imapClient, error) {
|
||||
conn, err := tls.Dial("tcp", addr, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &imapClient{
|
||||
conn: conn,
|
||||
reader: bufio.NewReader(conn),
|
||||
}
|
||||
// Read server greeting
|
||||
if _, err := c.readLine(); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("reading greeting: %w", err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *imapClient) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
func (c *imapClient) nextTag() string {
|
||||
return fmt.Sprintf("A%04d", c.tag.Add(1))
|
||||
}
|
||||
|
||||
func (c *imapClient) readLine() (string, error) {
|
||||
line, err := c.reader.ReadString('\n')
|
||||
return strings.TrimRight(line, "\r\n"), err
|
||||
}
|
||||
|
||||
// sendCommand sends a tagged command and reads lines until the tagged response.
|
||||
// Returns all untagged response lines and the final tagged status line.
|
||||
func (c *imapClient) sendCommand(cmd string) (untagged []string, status string, err error) {
|
||||
tag := c.nextTag()
|
||||
_, err = fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return untagged, "", err
|
||||
}
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
return untagged, line, nil
|
||||
}
|
||||
untagged = append(untagged, line)
|
||||
}
|
||||
}
|
||||
|
||||
// sendCommandOK sends a command and returns an error if the response is not OK.
|
||||
func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
|
||||
untagged, status, err := c.sendCommand(cmd)
|
||||
if err != nil {
|
||||
return untagged, err
|
||||
}
|
||||
// Status line is like: A0001 OK ... or A0001 NO ...
|
||||
parts := strings.SplitN(status, " ", 3)
|
||||
if len(parts) < 2 || parts[1] != "OK" {
|
||||
return untagged, fmt.Errorf("command %q failed: %s", cmd, status)
|
||||
}
|
||||
return untagged, nil
|
||||
}
|
||||
|
||||
// fetchLiteral reads an IMAP literal {N}\r\n followed by N bytes.
|
||||
func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
buf := make([]byte, size)
|
||||
_, err := io.ReadFull(c.reader, buf)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// sendFetch sends a FETCH command and collects the full response including literals.
|
||||
// Returns raw response lines (with literals inlined after their header lines).
|
||||
func (c *imapClient) sendFetch(cmd string) ([]string, error) {
|
||||
tag := c.nextTag()
|
||||
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var lines []string
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return lines, err
|
||||
}
|
||||
|
||||
// Check for literal marker {N} at end of line
|
||||
if idx := strings.LastIndex(line, "{"); idx >= 0 && strings.HasSuffix(line, "}") {
|
||||
sizeStr := line[idx+1 : len(line)-1]
|
||||
var size int
|
||||
if _, err := fmt.Sscanf(sizeStr, "%d", &size); err == nil && size > 0 {
|
||||
literal, err := c.readLiteral(size)
|
||||
if err != nil {
|
||||
return lines, fmt.Errorf("reading literal of %d bytes: %w", size, err)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
lines = append(lines, literal)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
// Check for OK
|
||||
parts := strings.SplitN(line, " ", 3)
|
||||
if len(parts) >= 2 && parts[1] != "OK" {
|
||||
return lines, fmt.Errorf("FETCH failed: %s", line)
|
||||
}
|
||||
return lines, nil
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
}
|
||||
|
||||
// fetchEmailsIMAP connects to an IMAP server and retrieves emails since the given time.
|
||||
func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, error) {
|
||||
addr := fmt.Sprintf("%s:%s", s.Config.IMAP.Host, s.Config.IMAP.Port)
|
||||
|
||||
c, err := imapDial(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP connect: %w", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
// Quote the password to handle special characters
|
||||
quotedPass := fmt.Sprintf("%q", s.Config.IMAP.Password)
|
||||
if _, err := c.sendCommandOK(fmt.Sprintf("LOGIN %s %s", s.Config.IMAP.Email, quotedPass)); err != nil {
|
||||
return nil, fmt.Errorf("IMAP login: %w", err)
|
||||
}
|
||||
|
||||
if _, err := c.sendCommandOK("SELECT INBOX"); err != nil {
|
||||
return nil, fmt.Errorf("IMAP select INBOX: %w", err)
|
||||
}
|
||||
|
||||
// SEARCH SINCE uses date only (no time), per IMAP spec
|
||||
dateStr := since.UTC().Format("02-Jan-2006")
|
||||
untagged, err := c.sendCommandOK(fmt.Sprintf("SEARCH SINCE %s", dateStr))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP search: %w", err)
|
||||
}
|
||||
|
||||
// Parse sequence numbers from "* SEARCH 1 2 3 ..."
|
||||
var seqNums []string
|
||||
for _, line := range untagged {
|
||||
if strings.HasPrefix(line, "* SEARCH") {
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) > 2 {
|
||||
seqNums = append(seqNums, parts[2:]...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(seqNums) == 0 {
|
||||
log.Printf("[EmailSync/IMAP] No messages found since %s", dateStr)
|
||||
c.sendCommand("LOGOUT")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync/IMAP] Found %d messages since %s", len(seqNums), dateStr)
|
||||
|
||||
seqSet := strings.Join(seqNums, ",")
|
||||
fetchLines, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP fetch: %w", err)
|
||||
}
|
||||
|
||||
// Parse fetched messages - literals contain the raw RFC822 message
|
||||
var messages []graphMessage
|
||||
for i := 0; i < len(fetchLines); i++ {
|
||||
line := fetchLines[i]
|
||||
// Look for a literal following this line
|
||||
if strings.Contains(line, "BODY[]") && strings.HasSuffix(line, "}") {
|
||||
if i+1 < len(fetchLines) {
|
||||
raw := fetchLines[i+1]
|
||||
i++ // skip the literal
|
||||
gm, err := parseRawEmail(raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
continue
|
||||
}
|
||||
messages = append(messages, gm)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.sendCommand("LOGOUT")
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// parseRawEmail parses an RFC822 email into a graphMessage.
|
||||
func parseRawEmail(raw string) (graphMessage, error) {
|
||||
msg, err := mail.ReadMessage(strings.NewReader(raw))
|
||||
if err != nil {
|
||||
return graphMessage{}, fmt.Errorf("parsing message: %w", err)
|
||||
}
|
||||
|
||||
header := msg.Header
|
||||
|
||||
// Parse From
|
||||
var fromName, fromAddr string
|
||||
if fromList, err := header.AddressList("From"); err == nil && len(fromList) > 0 {
|
||||
fromName = fromList[0].Name
|
||||
fromAddr = fromList[0].Address
|
||||
}
|
||||
|
||||
// Parse Date
|
||||
dateStr := header.Get("Date")
|
||||
parsedDate, err := mail.ParseDate(dateStr)
|
||||
if err != nil {
|
||||
parsedDate = time.Now()
|
||||
}
|
||||
|
||||
// Extract body text
|
||||
bodyContent := extractTextBody(msg.Header, msg.Body)
|
||||
|
||||
return graphMessage{
|
||||
ID: header.Get("Message-ID"),
|
||||
Subject: decodeHeader(header.Get("Subject")),
|
||||
ReceivedDateTime: parsedDate.Format(time.RFC3339),
|
||||
From: graphFrom{
|
||||
EmailAddress: graphEmailAddress{
|
||||
Name: fromName,
|
||||
Address: fromAddr,
|
||||
},
|
||||
},
|
||||
Body: graphBody{
|
||||
ContentType: "text",
|
||||
Content: bodyContent,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// extractTextBody pulls the text/plain or text/html content from a message body.
|
||||
func extractTextBody(header mail.Header, body io.Reader) string {
|
||||
contentType := header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = "text/plain"
|
||||
}
|
||||
|
||||
mediaType, params, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
// Try reading as plain text
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mediaType, "multipart/") {
|
||||
boundary := params["boundary"]
|
||||
if boundary == "" {
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
mr := multipart.NewReader(body, boundary)
|
||||
var textContent, htmlContent string
|
||||
for {
|
||||
part, err := mr.NextPart()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
partType := part.Header.Get("Content-Type")
|
||||
partMedia, _, _ := mime.ParseMediaType(partType)
|
||||
b, err := io.ReadAll(part)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
switch partMedia {
|
||||
case "text/plain":
|
||||
textContent = string(b)
|
||||
case "text/html":
|
||||
htmlContent = string(b)
|
||||
case "multipart/alternative", "multipart/related", "multipart/mixed":
|
||||
// Recursively handle nested multipart
|
||||
nested := extractTextBody(
|
||||
mail.Header{"Content-Type": {partType}},
|
||||
strings.NewReader(string(b)),
|
||||
)
|
||||
if nested != "" && textContent == "" {
|
||||
textContent = nested
|
||||
}
|
||||
}
|
||||
}
|
||||
if textContent != "" {
|
||||
return textContent
|
||||
}
|
||||
return htmlContent
|
||||
}
|
||||
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// decodeHeader decodes RFC 2047 encoded header values.
|
||||
func decodeHeader(s string) string {
|
||||
dec := new(mime.WordDecoder)
|
||||
decoded, err := dec.DecodeHeader(s)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
680
backend/services/email_sync.go
Normal file
680
backend/services/email_sync.go
Normal file
@@ -0,0 +1,680 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const MSGRAPH_TOKEN_JSON_PATH = "/backend/token/msgraph_token.json"
|
||||
|
||||
type EmailSyncConfig struct {
|
||||
Backend string // "graph" or "imap"
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
TenantID string
|
||||
RedirectURI string
|
||||
IMAP *IMAPConfig
|
||||
SyncInterval time.Duration
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
type EmailSyncService struct {
|
||||
Config *EmailSyncConfig
|
||||
OAuthConfig *oauth2.Config
|
||||
HTTPClient *http.Client
|
||||
DB *gorm.DB
|
||||
ClaudeClient *anthropic.Client
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Microsoft Graph API response types
|
||||
|
||||
type graphMessagesResponse struct {
|
||||
Value []graphMessage `json:"value"`
|
||||
NextLink string `json:"@odata.nextLink"`
|
||||
}
|
||||
|
||||
type graphMessage struct {
|
||||
ID string `json:"id"`
|
||||
Subject string `json:"subject"`
|
||||
ReceivedDateTime string `json:"receivedDateTime"`
|
||||
From graphFrom `json:"from"`
|
||||
Body graphBody `json:"body"`
|
||||
BodyPreview string `json:"bodyPreview"`
|
||||
}
|
||||
|
||||
type graphFrom struct {
|
||||
EmailAddress graphEmailAddress `json:"emailAddress"`
|
||||
}
|
||||
|
||||
type graphEmailAddress struct {
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
type graphBody struct {
|
||||
ContentType string `json:"contentType"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Claude response type
|
||||
|
||||
type EmailAnalysis struct {
|
||||
IsJobEmail bool `json:"isJobEmail"`
|
||||
Action string `json:"action"`
|
||||
Company string `json:"company"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Status string `json:"status"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
AppliedAt *string `json:"appliedAt"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// Email filtering config
|
||||
|
||||
var subjectKeywords = []string{
|
||||
"application", "interview", "offer", "rejected", "assessment",
|
||||
"applied", "candidate", "position", "role", "hiring",
|
||||
"thank you for applying", "we regret", "move forward",
|
||||
"next steps", "coding challenge", "take-home",
|
||||
}
|
||||
|
||||
var senderDomains = []string{
|
||||
"greenhouse.io", "lever.co", "workday.com", "myworkday.com",
|
||||
"ashbyhq.com", "smartrecruiters.com", "icims.com",
|
||||
"jobvite.com", "taleo.net", "breezy.hr", "recruitee.com",
|
||||
"applytojob.com", "jazz.co", "dover.com",
|
||||
}
|
||||
|
||||
// Status progression order
|
||||
|
||||
var statusOrder = map[string]int{
|
||||
"applied": 0,
|
||||
"screening": 1,
|
||||
"assessment": 2,
|
||||
"interviewing": 3,
|
||||
"offer": 4,
|
||||
"rejected": 5,
|
||||
"withdrawn": 6,
|
||||
}
|
||||
|
||||
// Token persistence
|
||||
|
||||
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||
data := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}{
|
||||
AccessToken: tok.AccessToken,
|
||||
RefreshToken: tok.RefreshToken,
|
||||
TokenType: tok.TokenType,
|
||||
Expiry: tok.Expiry,
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
return fmt.Errorf("creating token directory: %w", err)
|
||||
}
|
||||
|
||||
jsonBytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(path, jsonBytes, 0600)
|
||||
}
|
||||
|
||||
func LoadMSGraphToken(path string) (*oauth2.Token, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var saved struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &saved); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oauth2.Token{
|
||||
AccessToken: saved.AccessToken,
|
||||
RefreshToken: saved.RefreshToken,
|
||||
TokenType: saved.TokenType,
|
||||
Expiry: saved.Expiry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// persistingTokenSource wraps an oauth2.TokenSource to save refreshed tokens to disk.
|
||||
type persistingTokenSource struct {
|
||||
base oauth2.TokenSource
|
||||
path string
|
||||
lastToken *oauth2.Token
|
||||
}
|
||||
|
||||
func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
tok, err := p.base.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Save only when the token actually changed (i.e. was refreshed)
|
||||
if p.lastToken == nil || tok.AccessToken != p.lastToken.AccessToken {
|
||||
p.lastToken = tok
|
||||
if saveErr := SaveMSGraphToken(p.path, tok); saveErr != nil {
|
||||
log.Printf("[EmailSync] Warning: failed to persist refreshed token: %v", saveErr)
|
||||
}
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService {
|
||||
svc := &EmailSyncService{
|
||||
Config: config,
|
||||
DB: db,
|
||||
ClaudeClient: claudeClient,
|
||||
}
|
||||
|
||||
switch config.Backend {
|
||||
case "imap":
|
||||
if config.IMAP == nil || config.IMAP.Email == "" {
|
||||
log.Println("[EmailSync] IMAP backend selected but not configured")
|
||||
return svc
|
||||
}
|
||||
// IMAP connects per-sync, no persistent client needed.
|
||||
// Mark as ready by setting a non-nil HTTPClient (used as readiness flag).
|
||||
svc.HTTPClient = http.DefaultClient
|
||||
log.Printf("[EmailSync] Configured with IMAP backend (%s)", config.IMAP.Host)
|
||||
|
||||
case "graph":
|
||||
oauthConfig := &oauth2.Config{
|
||||
ClientID: config.ClientID,
|
||||
ClientSecret: config.ClientSecret,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/authorize", config.TenantID),
|
||||
TokenURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", config.TenantID),
|
||||
},
|
||||
RedirectURL: config.RedirectURI,
|
||||
Scopes: []string{"https://graph.microsoft.com/Mail.Read", "offline_access"},
|
||||
}
|
||||
svc.OAuthConfig = oauthConfig
|
||||
|
||||
token, err := LoadMSGraphToken(MSGRAPH_TOKEN_JSON_PATH)
|
||||
if err != nil || token == nil {
|
||||
authURL := oauthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
log.Println("[EmailSync] No token saved. Authenticate Microsoft Graph with:")
|
||||
log.Println(authURL)
|
||||
return svc
|
||||
}
|
||||
|
||||
baseSource := oauthConfig.TokenSource(context.Background(), token)
|
||||
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
|
||||
svc.HTTPClient = oauth2.NewClient(context.Background(), persistSource)
|
||||
log.Println("[EmailSync] Authenticated with Microsoft Graph")
|
||||
|
||||
default:
|
||||
log.Printf("[EmailSync] Unknown backend %q, defaulting to disabled", config.Backend)
|
||||
}
|
||||
|
||||
return svc
|
||||
}
|
||||
|
||||
// AuthURL returns the OAuth2 authorization URL for initial setup.
|
||||
func (s *EmailSyncService) AuthURL() string {
|
||||
return s.OAuthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
}
|
||||
|
||||
// CompleteAuth exchanges an authorization code for a token and initializes the HTTP client.
|
||||
func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error {
|
||||
token, err := s.OAuthConfig.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return fmt.Errorf("token exchange failed: %w", err)
|
||||
}
|
||||
|
||||
if err := SaveMSGraphToken(MSGRAPH_TOKEN_JSON_PATH, token); err != nil {
|
||||
return fmt.Errorf("saving token: %w", err)
|
||||
}
|
||||
|
||||
baseSource := s.OAuthConfig.TokenSource(ctx, token)
|
||||
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
|
||||
s.HTTPClient = oauth2.NewClient(ctx, persistSource)
|
||||
|
||||
log.Println("[EmailSync] Authentication completed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartScheduler runs SyncEmails on a recurring interval.
|
||||
func (s *EmailSyncService) StartScheduler(ctx context.Context) {
|
||||
if !s.Config.Enabled {
|
||||
log.Println("[EmailSync] Disabled, skipping scheduler")
|
||||
return
|
||||
}
|
||||
if s.HTTPClient == nil {
|
||||
log.Println("[EmailSync] Not authenticated, skipping scheduler")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Starting scheduler, interval: %s", s.Config.SyncInterval)
|
||||
|
||||
// Run once immediately on startup
|
||||
if err := s.SyncEmails(ctx); err != nil {
|
||||
log.Printf("[EmailSync] Initial sync error: %v", err)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(s.Config.SyncInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[EmailSync] Scheduler stopped")
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := s.SyncEmails(ctx); err != nil {
|
||||
log.Printf("[EmailSync] Sync error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SyncEmails is the main pipeline: fetch, filter, dedup, classify, create/update.
|
||||
func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
if !s.mu.TryLock() {
|
||||
return fmt.Errorf("sync already in progress")
|
||||
}
|
||||
defer s.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("[EmailSync] PANIC recovered: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
log.Println("[EmailSync] Starting sync...")
|
||||
|
||||
// Determine the time window: use the most recent ProcessedEmail timestamp, or default to 24h ago
|
||||
since := time.Now().Add(-24 * time.Hour)
|
||||
var latest models.ProcessedEmail
|
||||
if err := s.DB.Order("created_at DESC").First(&latest).Error; err == nil {
|
||||
since = latest.CreatedAt
|
||||
}
|
||||
|
||||
// Fetch emails from Microsoft Graph
|
||||
emails, err := s.fetchEmails(ctx, since)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetching emails: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Fetched %d emails since %s", len(emails), since.Format(time.RFC3339))
|
||||
|
||||
// Filter by subject/sender patterns
|
||||
filtered := s.filterEmails(emails)
|
||||
log.Printf("[EmailSync] %d emails passed filters", len(filtered))
|
||||
|
||||
var created, updated, skipped, errored int
|
||||
|
||||
for _, email := range filtered {
|
||||
// Dedup check
|
||||
var existing models.ProcessedEmail
|
||||
if err := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error; err == nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// Process this email
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
s.DB.Create(&models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: "error",
|
||||
})
|
||||
errored++
|
||||
continue
|
||||
}
|
||||
|
||||
// Record as processed
|
||||
s.DB.Create(&models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: action,
|
||||
JobAppID: jobAppID,
|
||||
})
|
||||
|
||||
switch action {
|
||||
case "created":
|
||||
created++
|
||||
case "updated":
|
||||
updated++
|
||||
default:
|
||||
skipped++
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Sync complete: %d fetched, %d filtered, %d created, %d updated, %d skipped, %d errors",
|
||||
len(emails), len(filtered), created, updated, skipped, errored)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchEmails retrieves emails since the given time using the configured backend.
|
||||
func (s *EmailSyncService) fetchEmails(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
if s.Config.Backend == "imap" {
|
||||
return s.fetchEmailsIMAP(since)
|
||||
}
|
||||
return s.fetchEmailsGraph(ctx, since)
|
||||
}
|
||||
|
||||
// fetchEmailsGraph retrieves emails from the Microsoft Graph API since the given time.
|
||||
func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
var all []graphMessage
|
||||
|
||||
sinceStr := since.UTC().Format("2006-01-02T15:04:05Z")
|
||||
params := url.Values{
|
||||
"$filter": {fmt.Sprintf("receivedDateTime ge %s", sinceStr)},
|
||||
"$select": {"id,subject,from,receivedDateTime,body,bodyPreview"},
|
||||
"$top": {"50"},
|
||||
"$orderby": {"receivedDateTime asc"},
|
||||
}
|
||||
|
||||
nextURL := fmt.Sprintf("https://graph.microsoft.com/v1.0/me/messages?%s", params.Encode())
|
||||
|
||||
for nextURL != "" {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", nextURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := s.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Graph API returned %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var result graphMessagesResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("parsing response: %w", err)
|
||||
}
|
||||
|
||||
all = append(all, result.Value...)
|
||||
nextURL = result.NextLink
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// filterEmails returns only emails that match subject keywords or sender domains.
|
||||
func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage {
|
||||
var matched []graphMessage
|
||||
for _, email := range emails {
|
||||
if s.matchesFilter(email) {
|
||||
matched = append(matched, email)
|
||||
}
|
||||
}
|
||||
return matched
|
||||
}
|
||||
|
||||
func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
|
||||
subjectLower := strings.ToLower(email.Subject)
|
||||
for _, kw := range subjectKeywords {
|
||||
if strings.Contains(subjectLower, kw) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
senderAddr := strings.ToLower(email.From.EmailAddress.Address)
|
||||
for _, domain := range senderDomains {
|
||||
if strings.HasSuffix(senderAddr, "@"+domain) || strings.HasSuffix(senderAddr, "."+domain) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// processEmail sends a single email to Claude and creates/updates a JobApplication.
|
||||
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
|
||||
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
|
||||
cleaned := cleanEmailBody(email.Body.Content, email.Body.ContentType)
|
||||
|
||||
userMsg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
|
||||
email.Subject,
|
||||
email.From.EmailAddress.Name,
|
||||
email.From.EmailAddress.Address,
|
||||
email.ReceivedDateTime,
|
||||
cleaned,
|
||||
)
|
||||
|
||||
message, err := s.ClaudeClient.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: anthropic.ModelClaudeHaiku4_5,
|
||||
MaxTokens: 512,
|
||||
System: []anthropic.TextBlockParam{
|
||||
{Text: emailClassificationPrompt},
|
||||
},
|
||||
Messages: []anthropic.MessageParam{
|
||||
{
|
||||
Role: "user",
|
||||
Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(userMsg)},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("Claude API error: %w", err)
|
||||
}
|
||||
|
||||
if len(message.Content) == 0 {
|
||||
return "", nil, fmt.Errorf("empty response from Claude")
|
||||
}
|
||||
|
||||
raw := message.Content[0].Text
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
raw = strings.TrimSpace(raw)
|
||||
|
||||
var analysis EmailAnalysis
|
||||
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
|
||||
return "", nil, fmt.Errorf("parsing Claude response: %w (raw: %s)", err, raw)
|
||||
}
|
||||
|
||||
if !analysis.IsJobEmail {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
if analysis.Company == "" || analysis.JobTitle == "" {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
// Try to find an existing job application
|
||||
var existing models.JobApplication
|
||||
found := s.DB.Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
|
||||
analysis.Company, analysis.JobTitle).
|
||||
Order("created_at DESC").
|
||||
First(&existing).Error == nil
|
||||
|
||||
if found && analysis.Action == "update" {
|
||||
return s.updateJobApplication(&existing, &analysis)
|
||||
}
|
||||
|
||||
if !found {
|
||||
return s.createJobApplication(&analysis)
|
||||
}
|
||||
|
||||
// Found but action is "create" — the record already exists, skip
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
|
||||
app := models.JobApplication{
|
||||
Company: analysis.Company,
|
||||
JobTitle: analysis.JobTitle,
|
||||
Status: analysis.Status,
|
||||
Location: analysis.Location,
|
||||
URL: analysis.URL,
|
||||
Notes: analysis.Notes,
|
||||
}
|
||||
|
||||
if analysis.AppliedAt != nil {
|
||||
if t, err := time.Parse(time.RFC3339, *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
} else if t, err := time.Parse("2006-01-02", *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
}
|
||||
}
|
||||
|
||||
if app.Status == "" {
|
||||
app.Status = "applied"
|
||||
}
|
||||
|
||||
if err := s.DB.Create(&app).Error; err != nil {
|
||||
return "", nil, fmt.Errorf("creating job application: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Created job application: %s at %s (status: %s)", app.JobTitle, app.Company, app.Status)
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
newOrder, newExists := statusOrder[analysis.Status]
|
||||
currentOrder, currentExists := statusOrder[existing.Status]
|
||||
|
||||
// Only update if the new status represents progression
|
||||
if !newExists || (currentExists && newOrder <= currentOrder) {
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
existing.Status = analysis.Status
|
||||
|
||||
// Append to notes if Claude provided any
|
||||
if analysis.Notes != nil && *analysis.Notes != "" {
|
||||
if existing.Notes != nil && *existing.Notes != "" {
|
||||
combined := *existing.Notes + "\n" + *analysis.Notes
|
||||
existing.Notes = &combined
|
||||
} else {
|
||||
existing.Notes = analysis.Notes
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.DB.Save(existing).Error; err != nil {
|
||||
return "", nil, fmt.Errorf("updating job application: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Updated job application: %s at %s (status: %s)", existing.JobTitle, existing.Company, existing.Status)
|
||||
return "updated", &existing.ID, nil
|
||||
}
|
||||
|
||||
// cleanEmailBody strips HTML and truncates the email body for Claude.
|
||||
func cleanEmailBody(content string, contentType string) string {
|
||||
text := content
|
||||
|
||||
if strings.EqualFold(contentType, "html") {
|
||||
// Strip HTML tags
|
||||
tagRegex := regexp.MustCompile(`<[^>]*>`)
|
||||
text = tagRegex.ReplaceAllString(text, " ")
|
||||
|
||||
// Decode common HTML entities
|
||||
replacer := strings.NewReplacer(
|
||||
" ", " ",
|
||||
"&", "&",
|
||||
"<", "<",
|
||||
">", ">",
|
||||
""", `"`,
|
||||
"'", "'",
|
||||
"'", "'",
|
||||
)
|
||||
text = replacer.Replace(text)
|
||||
}
|
||||
|
||||
// Collapse whitespace
|
||||
spaceRegex := regexp.MustCompile(`[ \t]+`)
|
||||
text = spaceRegex.ReplaceAllString(text, " ")
|
||||
nlRegex := regexp.MustCompile(`\n{3,}`)
|
||||
text = nlRegex.ReplaceAllString(text, "\n\n")
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
// Remove common signatures
|
||||
sigPatterns := []string{
|
||||
"\n-- \n",
|
||||
"\nSent from my iPhone",
|
||||
"\nSent from my iPad",
|
||||
"\nGet Outlook for",
|
||||
}
|
||||
for _, pattern := range sigPatterns {
|
||||
if idx := strings.Index(text, pattern); idx > 0 {
|
||||
text = text[:idx]
|
||||
}
|
||||
}
|
||||
|
||||
// Remove forwarded email chains
|
||||
lines := strings.Split(text, "\n")
|
||||
var cleaned []string
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(strings.TrimSpace(line), ">") {
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, line)
|
||||
}
|
||||
text = strings.Join(cleaned, "\n")
|
||||
|
||||
// Truncate to ~4000 characters
|
||||
if len(text) > 4000 {
|
||||
text = text[:4000]
|
||||
}
|
||||
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
func truncate(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen]
|
||||
}
|
||||
|
||||
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
|
||||
|
||||
Return ONLY a JSON object with these exact keys:
|
||||
- "isJobEmail": boolean - true if this email is about a job application
|
||||
- "action": "create" | "update" | "none" - whether this represents a new application confirmation or an update to an existing one
|
||||
- "company": string - the company name
|
||||
- "jobTitle": string - the job title/position
|
||||
- "status": string - one of: "applied", "screening", "interviewing", "assessment", "offer", "rejected", "withdrawn"
|
||||
- "location": string or null - job location if mentioned
|
||||
- "url": string or null - any application portal URL
|
||||
- "appliedAt": string or null - ISO 8601 date if an application date is mentioned (YYYY-MM-DD format)
|
||||
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
|
||||
|
||||
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
|
||||
45
backend/services/ratelimit.go
Normal file
45
backend/services/ratelimit.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RateLimiter struct {
|
||||
mu sync.Mutex
|
||||
attempts map[string][]time.Time
|
||||
max int
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func NewRateLimiter(max int, window time.Duration) *RateLimiter {
|
||||
return &RateLimiter{
|
||||
attempts: make(map[string][]time.Time),
|
||||
max: max,
|
||||
window: window,
|
||||
}
|
||||
}
|
||||
|
||||
func (rl *RateLimiter) Allow(key string) bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
cutoff := now.Add(-rl.window)
|
||||
|
||||
// Remove expired entries
|
||||
valid := rl.attempts[key][:0]
|
||||
for _, t := range rl.attempts[key] {
|
||||
if t.After(cutoff) {
|
||||
valid = append(valid, t)
|
||||
}
|
||||
}
|
||||
|
||||
if len(valid) >= rl.max {
|
||||
rl.attempts[key] = valid
|
||||
return false
|
||||
}
|
||||
|
||||
rl.attempts[key] = append(valid, now)
|
||||
return true
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package services
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -24,11 +24,12 @@ var Upgrader = websocket.Upgrader{
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
origin = strings.TrimPrefix(origin, "https://")
|
||||
origin = strings.TrimPrefix(origin, "http://")
|
||||
// Strip port for localhost comparisons (e.g. "localhost:80")
|
||||
host := strings.Split(origin, ":")[0]
|
||||
return origin == allowedDomain || origin == "www."+allowedDomain || host == "localhost"
|
||||
u, err := url.Parse(origin)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
host := u.Hostname()
|
||||
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
|
||||
},
|
||||
}
|
||||
|
||||
@@ -40,8 +41,8 @@ var (
|
||||
)
|
||||
|
||||
const (
|
||||
rateLimitWindow = time.Second
|
||||
rateLimitMaxMsgs = 10
|
||||
rateLimitWindow = time.Second
|
||||
rateLimitMaxMsgs = 10
|
||||
)
|
||||
|
||||
func InitWebSocket(database *gorm.DB, domain string) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/bin/sh
|
||||
if [ ! -d /etc/letsencrypt/live/${DOMAIN} ]; then
|
||||
certbot certonly --webroot -w /var/www/certbot --email ${EMAIL} -d ${DOMAIN} -d www.${DOMAIN} --agree-tos --non-interactive;
|
||||
fi;
|
||||
certbot certonly --webroot -w /var/www/certbot \
|
||||
--email ${EMAIL} \
|
||||
-d ${DOMAIN} -d www.${DOMAIN} -d chat.${DOMAIN} \
|
||||
--agree-tos --non-interactive --expand;
|
||||
|
||||
trap exit TERM;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ services:
|
||||
volumes:
|
||||
- ./vue:/app
|
||||
- /app/node_modules
|
||||
- /app/src/wasm
|
||||
environment:
|
||||
- NODE_ENV=development
|
||||
backend:
|
||||
@@ -11,10 +12,11 @@ services:
|
||||
- SPOTIFY_REDIRECT_URI=https://localhost/api/spotify/callback
|
||||
- GQL_PLAYGROUND=true
|
||||
- GQL_INTROSPECTION=true
|
||||
- DEV_MODE=true
|
||||
- SEED_DB=true
|
||||
nginx:
|
||||
environment:
|
||||
- DEV_MODE=true
|
||||
- SEED_DB=true
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
|
||||
@@ -1,226 +1,219 @@
|
||||
networks:
|
||||
app-network:
|
||||
driver: bridge
|
||||
app-network:
|
||||
driver: bridge
|
||||
ipam:
|
||||
config:
|
||||
- subnet: 172.28.0.0/16
|
||||
|
||||
volumes:
|
||||
dbdata:
|
||||
uploads:
|
||||
vue_dist:
|
||||
uptime_kuma_data:
|
||||
searxng_data:
|
||||
# Postgres database
|
||||
dbdata:
|
||||
# File upload
|
||||
uploads:
|
||||
# Vue build
|
||||
vue_dist:
|
||||
# Searxng data
|
||||
searxng_data:
|
||||
# Open-WebUI data
|
||||
openwebui_data:
|
||||
|
||||
services:
|
||||
vue:
|
||||
build:
|
||||
context: ./vue
|
||||
dockerfile: Dockerfile
|
||||
container_name: vue
|
||||
volumes:
|
||||
- vue_dist:/output
|
||||
networks:
|
||||
- app-network
|
||||
vue:
|
||||
build:
|
||||
context: ./vue
|
||||
dockerfile: Dockerfile
|
||||
container_name: vue
|
||||
volumes:
|
||||
- vue_dist:/output
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
nginx:
|
||||
build:
|
||||
context: ./nginx
|
||||
dockerfile: Dockerfile
|
||||
container_name: nginx
|
||||
env_file: ./.env
|
||||
restart: always
|
||||
depends_on:
|
||||
- vue
|
||||
- backend
|
||||
- icecast2
|
||||
- gitea
|
||||
- hasura
|
||||
- quartz
|
||||
- uptime-kuma
|
||||
- searxng
|
||||
- wallabag
|
||||
networks:
|
||||
- app-network
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
volumes:
|
||||
- ./certbot/conf:/etc/letsencrypt
|
||||
- ./certbot/www:/var/www/certbot
|
||||
- uploads:/uploads
|
||||
- vue_dist:/etc/nginx/html
|
||||
nginx:
|
||||
build:
|
||||
context: ./nginx
|
||||
dockerfile: Dockerfile
|
||||
container_name: nginx
|
||||
env_file: ./.env
|
||||
restart: always
|
||||
depends_on:
|
||||
- vue
|
||||
- backend
|
||||
- icecast2
|
||||
- gitea
|
||||
- hasura
|
||||
- quartz
|
||||
- searxng
|
||||
- open-webui
|
||||
networks:
|
||||
- app-network
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
volumes:
|
||||
- ./certbot/conf:/etc/letsencrypt
|
||||
- ./certbot/www:/var/www/certbot
|
||||
- uploads:/uploads
|
||||
- vue_dist:/etc/nginx/html
|
||||
|
||||
certbot:
|
||||
image: certbot/certbot:v3.1.0
|
||||
container_name: certbot
|
||||
volumes:
|
||||
- ./certbot/entrypoint.sh:/entrypoint.sh
|
||||
- ./certbot/conf:/etc/letsencrypt
|
||||
- ./certbot/www:/var/www/certbot
|
||||
entrypoint: ["/entrypoint.sh"]
|
||||
env_file:
|
||||
- .env
|
||||
networks:
|
||||
- app-network
|
||||
certbot:
|
||||
image: certbot/certbot:v3.1.0
|
||||
container_name: certbot
|
||||
volumes:
|
||||
- ./certbot/entrypoint.sh:/entrypoint.sh
|
||||
- ./certbot/conf:/etc/letsencrypt
|
||||
- ./certbot/www:/var/www/certbot
|
||||
entrypoint: ["/entrypoint.sh"]
|
||||
env_file:
|
||||
- .env
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${BACKEND_HOST}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
- ./.env
|
||||
volumes:
|
||||
- ./backend/token/:/backend/token
|
||||
- ${OBSIDIAN_DIR}:/backend/notes
|
||||
- ./logs:/backend/logs
|
||||
- uploads:/backend/uploads
|
||||
- ./icecast2/fallback_music:/backend/fallback_music
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${BACKEND_HOST}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
- ./.env
|
||||
volumes:
|
||||
- ./backend/token/:/backend/token
|
||||
- ${OBSIDIAN_DIR}:/backend/notes
|
||||
- ./logs:/backend/logs
|
||||
- uploads:/backend/uploads
|
||||
- ./icecast2/fallback_music:/backend/fallback_music
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:8080/"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
db:
|
||||
image: postgres:16
|
||||
container_name: "${POSTGRES_HOST}"
|
||||
restart: always
|
||||
env_file:
|
||||
- ./.env
|
||||
networks:
|
||||
- app-network
|
||||
volumes:
|
||||
- dbdata:/var/lib/postgresql/data
|
||||
autoheal:
|
||||
image: willfarrell/autoheal:latest
|
||||
container_name: autoheal
|
||||
restart: always
|
||||
environment:
|
||||
- AUTOHEAL_CONTAINER_LABEL=all
|
||||
- AUTOHEAL_INTERVAL=30
|
||||
- AUTOHEAL_START_PERIOD=60
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
hasura:
|
||||
image: hasura/graphql-engine:v2.44.0
|
||||
container_name: "${HASURA_HOST}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||||
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
|
||||
HASURA_GRAPHQL_DEV_MODE: "false"
|
||||
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
|
||||
db:
|
||||
image: postgres:16
|
||||
container_name: "${POSTGRES_HOST}"
|
||||
restart: always
|
||||
env_file:
|
||||
- ./.env
|
||||
networks:
|
||||
- app-network
|
||||
volumes:
|
||||
- dbdata:/var/lib/postgresql/data
|
||||
|
||||
icecast2:
|
||||
build:
|
||||
context: ./icecast2
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${ICECAST_HOST}"
|
||||
restart: always
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
- ./.env
|
||||
volumes:
|
||||
- ./icecast2/fallback_music:/music:ro
|
||||
ports:
|
||||
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
|
||||
hasura:
|
||||
image: hasura/graphql-engine:v2.44.0
|
||||
container_name: "${HASURA_HOST}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||||
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
|
||||
HASURA_GRAPHQL_DEV_MODE: "false"
|
||||
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
|
||||
|
||||
quartz:
|
||||
build:
|
||||
context: ./quartz
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${QUARTZ_HOST}"
|
||||
restart: always
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
- ./.env
|
||||
volumes:
|
||||
- ${OBSIDIAN_DIR}:/quartz/content:ro
|
||||
icecast2:
|
||||
build:
|
||||
context: ./icecast2
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${ICECAST_HOST}"
|
||||
restart: always
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
- ./.env
|
||||
volumes:
|
||||
- ./icecast2/fallback_music:/music:ro
|
||||
ports:
|
||||
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
|
||||
|
||||
uptime-kuma:
|
||||
image: louislam/uptime-kuma:1
|
||||
container_name: "${UPTIMEKUMA_HOST}"
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
- UPTIME_KUMA_BASE_PATH=/uptime-kuma
|
||||
volumes:
|
||||
- uptime_kuma_data:/app/data
|
||||
quartz:
|
||||
build:
|
||||
context: ./quartz
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${QUARTZ_HOST}"
|
||||
restart: always
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
- ./.env
|
||||
volumes:
|
||||
- ${OBSIDIAN_DIR}:/quartz/content:ro
|
||||
|
||||
searxng:
|
||||
build:
|
||||
context: ./searxng
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${SEARXNG_HOST}"
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
- BASE_URL=https://www.${DOMAIN}/searxng/
|
||||
- INSTANCE_NAME=searxng
|
||||
- SEARXNG_SECRET_KEY=${SEARXNG_SECRET_KEY}
|
||||
volumes:
|
||||
- searxng_data:/etc/searxng
|
||||
searxng:
|
||||
build:
|
||||
context: ./searxng
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${SEARXNG_HOST}"
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
- BASE_URL=https://www.${DOMAIN}/searxng/
|
||||
- INSTANCE_NAME=searxng
|
||||
- SEARXNG_SECRET_KEY=${SEARXNG_SECRET_KEY}
|
||||
volumes:
|
||||
- searxng_data:/etc/searxng
|
||||
|
||||
wallabag:
|
||||
image: wallabag/wallabag:latest
|
||||
container_name: "${WALLABAG_HOST}"
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- app-network
|
||||
depends_on:
|
||||
- db
|
||||
environment:
|
||||
- SYMFONY__ENV__DOMAIN_NAME=https://www.${DOMAIN}/wallabag
|
||||
- SYMFONY__ENV__DATABASE_DRIVER=pdo_pgsql
|
||||
- SYMFONY__ENV__DATABASE_HOST=${POSTGRES_HOST}
|
||||
- SYMFONY__ENV__DATABASE_PORT=${POSTGRES_PORT}
|
||||
- SYMFONY__ENV__DATABASE_NAME=wallabag
|
||||
- SYMFONY__ENV__DATABASE_USER=${POSTGRES_USER}
|
||||
- SYMFONY__ENV__DATABASE_PASSWORD=${POSTGRES_PASSWORD}
|
||||
open-webui:
|
||||
image: ghcr.io/open-webui/open-webui:main
|
||||
container_name: "${OPENWEBUI_HOST}"
|
||||
restart: always
|
||||
networks:
|
||||
- app-network
|
||||
env_file:
|
||||
- ./.env
|
||||
environment:
|
||||
- OLLAMA_BASE_URL=${OLLAMA_BASE_URL}
|
||||
- WEBUI_AUTH=False
|
||||
- WEBUI_URL=https://chat.${DOMAIN}
|
||||
volumes:
|
||||
- openwebui_data:/app/backend/data
|
||||
|
||||
gitea-runner:
|
||||
build:
|
||||
context: ./gitea-runner
|
||||
dockerfile: Dockerfile
|
||||
container_name: "${GITEA_RUNNER_HOST}"
|
||||
environment:
|
||||
GITEA_RUNNER_NAME: ${GITEA_RUNNER_NAME}
|
||||
CONFIG_FILE: /config.yaml
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN: ${GITEA_RUNNER_REGISTRATION_TOKEN}
|
||||
GITEA_INSTANCE_URL: "http://${GITEA_HOST}:3000"
|
||||
GITEA_RUNNER_LABELS: "self-hosted:host"
|
||||
volumes:
|
||||
- ./gitea-runner/config.yaml:/config.yaml
|
||||
- ./gitea-runner/data:/data
|
||||
- /var/run/docker.sock:/var/run/docker.sock # WARNING: Docker socket mount gives container host-level access. Runner is in 'disabled' profile to mitigate risk.
|
||||
- /home/adamf/deploy/web_server:/home/adamf/deploy/web_server # Same path on host and container so docker compose bind mounts resolve correctly
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
gitea:
|
||||
image: docker.gitea.com/gitea:1.25.4-rootless
|
||||
container_name: "${GITEA_HOST}"
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
- GITEA__database__DB_TYPE=postgres
|
||||
- GITEA__database__HOST=${POSTGRES_HOST}
|
||||
- GITEA__database__NAME=${POSTGRES_GITEA_DB}
|
||||
- GITEA__database__USER=${POSTGRES_USER}
|
||||
- GITEA__database__PASSWD=${POSTGRES_PASSWORD}
|
||||
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
|
||||
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
|
||||
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
|
||||
- USER_UID=1000
|
||||
- USER_GID=1000
|
||||
restart: always
|
||||
volumes:
|
||||
- ./gitea/data:/var/lib/gitea
|
||||
- ./gitea/config:/etc/gitea
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
ports:
|
||||
- "2222:2222"
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
- db
|
||||
gitea:
|
||||
image: docker.gitea.com/gitea:1.25.4-rootless
|
||||
container_name: "${GITEA_HOST}"
|
||||
entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"]
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
- GITEA__database__DB_TYPE=postgres
|
||||
- GITEA__database__HOST=${POSTGRES_HOST}
|
||||
- GITEA__database__NAME=${POSTGRES_GITEA_DB}
|
||||
- GITEA__database__USER=${POSTGRES_USER}
|
||||
- GITEA__database__PASSWD=${POSTGRES_PASSWORD}
|
||||
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
|
||||
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
|
||||
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
|
||||
- USER_UID=1000
|
||||
- USER_GID=1000
|
||||
restart: always
|
||||
volumes:
|
||||
- ./gitea/data:/var/lib/gitea
|
||||
- ./gitea/config:/etc/gitea
|
||||
- ./gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro
|
||||
- /etc/timezone:/etc/timezone:ro
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
ports:
|
||||
- "2222:2222"
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
FROM gitea/act_runner:latest
|
||||
|
||||
RUN apk add --no-cache docker-cli docker-cli-compose
|
||||
@@ -1,112 +0,0 @@
|
||||
# Example configuration file, it's safe to copy this as the default config file without any modification.
|
||||
|
||||
# You don't have to copy this file to your instance,
|
||||
# just run `./act_runner generate-config > config.yaml` to generate a config file.
|
||||
|
||||
log:
|
||||
# The level of logging, can be trace, debug, info, warn, error, fatal
|
||||
level: info
|
||||
|
||||
runner:
|
||||
# Where to store the registration result.
|
||||
file: .runner
|
||||
# Execute how many tasks concurrently at the same time.
|
||||
capacity: 1
|
||||
# Extra environment variables to run jobs.
|
||||
envs:
|
||||
A_TEST_ENV_NAME_1: a_test_env_value_1
|
||||
A_TEST_ENV_NAME_2: a_test_env_value_2
|
||||
# Extra environment variables to run jobs from a file.
|
||||
# It will be ignored if it's empty or the file doesn't exist.
|
||||
env_file: .env
|
||||
# The timeout for a job to be finished.
|
||||
# Please note that the Gitea instance also has a timeout (3h by default) for the job.
|
||||
# So the job could be stopped by the Gitea instance if it's timeout is shorter than this.
|
||||
timeout: 3h
|
||||
# The timeout for the runner to wait for running jobs to finish when shutting down.
|
||||
# Any running jobs that haven't finished after this timeout will be cancelled.
|
||||
shutdown_timeout: 0s
|
||||
# Whether skip verifying the TLS certificate of the Gitea instance.
|
||||
insecure: false
|
||||
# The timeout for fetching the job from the Gitea instance.
|
||||
fetch_timeout: 5s
|
||||
# The interval for fetching the job from the Gitea instance.
|
||||
fetch_interval: 2s
|
||||
# The github_mirror of a runner is used to specify the mirror address of the github that pulls the action repository.
|
||||
# It works when something like `uses: actions/checkout@v4` is used and DEFAULT_ACTIONS_URL is set to github,
|
||||
# and github_mirror is not empty. In this case,
|
||||
# it replaces https://github.com with the value here, which is useful for some special network environments.
|
||||
github_mirror: ""
|
||||
# The labels of a runner are used to determine which jobs the runner can run, and how to run them.
|
||||
# Like: "macos-arm64:host" or "ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest"
|
||||
# Find more images provided by Gitea at https://gitea.com/docker.gitea.com/runner-images .
|
||||
# If it's empty when registering, it will ask for inputting labels.
|
||||
# If it's empty when execute `daemon`, will use labels in `.runner` file.
|
||||
labels:
|
||||
- "self-hosted:host"
|
||||
- "ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest"
|
||||
- "ubuntu-22.04:docker://docker.gitea.com/runner-images:ubuntu-22.04"
|
||||
- "ubuntu-20.04:docker://docker.gitea.com/runner-images:ubuntu-20.04"
|
||||
|
||||
cache:
|
||||
# Enable cache server to use actions/cache.
|
||||
enabled: true
|
||||
# The directory to store the cache data.
|
||||
# If it's empty, the cache data will be stored in $HOME/.cache/actcache.
|
||||
dir: ""
|
||||
# The host of the cache server.
|
||||
# It's not for the address to listen, but the address to connect from job containers.
|
||||
# So 0.0.0.0 is a bad choice, leave it empty to detect automatically.
|
||||
host: ""
|
||||
# The port of the cache server.
|
||||
# 0 means to use a random available port.
|
||||
port: 0
|
||||
# The external cache server URL. Valid only when enable is true.
|
||||
# If it's specified, act_runner will use this URL as the ACTIONS_CACHE_URL rather than start a server by itself.
|
||||
# The URL should generally end with "/".
|
||||
external_server: ""
|
||||
|
||||
container:
|
||||
# Specifies the network to which the container will connect.
|
||||
# Could be host, bridge or the name of a custom network.
|
||||
# If it's empty, act_runner will create a network automatically.
|
||||
network: ""
|
||||
# Whether to use privileged mode or not when launching task containers (privileged mode is required for Docker-in-Docker).
|
||||
privileged: false
|
||||
# And other options to be used when the container is started (eg, --add-host=my.gitea.url:host-gateway).
|
||||
options:
|
||||
# The parent directory of a job's working directory.
|
||||
# NOTE: There is no need to add the first '/' of the path as act_runner will add it automatically.
|
||||
# If the path starts with '/', the '/' will be trimmed.
|
||||
# For example, if the parent directory is /path/to/my/dir, workdir_parent should be path/to/my/dir
|
||||
# If it's empty, /workspace will be used.
|
||||
workdir_parent:
|
||||
# Volumes (including bind mounts) can be mounted to containers. Glob syntax is supported, see https://github.com/gobwas/glob
|
||||
# You can specify multiple volumes. If the sequence is empty, no volumes can be mounted.
|
||||
# For example, if you only allow containers to mount the `data` volume and all the json files in `/src`, you should change the config to:
|
||||
# valid_volumes:
|
||||
# - data
|
||||
# - /src/*.json
|
||||
# If you want to allow any volume, please use the following configuration:
|
||||
# valid_volumes:
|
||||
# - '**'
|
||||
valid_volumes:
|
||||
- "**"
|
||||
# overrides the docker client host with the specified one.
|
||||
# If it's empty, act_runner will find an available docker host automatically.
|
||||
# If it's "-", act_runner will find an available docker host automatically, but the docker host won't be mounted to the job containers and service containers.
|
||||
# If it's not empty or "-", the specified docker host will be used. An error will be returned if it doesn't work.
|
||||
docker_host: ""
|
||||
# Pull docker image(s) even if already present
|
||||
force_pull: true
|
||||
# Rebuild docker image(s) even if already present
|
||||
force_rebuild: false
|
||||
# Always require a reachable docker daemon, even if not required by act_runner
|
||||
require_docker: false
|
||||
# Timeout to wait for the docker daemon to be reachable, if docker is required by require_docker or act_runner
|
||||
docker_timeout: 0s
|
||||
|
||||
host:
|
||||
# The parent directory of a job's working directory.
|
||||
# If it's empty, $HOME/.cache/act/ will be used.
|
||||
workdir_parent:
|
||||
24
gitea-runner/download.sh
Executable file
24
gitea-runner/download.sh
Executable file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="0.2.11"
|
||||
BASE_URL="https://gitea.com/gitea/act_runner/releases/download/v${VERSION}"
|
||||
|
||||
ARCH=$(uname -m)
|
||||
case "$ARCH" in
|
||||
x86_64) ASSET="act_runner-${VERSION}-linux-amd64" ;;
|
||||
aarch64) ASSET="act_runner-${VERSION}-linux-arm64" ;;
|
||||
armv7l) ASSET="act_runner-${VERSION}-linux-armv7" ;;
|
||||
*)
|
||||
echo "Unsupported architecture: $ARCH" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
DEST="${SCRIPT_DIR}/act_runner"
|
||||
|
||||
echo "Downloading act_runner v${VERSION} for ${ARCH}..."
|
||||
curl -fSL "${BASE_URL}/${ASSET}" -o "$DEST"
|
||||
chmod +x "$DEST"
|
||||
echo "Downloaded to $DEST"
|
||||
27
gitea-runner/run.sh
Executable file
27
gitea-runner/run.sh
Executable file
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
if [ ! -f ./act_runner ]; then
|
||||
echo "act_runner binary not found. Downloading..." >&2
|
||||
bash "$(dirname "$0")/download.sh"
|
||||
fi
|
||||
|
||||
echo "Waiting for localhost:3000 to respond..." >&2
|
||||
|
||||
while ! curl -sf http://localhost:3000 > /dev/null 2>&1; do
|
||||
sleep 2
|
||||
done
|
||||
|
||||
echo "localhost:3000 is up." >&2
|
||||
|
||||
if [ ! -f .runner ]; then
|
||||
echo "No .runner file found. Registering runner..." >&2
|
||||
./act_runner register --no-interactive \
|
||||
--instance http://localhost:3000 \
|
||||
--token "${GITEA_RUNNER_REGISTRATION_TOKEN}" \
|
||||
--name "${GITEA_RUNNER_NAME:-pi-runner}" \
|
||||
--labels self-hosted
|
||||
fi
|
||||
|
||||
echo "Starting act_runner daemon..." >&2
|
||||
exec ./act_runner daemon
|
||||
|
||||
@@ -60,7 +60,6 @@ INSTALL_LOCK = true
|
||||
SECRET_KEY =
|
||||
REVERSE_PROXY_LIMIT = 1
|
||||
REVERSE_PROXY_TRUSTED_PROXIES = *
|
||||
INTERNAL_TOKEN =
|
||||
PASSWORD_HASH_ALGO = pbkdf2
|
||||
|
||||
[service]
|
||||
|
||||
0
gitea/config/entrypoint.sh
Normal file
0
gitea/config/entrypoint.sh
Normal file
10
gitea/entrypoint.sh
Executable file
10
gitea/entrypoint.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Generate app.ini from template if it doesn't already exist
|
||||
if [ ! -f /etc/gitea/app.ini ]; then
|
||||
cp /etc/gitea/app.ini.template /etc/gitea/app.ini
|
||||
echo "Generated app.ini from template"
|
||||
fi
|
||||
|
||||
exec /usr/local/bin/docker-entrypoint.sh "$@"
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Check if dev mode, certificate exists, or setup mode
|
||||
# Check if DEV_MODE
|
||||
if [ "$DEV_MODE" = "true" ]; then
|
||||
echo "Dev mode. Generating self-signed certificate for HTTPS."
|
||||
CERT_DIR="/etc/letsencrypt/live/localhost"
|
||||
@@ -12,16 +12,19 @@ if [ "$DEV_MODE" = "true" ]; then
|
||||
-out "$CERT_DIR/fullchain.pem" \
|
||||
-subj "/CN=localhost" 2>/dev/null
|
||||
fi
|
||||
envsubst '${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${SEARXNG_HOST} ${SEARXNG_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT}' \
|
||||
# In dev mode, so use nginx_dev.conf.template
|
||||
envsubst '${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${SEARXNG_HOST} ${SEARXNG_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT} ${OPENWEBUI_HOST} ${OPENWEBUI_PORT}' \
|
||||
</etc/nginx/nginx_dev.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
||||
echo "Certificates found. Using production nginx config."
|
||||
envsubst '${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${SEARXNG_HOST} ${SEARXNG_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT}' \
|
||||
# In production with certificates already existing, so use nginx.conf.template
|
||||
envsubst '${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${QUARTZ_HOST} ${QUARTZ_PORT} ${UPTIMEKUMA_HOST} ${UPTIMEKUMA_PORT} ${SEARXNG_HOST} ${SEARXNG_PORT} ${WALLABAG_HOST} ${WALLABAG_PORT} ${OPENWEBUI_HOST} ${OPENWEBUI_PORT}' \
|
||||
</etc/nginx/nginx.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
else
|
||||
echo "Certificates NOT found. Using setup nginx config."
|
||||
# In production with no certificates, so use nginx_setup.conf.template and will need restart after generation
|
||||
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
||||
fi
|
||||
|
||||
|
||||
@@ -9,10 +9,13 @@ http {
|
||||
server_tokens off;
|
||||
charset utf-8;
|
||||
|
||||
resolver 127.0.0.11 valid=10s;
|
||||
|
||||
client_max_body_size 50M;
|
||||
|
||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
|
||||
limit_req_zone $binary_remote_addr zone=graphql:10m rate=10r/s;
|
||||
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
|
||||
|
||||
log_format compact
|
||||
@@ -70,6 +73,12 @@ http {
|
||||
http2 on;
|
||||
server_name www.$DOMAIN;
|
||||
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_quartz http://$QUARTZ_HOST:$QUARTZ_PORT;
|
||||
set $upstream_searxng http://$SEARXNG_HOST:$SEARXNG_PORT;
|
||||
|
||||
root /etc/nginx/html;
|
||||
index index.html;
|
||||
@@ -138,7 +147,7 @@ http {
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
@@ -151,7 +160,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -161,7 +170,17 @@ http {
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/graphql {
|
||||
limit_req zone=graphql burst=10 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -171,7 +190,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -183,7 +202,8 @@ http {
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
proxy_pass http://$ICECAST_HOST:$ICECAST_PORT/;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -195,7 +215,8 @@ http {
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
proxy_pass http://$GITEA_HOST:$GITEA_PORT/;
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -207,7 +228,10 @@ http {
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
proxy_pass http://$HASURA_HOST:$HASURA_PORT/;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -222,7 +246,10 @@ http {
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
proxy_pass http://$QUARTZ_HOST:$QUARTZ_PORT/;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/notes/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_quartz;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
@@ -232,19 +259,18 @@ http {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /uptime-kuma {
|
||||
return 301 /uptime-kuma/;
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location /uptime-kuma/ {
|
||||
proxy_pass http://$UPTIMEKUMA_HOST:$UPTIMEKUMA_PORT;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
|
||||
location /searxng {
|
||||
@@ -252,25 +278,78 @@ http {
|
||||
}
|
||||
|
||||
location /searxng/ {
|
||||
proxy_pass http://$SEARXNG_HOST:$SEARXNG_PORT/;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/searxng/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_searxng;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /wallabag {
|
||||
return 301 /wallabag/;
|
||||
}
|
||||
|
||||
location /wallabag/ {
|
||||
proxy_pass http://$WALLABAG_HOST:$WALLABAG_PORT;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name chat.$DOMAIN;
|
||||
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://chat.$DOMAIN$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name chat.$DOMAIN;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
|
||||
|
||||
set $upstream_openwebui http://$OPENWEBUI_HOST:$OPENWEBUI_PORT;
|
||||
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
|
||||
|
||||
client_max_body_size 50M;
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 https://www.$DOMAIN/admin/login?redirect=https://chat.$DOMAIN$request_uri;
|
||||
}
|
||||
|
||||
location / {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
proxy_pass $upstream_openwebui;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ http {
|
||||
server_tokens off;
|
||||
charset utf-8;
|
||||
|
||||
resolver 127.0.0.11 valid=10s;
|
||||
|
||||
client_max_body_size 50M;
|
||||
|
||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||
@@ -44,6 +46,13 @@ http {
|
||||
listen 80;
|
||||
server_name $DOMAIN www.$DOMAIN;
|
||||
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_quartz http://$QUARTZ_HOST:$QUARTZ_PORT;
|
||||
set $upstream_searxng http://$SEARXNG_HOST:$SEARXNG_PORT;
|
||||
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
@@ -65,7 +74,7 @@ http {
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
@@ -78,7 +87,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -88,7 +97,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -98,7 +107,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -110,7 +119,8 @@ http {
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
proxy_pass http://$ICECAST_HOST:$ICECAST_PORT/;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -122,7 +132,8 @@ http {
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
proxy_pass http://$GITEA_HOST:$GITEA_PORT/;
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -134,7 +145,10 @@ http {
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
proxy_pass http://$HASURA_HOST:$HASURA_PORT/;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -149,7 +163,10 @@ http {
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
proxy_pass http://$QUARTZ_HOST:$QUARTZ_PORT/;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/notes/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_quartz;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
@@ -159,19 +176,18 @@ http {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /uptime-kuma {
|
||||
return 301 /uptime-kuma/;
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location /uptime-kuma/ {
|
||||
proxy_pass http://$UPTIMEKUMA_HOST:$UPTIMEKUMA_PORT;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
|
||||
location /searxng {
|
||||
@@ -179,19 +195,10 @@ http {
|
||||
}
|
||||
|
||||
location /searxng/ {
|
||||
proxy_pass http://$SEARXNG_HOST:$SEARXNG_PORT/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /wallabag {
|
||||
return 301 /wallabag/;
|
||||
}
|
||||
|
||||
location /wallabag/ {
|
||||
proxy_pass http://$WALLABAG_HOST:$WALLABAG_PORT;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/searxng/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_searxng;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -207,6 +214,13 @@ http {
|
||||
ssl_certificate /etc/letsencrypt/live/localhost/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/localhost/privkey.pem;
|
||||
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_quartz http://$QUARTZ_HOST:$QUARTZ_PORT;
|
||||
set $upstream_searxng http://$SEARXNG_HOST:$SEARXNG_PORT;
|
||||
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
@@ -228,7 +242,7 @@ http {
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
@@ -241,7 +255,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -251,7 +265,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -261,7 +275,7 @@ http {
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -273,7 +287,8 @@ http {
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
proxy_pass http://$ICECAST_HOST:$ICECAST_PORT/;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -285,7 +300,8 @@ http {
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
proxy_pass http://$GITEA_HOST:$GITEA_PORT/;
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -297,7 +313,10 @@ http {
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
proxy_pass http://$HASURA_HOST:$HASURA_PORT/;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -312,7 +331,10 @@ http {
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
proxy_pass http://$QUARTZ_HOST:$QUARTZ_PORT/;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/notes/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_quartz;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
@@ -322,19 +344,18 @@ http {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /uptime-kuma {
|
||||
return 301 /uptime-kuma/;
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location /uptime-kuma/ {
|
||||
proxy_pass http://$UPTIMEKUMA_HOST:$UPTIMEKUMA_PORT;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
|
||||
location /searxng {
|
||||
@@ -342,19 +363,10 @@ http {
|
||||
}
|
||||
|
||||
location /searxng/ {
|
||||
proxy_pass http://$SEARXNG_HOST:$SEARXNG_PORT/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /wallabag {
|
||||
return 301 /wallabag/;
|
||||
}
|
||||
|
||||
location /wallabag/ {
|
||||
proxy_pass http://$WALLABAG_HOST:$WALLABAG_PORT;
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/searxng/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_searxng;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
|
||||
147
readme.md
147
readme.md
@@ -1,147 +0,0 @@
|
||||
# My Web
|
||||
|
||||
## Important TODO
|
||||
|
||||
- Get a new background
|
||||
|
||||

|
||||
|
||||
Welcome to the source code for my website! Please contact me if you would like to collaborate and thank you for visiting.
|
||||
|
||||
This website is currently self hosted on my Raspberry Pi. Any interference and the killswitch will activate and stop the UK national grid power system so please don't tamper with my domain :).
|
||||
|
||||
## Architecture
|
||||
|
||||
All services run in Docker containers orchestrated by Docker Compose:
|
||||
|
||||
```
|
||||
vue ── Frontend build (outputs dist to shared volume)
|
||||
nginx (80, 443) ── Frontend SPA + Reverse Proxy
|
||||
backend (8080) ── Go API
|
||||
db (5432) ── PostgreSQL 16
|
||||
icecast2 (8000) ── Audio Streaming
|
||||
gitea (3000) ── Self-Hosted Git
|
||||
gitea-runner ── CI/CD Runner
|
||||
certbot ── SSL Certificate Management
|
||||
```
|
||||
|
||||
## Tech Stack
|
||||
|
||||
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), Rust/WASM
|
||||
|
||||
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
|
||||
|
||||
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
|
||||
|
||||
**Infrastructure** - Docker Compose, Nginx, Let's Encrypt (Certbot), Gitea + Act Runner
|
||||
|
||||
## Features
|
||||
|
||||
- Spotify integration (currently playing, recently played)
|
||||
- Steam integration (online status, recent games)
|
||||
- Obsidian note viewer with wikilink and LaTeX support
|
||||
- Live radio streaming via Icecast2
|
||||
- Real-time chat over WebSockets with image/video uploads
|
||||
- Blog with admin panel (CRUD)
|
||||
- Activity and rowing session tracking
|
||||
- Fan shrines (GTO, Evangelion, Demoman, Skip Skip Benben)
|
||||
- Self-hosted Git (Gitea) with CI/CD and commit feed on homepage
|
||||
- Claude AI integration
|
||||
- Printable CV with role-specific sections
|
||||
- Landing page with animated stamps section
|
||||
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | Description |
|
||||
| -------------- | ------------------------------------- |
|
||||
| `/` | Landing page |
|
||||
| `/stp` | Home dashboard with grid layout |
|
||||
| `/admin` | Admin panel (authenticated) |
|
||||
| `/cv` | Curriculum Vitae (printable) |
|
||||
| `/bookmarks` | Bookmarks |
|
||||
| `/notes/:path` | Obsidian note viewer |
|
||||
| `/shrines` | Fan shrine index + individual shrines |
|
||||
|
||||
## API
|
||||
|
||||
The primary API is **GraphQL** at `POST /api/graphql` (with a playground at `GET /api/graphql`). Queries cover posts, users, favorites, activities, rowing sessions, Spotify (currently playing, recently played), Gitea feed, and messages.
|
||||
|
||||
REST endpoints handle auth (`/auth/*`), Spotify OAuth (`/spotify/*`), file uploads (`/messages/upload`), note serving (`/notes/*`), and WebSocket chat (`/api/ws`). Steam data (online status, recent games) is also available via the GraphQL API.
|
||||
|
||||
Protected endpoints require JWT authentication via `/auth/login` (tokens set as HTTP-only cookies).
|
||||
|
||||
## Local Testing (Dev Mode)
|
||||
|
||||
Run the full stack over plain HTTP without SSL certificates:
|
||||
|
||||
```
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
```
|
||||
|
||||
This uses an HTTP-only nginx config with all routing (SPA, backend proxy, radio, gitea) and disables certbot. Visit `http://localhost` to test.
|
||||
|
||||
## Future Ideas
|
||||
|
||||
- More Rust to WASM
|
||||
- ML for chatboards
|
||||
- Cache requests
|
||||
- Design more webpages
|
||||
- Calendar to show radio times
|
||||
- Nice smooth function background and transitions
|
||||
- Design shrines
|
||||
- Redis (not really but practical experience)
|
||||
|
||||
## .env
|
||||
|
||||
These environment variables are found in the `.env` file. The use of environment variables can be found by reading the code so the security of the variable names are not significant.
|
||||
|
||||
```
|
||||
POSTGRES_USER=
|
||||
POSTGRES_PASSWORD=
|
||||
POSTGRES_DB=
|
||||
POSTGRES_PORT=
|
||||
POSTGRES_HOST=
|
||||
|
||||
GITEA_HOST=
|
||||
GITEA_PORT=
|
||||
POSTGRES_GITEA_DB=
|
||||
|
||||
GITEA_RUNNER_HOST=
|
||||
GITEA_RUNNER_NAME=
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN=
|
||||
|
||||
BACKEND_PORT=
|
||||
BACKEND_HOST=
|
||||
BACKEND_SECRET=
|
||||
BACKEND_ENDPOINT=
|
||||
|
||||
CLAUDE_API_KEY=
|
||||
|
||||
SEED_DB=
|
||||
|
||||
OBSIDIAN_DIR=
|
||||
|
||||
SPOTIFY_CLIENT_ID=
|
||||
SPOTIFY_CLIENT_SECRET=
|
||||
SPOTIFY_REDIRECT_URI=
|
||||
SPOTIFY_AUTH_STATE=
|
||||
|
||||
STEAM_API_KEY=
|
||||
STEAM_ID=
|
||||
|
||||
ICECAST_SOURCE_PASSWORD=
|
||||
ICECAST_RELAY_PASSWORD=
|
||||
ICECAST_ADMIN_USER=
|
||||
ICECAST_ADMIN_PASSWORD=
|
||||
ICECAST_HOST=
|
||||
ICECAST_PORT=
|
||||
ICECAST_MOUNT=
|
||||
|
||||
DOMAIN=
|
||||
EMAIL=
|
||||
|
||||
GITEA_LFS_JWT_SECRET=
|
||||
GITEA_INTERNAL_TOKEN=
|
||||
GITEA_OAUTH2_JWT_SECRET=
|
||||
```
|
||||
@@ -1,5 +1,6 @@
|
||||
FROM searxng/searxng:latest
|
||||
|
||||
|
||||
COPY settings.yml.template /searxng/settings.yml.template
|
||||
COPY entrypoint.sh /searxng/entrypoint.sh
|
||||
RUN chmod +x /searxng/entrypoint.sh
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/bin/bash
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
envsubst < /searxng/settings.yml.template > /etc/searxng/settings.yml
|
||||
sed -e "s|\${BASE_URL}|${BASE_URL}|g" \
|
||||
-e "s|\${SEARXNG_SECRET_KEY}|${SEARXNG_SECRET_KEY}|g" \
|
||||
/searxng/settings.yml.template > /etc/searxng/settings.yml
|
||||
|
||||
exec /usr/local/searxng/dockerfiles/docker-entrypoint.sh "$@"
|
||||
exec /usr/local/searxng/entrypoint.sh "$@"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use_default_settings: true
|
||||
|
||||
server:
|
||||
base_url: https://www.adam-french.co.uk/searxng/
|
||||
base_url: ${BASE_URL}
|
||||
secret_key: "${SEARXNG_SECRET_KEY}"
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
# Stage 1: Build WASM from Rust
|
||||
FROM rust:slim AS wasm-builder
|
||||
RUN rustup target add wasm32-unknown-unknown \
|
||||
&& cargo install wasm-pack
|
||||
WORKDIR /wasm
|
||||
COPY crates/stp_wasm/ crates/stp_wasm/
|
||||
RUN wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm
|
||||
|
||||
# Stage 2: Build Vue frontend
|
||||
FROM node:22-slim
|
||||
RUN apt-get update && apt-get install -y make git && rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
CMD ["sh", "-c", "npm run build -- --outDir /output --emptyOutDir"]
|
||||
COPY --from=wasm-builder /wasm/src/wasm/ src/wasm/
|
||||
CMD ["sh", "-c", "npx vite build --outDir /output --emptyOutDir"]
|
||||
|
||||
@@ -3,6 +3,9 @@ name = "stp_wasm"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
js-sys = "0.3.85"
|
||||
wasm-bindgen = "0.2.108"
|
||||
@@ -10,6 +13,13 @@ web-sys = { version = "0.3.85", features = [
|
||||
"console",
|
||||
"Document",
|
||||
"Element",
|
||||
"HtmlElement",
|
||||
"Window",
|
||||
"Animation",
|
||||
"CssStyleDeclaration",
|
||||
"ResizeObserver",
|
||||
"ResizeObserverEntry",
|
||||
"ResizeObserverSize",
|
||||
"EventTarget",
|
||||
"MouseEvent",
|
||||
] }
|
||||
|
||||
259
vue/crates/stp_wasm/src/auto_scroll.rs
Normal file
259
vue/crates/stp_wasm/src/auto_scroll.rs
Normal file
@@ -0,0 +1,259 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use web_sys::HtmlElement;
|
||||
|
||||
const SPEED: f64 = 0.0005; // % per frame
|
||||
const PAUSE: i32 = 2000; // ms at top/bottom
|
||||
|
||||
struct Inner {
|
||||
el: HtmlElement,
|
||||
pos: f64,
|
||||
direction: f64, // 1.0 = down, -1.0 = up
|
||||
hovered: bool,
|
||||
cached_scroll_height: f64,
|
||||
raf_id: Option<i32>,
|
||||
pause_timeout_id: Option<i32>,
|
||||
resize_observer: Option<web_sys::ResizeObserver>,
|
||||
// closures kept alive
|
||||
tick_closure: Option<Closure<dyn FnMut()>>,
|
||||
resize_closure: Option<Closure<dyn FnMut(js_sys::Array)>>,
|
||||
mouseenter_closure: Option<Closure<dyn FnMut()>>,
|
||||
mouseleave_closure: Option<Closure<dyn FnMut()>>,
|
||||
start_after_pause_closure: Option<Closure<dyn FnMut()>>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct AutoScroller {
|
||||
inner: Rc<RefCell<Inner>>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn measure_scroll_height(&mut self) {
|
||||
self.cached_scroll_height = self.el.scroll_height() as f64;
|
||||
}
|
||||
|
||||
fn stop_loop(&mut self) {
|
||||
let window = web_sys::window().unwrap();
|
||||
if let Some(id) = self.raf_id.take() {
|
||||
window.cancel_animation_frame(id).ok();
|
||||
}
|
||||
if let Some(id) = self.pause_timeout_id.take() {
|
||||
window.clear_timeout_with_handle(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_loop(inner: &Rc<RefCell<Inner>>) {
|
||||
{
|
||||
let mut s = inner.borrow_mut();
|
||||
s.stop_loop();
|
||||
}
|
||||
schedule_tick(inner);
|
||||
}
|
||||
|
||||
fn schedule_tick(inner: &Rc<RefCell<Inner>>) {
|
||||
let inner_clone = Rc::clone(inner);
|
||||
|
||||
// Create a fresh tick closure each frame
|
||||
let closure = Closure::once(move || {
|
||||
tick(&inner_clone);
|
||||
});
|
||||
|
||||
let mut s = inner.borrow_mut();
|
||||
let window = web_sys::window().unwrap();
|
||||
let id = window
|
||||
.request_animation_frame(closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
s.raf_id = Some(id);
|
||||
// Store the closure to keep it alive until the frame fires
|
||||
s.tick_closure = Some(closure);
|
||||
}
|
||||
|
||||
fn tick(inner: &Rc<RefCell<Inner>>) {
|
||||
let should_continue;
|
||||
{
|
||||
let mut s = inner.borrow_mut();
|
||||
s.raf_id = None;
|
||||
|
||||
if s.hovered {
|
||||
return;
|
||||
}
|
||||
|
||||
if s.cached_scroll_height == 0.0 {
|
||||
drop(s);
|
||||
schedule_tick(inner);
|
||||
return;
|
||||
}
|
||||
|
||||
let reached_bottom = s.pos >= 1.0;
|
||||
let reached_top = s.pos <= 0.0;
|
||||
|
||||
if reached_bottom {
|
||||
s.pos = 0.999;
|
||||
s.direction = -1.0;
|
||||
drop(s);
|
||||
schedule_pause(inner);
|
||||
return;
|
||||
} else if reached_top && s.direction == -1.0 {
|
||||
s.pos = 0.001;
|
||||
s.direction = 1.0;
|
||||
drop(s);
|
||||
schedule_pause(inner);
|
||||
return;
|
||||
}
|
||||
|
||||
s.pos += s.direction * SPEED;
|
||||
s.el.set_scroll_top((s.pos * s.cached_scroll_height) as i32);
|
||||
should_continue = true;
|
||||
}
|
||||
|
||||
if should_continue {
|
||||
schedule_tick(inner);
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_pause(inner: &Rc<RefCell<Inner>>) {
|
||||
{
|
||||
let mut s = inner.borrow_mut();
|
||||
s.stop_loop();
|
||||
}
|
||||
|
||||
let inner_clone = Rc::clone(inner);
|
||||
let closure = Closure::once(move || {
|
||||
start_loop(&inner_clone);
|
||||
});
|
||||
|
||||
let mut s = inner.borrow_mut();
|
||||
let window = web_sys::window().unwrap();
|
||||
let id = window
|
||||
.set_timeout_with_callback_and_timeout_and_arguments_0(
|
||||
closure.as_ref().unchecked_ref(),
|
||||
PAUSE,
|
||||
)
|
||||
.unwrap();
|
||||
s.pause_timeout_id = Some(id);
|
||||
s.start_after_pause_closure = Some(closure);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl AutoScroller {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(el: HtmlElement) -> AutoScroller {
|
||||
let inner = Rc::new(RefCell::new(Inner {
|
||||
el,
|
||||
pos: 0.0,
|
||||
direction: 1.0,
|
||||
hovered: false,
|
||||
cached_scroll_height: 0.0,
|
||||
raf_id: None,
|
||||
pause_timeout_id: None,
|
||||
resize_observer: None,
|
||||
tick_closure: None,
|
||||
resize_closure: None,
|
||||
mouseenter_closure: None,
|
||||
mouseleave_closure: None,
|
||||
start_after_pause_closure: None,
|
||||
}));
|
||||
|
||||
// Set up mouseenter listener
|
||||
{
|
||||
let inner_clone = Rc::clone(&inner);
|
||||
let closure = Closure::wrap(Box::new(move || {
|
||||
let mut s = inner_clone.borrow_mut();
|
||||
s.hovered = true;
|
||||
s.stop_loop();
|
||||
}) as Box<dyn FnMut()>);
|
||||
let s = inner.borrow();
|
||||
s.el
|
||||
.add_event_listener_with_callback("mouseenter", closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
drop(s);
|
||||
inner.borrow_mut().mouseenter_closure = Some(closure);
|
||||
}
|
||||
|
||||
// Set up mouseleave listener
|
||||
{
|
||||
let inner_clone = Rc::clone(&inner);
|
||||
let closure = Closure::wrap(Box::new(move || {
|
||||
{
|
||||
let mut s = inner_clone.borrow_mut();
|
||||
s.hovered = false;
|
||||
if s.cached_scroll_height > 0.0 {
|
||||
s.pos = s.el.scroll_top() as f64 / s.cached_scroll_height;
|
||||
}
|
||||
}
|
||||
start_loop(&inner_clone);
|
||||
}) as Box<dyn FnMut()>);
|
||||
let s = inner.borrow();
|
||||
s.el
|
||||
.add_event_listener_with_callback("mouseleave", closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
drop(s);
|
||||
inner.borrow_mut().mouseleave_closure = Some(closure);
|
||||
}
|
||||
|
||||
AutoScroller { inner }
|
||||
}
|
||||
|
||||
pub fn start(&self) {
|
||||
// Measure initial scroll height
|
||||
self.inner.borrow_mut().measure_scroll_height();
|
||||
|
||||
// Set up resize observer
|
||||
let inner_clone = Rc::clone(&self.inner);
|
||||
let resize_closure = Closure::wrap(Box::new(move |_entries: js_sys::Array| {
|
||||
inner_clone.borrow_mut().measure_scroll_height();
|
||||
}) as Box<dyn FnMut(js_sys::Array)>);
|
||||
|
||||
let observer =
|
||||
web_sys::ResizeObserver::new(resize_closure.as_ref().unchecked_ref()).unwrap();
|
||||
|
||||
// Clone the element ref and drop the borrow before calling observe(),
|
||||
// because observe() can fire the resize callback synchronously,
|
||||
// which would conflict with an active borrow.
|
||||
let el_clone = self.inner.borrow().el.clone();
|
||||
observer.observe(&el_clone);
|
||||
|
||||
{
|
||||
let mut s = self.inner.borrow_mut();
|
||||
s.resize_observer = Some(observer);
|
||||
s.resize_closure = Some(resize_closure);
|
||||
}
|
||||
|
||||
// Start with a pause then begin scrolling
|
||||
schedule_pause(&self.inner);
|
||||
}
|
||||
|
||||
pub fn destroy(&self) {
|
||||
let mut s = self.inner.borrow_mut();
|
||||
s.stop_loop();
|
||||
|
||||
if let Some(observer) = s.resize_observer.take() {
|
||||
observer.disconnect();
|
||||
}
|
||||
|
||||
if let Some(ref closure) = s.mouseenter_closure {
|
||||
s.el
|
||||
.remove_event_listener_with_callback(
|
||||
"mouseenter",
|
||||
closure.as_ref().unchecked_ref(),
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
if let Some(ref closure) = s.mouseleave_closure {
|
||||
s.el
|
||||
.remove_event_listener_with_callback(
|
||||
"mouseleave",
|
||||
closure.as_ref().unchecked_ref(),
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
|
||||
s.mouseenter_closure = None;
|
||||
s.mouseleave_closure = None;
|
||||
s.resize_closure = None;
|
||||
s.tick_closure = None;
|
||||
s.start_after_pause_closure = None;
|
||||
}
|
||||
}
|
||||
135
vue/crates/stp_wasm/src/headline.rs
Normal file
135
vue/crates/stp_wasm/src/headline.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use web_sys::HtmlElement;
|
||||
|
||||
const SPEED: f64 = 0.5; // pixels per frame
|
||||
|
||||
struct Inner {
|
||||
container: HtmlElement,
|
||||
item1: HtmlElement,
|
||||
offset: f64,
|
||||
cached_width: f64,
|
||||
raf_id: Option<i32>,
|
||||
resize_observer: Option<web_sys::ResizeObserver>,
|
||||
// closures kept alive
|
||||
animate_closure: Option<Closure<dyn FnMut()>>,
|
||||
resize_closure: Option<Closure<dyn FnMut(js_sys::Array)>>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct HeadlineScroller {
|
||||
inner: Rc<RefCell<Inner>>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn measure_width(&mut self) {
|
||||
let container_width = self.container.offset_width() as f64;
|
||||
let item_width = self.item1.scroll_width() as f64;
|
||||
self.cached_width = container_width.max(item_width);
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_frame(inner: &Rc<RefCell<Inner>>) {
|
||||
let inner_clone = Rc::clone(inner);
|
||||
|
||||
let closure = Closure::once(move || {
|
||||
animate(&inner_clone);
|
||||
});
|
||||
|
||||
let mut s = inner.borrow_mut();
|
||||
let window = web_sys::window().unwrap();
|
||||
let id = window
|
||||
.request_animation_frame(closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
s.raf_id = Some(id);
|
||||
s.animate_closure = Some(closure);
|
||||
}
|
||||
|
||||
fn animate(inner: &Rc<RefCell<Inner>>) {
|
||||
{
|
||||
let mut s = inner.borrow_mut();
|
||||
s.raf_id = None;
|
||||
|
||||
if s.cached_width == 0.0 {
|
||||
drop(s);
|
||||
schedule_frame(inner);
|
||||
return;
|
||||
}
|
||||
|
||||
s.offset -= SPEED;
|
||||
|
||||
if s.offset <= -s.cached_width {
|
||||
s.offset += s.cached_width;
|
||||
}
|
||||
|
||||
let transform = format!("translateX({}px)", s.offset);
|
||||
s.container.style().set_property("transform", &transform).ok();
|
||||
}
|
||||
|
||||
schedule_frame(inner);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl HeadlineScroller {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(container: HtmlElement, item1: HtmlElement) -> HeadlineScroller {
|
||||
let inner = Rc::new(RefCell::new(Inner {
|
||||
container,
|
||||
item1,
|
||||
offset: 0.0,
|
||||
cached_width: 0.0,
|
||||
raf_id: None,
|
||||
resize_observer: None,
|
||||
animate_closure: None,
|
||||
resize_closure: None,
|
||||
}));
|
||||
|
||||
HeadlineScroller { inner }
|
||||
}
|
||||
|
||||
pub fn start(&self) {
|
||||
// Measure initial width
|
||||
self.inner.borrow_mut().measure_width();
|
||||
|
||||
// Set up resize observer
|
||||
let inner_clone = Rc::clone(&self.inner);
|
||||
let resize_closure = Closure::wrap(Box::new(move |_entries: js_sys::Array| {
|
||||
inner_clone.borrow_mut().measure_width();
|
||||
}) as Box<dyn FnMut(js_sys::Array)>);
|
||||
|
||||
let observer =
|
||||
web_sys::ResizeObserver::new(resize_closure.as_ref().unchecked_ref()).unwrap();
|
||||
|
||||
// Clone the element ref and drop the borrow before calling observe(),
|
||||
// because observe() can fire the resize callback synchronously,
|
||||
// which would conflict with an active borrow.
|
||||
let container_clone = self.inner.borrow().container.clone();
|
||||
observer.observe(&container_clone);
|
||||
|
||||
{
|
||||
let mut s = self.inner.borrow_mut();
|
||||
s.resize_observer = Some(observer);
|
||||
s.resize_closure = Some(resize_closure);
|
||||
}
|
||||
|
||||
// Start animation loop
|
||||
schedule_frame(&self.inner);
|
||||
}
|
||||
|
||||
pub fn destroy(&self) {
|
||||
let mut s = self.inner.borrow_mut();
|
||||
|
||||
let window = web_sys::window().unwrap();
|
||||
if let Some(id) = s.raf_id.take() {
|
||||
window.cancel_animation_frame(id).ok();
|
||||
}
|
||||
|
||||
if let Some(observer) = s.resize_observer.take() {
|
||||
observer.disconnect();
|
||||
}
|
||||
|
||||
s.animate_closure = None;
|
||||
s.resize_closure = None;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
mod auto_scroll;
|
||||
mod headline;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct BadApplePlayer {
|
||||
is_playing: bool,
|
||||
}
|
||||
pub use auto_scroll::AutoScroller;
|
||||
pub use headline::HeadlineScroller;
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="Adam French's personal website">
|
||||
<title>AF</title>
|
||||
<link rel="preconnect" href="https://i.scdn.co" crossorigin>
|
||||
<link
|
||||
rel="preconnect"
|
||||
href="https://cdn.akamai.steamstatic.com"
|
||||
crossorigin
|
||||
>
|
||||
<link rel="icon" type="/img/x-icon" href="/img/favicon.ico">
|
||||
<link
|
||||
rel="preload"
|
||||
href="/fonts/big_noodle_titling.woff2"
|
||||
as="font"
|
||||
type="font/woff2"
|
||||
crossorigin
|
||||
>
|
||||
<link
|
||||
rel="preload"
|
||||
href="/fonts/CreatoDisplay-Bold.woff2"
|
||||
as="font"
|
||||
type="font/woff2"
|
||||
crossorigin
|
||||
>
|
||||
</head>
|
||||
<body id="app">
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="Adam French's personal website" />
|
||||
<title>AF</title>
|
||||
<link rel="preconnect" href="https://i.scdn.co" crossorigin />
|
||||
<link
|
||||
rel="preconnect"
|
||||
href="https://cdn.akamai.steamstatic.com"
|
||||
crossorigin
|
||||
/>
|
||||
<link rel="icon" type="/img/x-icon" href="/img/favicon.ico" />
|
||||
<link
|
||||
rel="preload"
|
||||
href="/fonts/big_noodle_titling.woff2"
|
||||
as="font"
|
||||
type="font/woff2"
|
||||
crossorigin
|
||||
/>
|
||||
<link
|
||||
rel="preload"
|
||||
href="/fonts/CreatoDisplay-Bold.woff2"
|
||||
as="font"
|
||||
type="font/woff2"
|
||||
crossorigin
|
||||
/>
|
||||
</head>
|
||||
<body id="app">
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
357
vue/package-lock.json
generated
357
vue/package-lock.json
generated
@@ -24,8 +24,10 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"vite": "^7.1.11",
|
||||
"vite-plugin-vue-devtools": "^8.0.3"
|
||||
"vite": "^7.3.2",
|
||||
"vite-plugin-top-level-await": "^1.6.0",
|
||||
"vite-plugin-vue-devtools": "^8.0.3",
|
||||
"vite-plugin-wasm": "^3.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
@@ -1024,6 +1026,24 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@rollup/plugin-virtual": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@rollup/plugin-virtual/-/plugin-virtual-3.0.2.tgz",
|
||||
"integrity": "sha512-10monEYsBp3scM4/ND4LNH5Rxvh3e/cVeL3jWTgZ2SrQ+BmUoQcopVQvnaMcOnykb1VkxUFuDAN+0FnpTFRy2A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"rollup": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@rollup/rollup-android-arm-eabi": {
|
||||
"version": "4.59.0",
|
||||
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
|
||||
@@ -1349,6 +1369,293 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@swc/core": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.15.24.tgz",
|
||||
"integrity": "sha512-5Hj8aNasue7yusUt8LGCUe/AjM7RMAce8ZoyDyiFwx7Al+GbYKL+yE7g4sJk8vEr1dKIkTRARkNIJENc4CjkBQ==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@swc/counter": "^0.1.3",
|
||||
"@swc/types": "^0.1.26"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/swc"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@swc/core-darwin-arm64": "1.15.24",
|
||||
"@swc/core-darwin-x64": "1.15.24",
|
||||
"@swc/core-linux-arm-gnueabihf": "1.15.24",
|
||||
"@swc/core-linux-arm64-gnu": "1.15.24",
|
||||
"@swc/core-linux-arm64-musl": "1.15.24",
|
||||
"@swc/core-linux-ppc64-gnu": "1.15.24",
|
||||
"@swc/core-linux-s390x-gnu": "1.15.24",
|
||||
"@swc/core-linux-x64-gnu": "1.15.24",
|
||||
"@swc/core-linux-x64-musl": "1.15.24",
|
||||
"@swc/core-win32-arm64-msvc": "1.15.24",
|
||||
"@swc/core-win32-ia32-msvc": "1.15.24",
|
||||
"@swc/core-win32-x64-msvc": "1.15.24"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@swc/helpers": ">=0.5.17"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@swc/helpers": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-darwin-arm64": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.15.24.tgz",
|
||||
"integrity": "sha512-uM5ZGfFXjtvtJ+fe448PVBEbn/CSxS3UAyLj3O9xOqKIWy3S6hPTXSPbszxkSsGDYKi+YFhzAsR4r/eXLxEQ0g==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-darwin-x64": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.15.24.tgz",
|
||||
"integrity": "sha512-fMIb/Zfn929pw25VMBhV7Ji2Dl+lCWtUPNdYJQYOke+00E5fcQ9ynxtP8+qhUo/HZc+mYQb1gJxwHM9vty+lXg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-arm-gnueabihf": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.15.24.tgz",
|
||||
"integrity": "sha512-vOkjsyjjxnoYx3hMEWcGxQrMgnNrRm6WAegBXrN8foHtDAR+zpdhpGF5a4lj1bNPgXAvmysjui8cM1ov/Clkaw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-arm64-gnu": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.15.24.tgz",
|
||||
"integrity": "sha512-h/oNu+upkXJ6Cicnq7YGVj9PkdfarLCdQa8l/FlHYvfv8CEiMaeeTnpLU7gSBH/rGxosM6Qkfa/J9mThGF9CLA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-arm64-musl": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.15.24.tgz",
|
||||
"integrity": "sha512-ZpF/pRe1guk6sKzQI9D1jAORtjTdNlyeXn9GDz8ophof/w2WhojRblvSDJaGe7rJjcPN8AaOkhwdRUh7q8oYIg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-ppc64-gnu": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-linux-ppc64-gnu/-/core-linux-ppc64-gnu-1.15.24.tgz",
|
||||
"integrity": "sha512-QZEsZfisHTSJlmyChgDFNmKPb3W6Lhbfo/O76HhIngfEdnQNmukS38/VSe1feho+xkV5A5hETyCbx3sALBZKAQ==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-s390x-gnu": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-linux-s390x-gnu/-/core-linux-s390x-gnu-1.15.24.tgz",
|
||||
"integrity": "sha512-DLdJKVsJgglqQrJBuoUYNmzm3leI7kUZhLbZGHv42onfKsGf6JDS3+bzCUQfte/XOqDjh/tmmn1DR/CF/tCJFw==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-x64-gnu": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.15.24.tgz",
|
||||
"integrity": "sha512-IpLYfposPA/XLxYOKpRfeccl1p5dDa3+okZDHHTchBkXEaVCnq5MADPmIWwIYj1tudt7hORsEHccG5no6IUQRw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-linux-x64-musl": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.15.24.tgz",
|
||||
"integrity": "sha512-JHy3fMSc0t/EPWgo74+OK5TGr51aElnzqfUPaiRf2qJ/BfX5CUCfMiWVBuhI7qmVMBnk1jTRnL/xZnOSHDPLYg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-win32-arm64-msvc": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.15.24.tgz",
|
||||
"integrity": "sha512-Txj+qUH1z2bUd1P3JvwByfjKFti3cptlAxhWgmunBUUxy/IW3CXLZ6l6Gk4liANadKkU71nIU1X30Z5vpMT3BA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-win32-ia32-msvc": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.15.24.tgz",
|
||||
"integrity": "sha512-15D/nl3XwrhFpMv+MADFOiVwv3FvH9j8c6Rf8EXBT3Q5LoMh8YnDnSgPYqw1JzPnksvsBX6QPXLiPqmcR/Z4qQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core-win32-x64-msvc": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.15.24.tgz",
|
||||
"integrity": "sha512-PR0PlTlPra2JbaDphrOAzm6s0v9rA0F17YzB+XbWD95B4g2cWcZY9LAeTa4xll70VLw9Jr7xBrlohqlQmelMFQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 AND MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/counter": {
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
|
||||
"integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@swc/types": {
|
||||
"version": "0.1.26",
|
||||
"resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.26.tgz",
|
||||
"integrity": "sha512-lyMwd7WGgG79RS7EERZV3T8wMdmPq3xwyg+1nmAM64kIhx5yl+juO2PYIHb7vTiPgPCj8LYjsNV2T5wiQHUEaw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@swc/counter": "^0.1.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/wasm": {
|
||||
"version": "1.15.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/wasm/-/wasm-1.15.24.tgz",
|
||||
"integrity": "sha512-vFjzOE8dhJcfeTbM4+HO9Qy58IINV0ysqStAgw81uds+KqCeUDM9huN+SZ5lWZ6U+5nf8VcZoEw5N81xMtAidg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@tailwindcss/node": {
|
||||
"version": "4.1.18",
|
||||
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",
|
||||
@@ -3518,10 +3825,24 @@
|
||||
"integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",
|
||||
"license": "(WTFPL OR MIT)"
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
|
||||
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.3.1",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz",
|
||||
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
|
||||
"version": "7.3.2",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
|
||||
"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "^0.27.0",
|
||||
@@ -3661,6 +3982,22 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite-plugin-top-level-await": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/vite-plugin-top-level-await/-/vite-plugin-top-level-await-1.6.0.tgz",
|
||||
"integrity": "sha512-bNhUreLamTIkoulCR9aDXbTbhLk6n1YE8NJUTTxl5RYskNRtzOR0ASzSjBVRtNdjIfngDXo11qOsybGLNsrdww==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@rollup/plugin-virtual": "^3.0.2",
|
||||
"@swc/core": "^1.12.14",
|
||||
"@swc/wasm": "^1.12.14",
|
||||
"uuid": "10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vite": ">=2.8"
|
||||
}
|
||||
},
|
||||
"node_modules/vite-plugin-vue-devtools": {
|
||||
"version": "8.0.5",
|
||||
"resolved": "https://registry.npmjs.org/vite-plugin-vue-devtools/-/vite-plugin-vue-devtools-8.0.5.tgz",
|
||||
@@ -3736,6 +4073,16 @@
|
||||
"vite": "^3.0.0-0 || ^4.0.0-0 || ^5.0.0-0 || ^6.0.0-0 || ^7.0.0-0"
|
||||
}
|
||||
},
|
||||
"node_modules/vite-plugin-wasm": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/vite-plugin-wasm/-/vite-plugin-wasm-3.6.0.tgz",
|
||||
"integrity": "sha512-mL/QPziiIA4RAA6DkaZZzOstdwbW5jO4Vz7Zenj0wieKWBlNvIvX5L5ljum9lcUX0ShNfBgCNLKTjNkRVVqcsw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"vite": "^2 || ^3 || ^4 || ^5 || ^6 || ^7 || ^8"
|
||||
}
|
||||
},
|
||||
"node_modules/vue": {
|
||||
"version": "3.5.26",
|
||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.26.tgz",
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build:wasm": "wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm",
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build": "npm run build:wasm && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -28,7 +29,9 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"vite": "^7.1.11",
|
||||
"vite-plugin-vue-devtools": "^8.0.3"
|
||||
"vite": "^7.3.2",
|
||||
"vite-plugin-top-level-await": "^1.6.0",
|
||||
"vite-plugin-vue-devtools": "^8.0.3",
|
||||
"vite-plugin-wasm": "^3.6.0"
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 221 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 569 KiB |
@@ -1,32 +1,7 @@
|
||||
<script setup>
|
||||
import { RouterView } from "vue-router";
|
||||
import Navbar from "@/components/Navbar.vue";
|
||||
import Footer from "@/components/Footer.vue";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app-layout halftone">
|
||||
<Navbar class="no-print sticky top-0 z-50" />
|
||||
<main class="app-content">
|
||||
<RouterView v-slot="{ Component }">
|
||||
<Transition name="slide" mode="out-in">
|
||||
<component :is="Component" :key="$route.path" />
|
||||
</Transition>
|
||||
</RouterView>
|
||||
</main>
|
||||
<Footer class="no-print sticky bottom-0 z-50" />
|
||||
</div>
|
||||
<RouterView />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.app-layout {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.app-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,208 +3,227 @@
|
||||
/* Route transitions */
|
||||
.slide-enter-active,
|
||||
.slide-leave-active {
|
||||
transition:
|
||||
transform 0.3s ease,
|
||||
opacity 0.3s ease;
|
||||
transition:
|
||||
transform 0.3s ease,
|
||||
opacity 0.3s ease;
|
||||
}
|
||||
.slide-enter-from {
|
||||
transform: translateX(30px);
|
||||
opacity: 0;
|
||||
transform: translateX(30px);
|
||||
opacity: 0;
|
||||
}
|
||||
.slide-leave-to {
|
||||
transform: translateX(-30px);
|
||||
opacity: 0;
|
||||
transform: translateX(-30px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* PRINTING */
|
||||
@media print {
|
||||
.no-print,
|
||||
.no-print * {
|
||||
display: none !important;
|
||||
margin: 0px;
|
||||
padding: 0px;
|
||||
width: 0x;
|
||||
height: 0px;
|
||||
}
|
||||
.no-print,
|
||||
.no-print * {
|
||||
display: none !important;
|
||||
margin: 0px;
|
||||
padding: 0px;
|
||||
width: 0x;
|
||||
height: 0px;
|
||||
}
|
||||
}
|
||||
|
||||
/* END OF PRINTING */
|
||||
|
||||
/* FONTS */
|
||||
@font-face {
|
||||
font-family: "big_noodle_titling";
|
||||
src: url("/fonts/big_noodle_titling.woff2") format("woff2");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-family: "big_noodle_titling";
|
||||
src: url("/fonts/big_noodle_titling.woff2") format("woff2");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CreatoDisplay";
|
||||
src: url("/fonts/CreatoDisplay-Bold.woff2") format("woff2");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
font-family: "CreatoDisplay";
|
||||
src: url("/fonts/CreatoDisplay-Bold.woff2") format("woff2");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* END OF FONTS */
|
||||
|
||||
/* VARIABLES */
|
||||
:root {
|
||||
/* RED, WHITE, BLACK are standard*/
|
||||
--portal_grey: #dddddd;
|
||||
--portal_orange: #ff9a00;
|
||||
--portal_light_orange: #ff5d00;
|
||||
--portal_blue: #0065ff;
|
||||
--portal_light_blue: #00a2ff;
|
||||
/* RED, WHITE, BLACK are standard*/
|
||||
--portal_grey: #dddddd;
|
||||
--portal_orange: #ff9a00;
|
||||
--portal_light_orange: #ff5d00;
|
||||
--portal_blue: #0065ff;
|
||||
--portal_light_blue: #00a2ff;
|
||||
|
||||
/* MAIN COLORS */
|
||||
--primary: #55ffbb;
|
||||
--secondary: #62ff57;
|
||||
--tertiary: #ff579a;
|
||||
--quaternary: #024942;
|
||||
/* MAIN COLORS */
|
||||
--primary: #55ffbb;
|
||||
--secondary: #62ff57;
|
||||
--tertiary: #ff579a;
|
||||
--quaternary: #024942;
|
||||
|
||||
/* BACKGROUND COLORS */
|
||||
--bg_primary: #1b110e;
|
||||
--bg_secondary: #04080f;
|
||||
--bg_tertiary: #0c1c10;
|
||||
--link: #222;
|
||||
/* BACKGROUND COLORS */
|
||||
--bg_primary: #1b110e;
|
||||
--bg_secondary: #04080f;
|
||||
--bg_tertiary: #0c1c10;
|
||||
--link: #222;
|
||||
|
||||
--bdr: 2px;
|
||||
--bdr: 2px;
|
||||
|
||||
--spacing: 3px;
|
||||
--spacing: 3px;
|
||||
|
||||
/* FONTS USED */
|
||||
--font_heading: big_noodle_titling;
|
||||
--font_default: CreatoDisplay;
|
||||
/* FONTS USED */
|
||||
--font_heading: big_noodle_titling;
|
||||
--font_default: CreatoDisplay;
|
||||
}
|
||||
|
||||
@theme {
|
||||
--color-primary: var(--primary);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-tertiary: var(--tertiary);
|
||||
--color-quaternary: var(--quaternary);
|
||||
--color-primary: var(--primary);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-tertiary: var(--tertiary);
|
||||
--color-quaternary: var(--quaternary);
|
||||
|
||||
--color-bg_primary: var(--bg_primary);
|
||||
--color-bg_secondary: var(--bg_secondary);
|
||||
--color-link: var(--link);
|
||||
--color-bg_primary: var(--bg_primary);
|
||||
--color-bg_secondary: var(--bg_secondary);
|
||||
--color-link: var(--link);
|
||||
|
||||
--borderWidth-primary: var(--primary);
|
||||
--borderWidth-secondary: var(--secondary);
|
||||
--borderWidth-tertiary: var(--tertiary);
|
||||
--borderWidth-primary: var(--primary);
|
||||
--borderWidth-secondary: var(--secondary);
|
||||
--borderWidth-tertiary: var(--tertiary);
|
||||
|
||||
--font-heading: var(--font_heading);
|
||||
--default-font-family: var(--font_default);
|
||||
--font-heading: var(--font_heading);
|
||||
--default-font-family: var(--font_default);
|
||||
}
|
||||
|
||||
/* END OF VARIABLES */
|
||||
/* ELEMENTS */
|
||||
body {
|
||||
margin: 0 auto;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--primary) var(--bg_secondary);
|
||||
}
|
||||
|
||||
/* Chrome/Edge scrollbar styling */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--bg_secondary);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--quaternary);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--primary);
|
||||
}
|
||||
|
||||
input {
|
||||
color: var(--secondary);
|
||||
border-color: var(--primary);
|
||||
border-width: 1px;
|
||||
color: var(--secondary);
|
||||
border-color: var(--primary);
|
||||
border-width: 1px;
|
||||
}
|
||||
|
||||
small {
|
||||
color: var(--tertiary);
|
||||
color: var(--tertiary);
|
||||
}
|
||||
|
||||
code {
|
||||
color: var(--tertiary);
|
||||
color: var(--tertiary);
|
||||
}
|
||||
|
||||
ul {
|
||||
color: var(--tertiary);
|
||||
color: var(--tertiary);
|
||||
}
|
||||
|
||||
li {
|
||||
color: var(--tertiary);
|
||||
color: var(--tertiary);
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4 {
|
||||
margin: 0.25rem;
|
||||
font-family: var(--font_heading);
|
||||
color: var(--primary);
|
||||
margin: 0.25rem;
|
||||
font-family: var(--font_heading);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
h3,
|
||||
h4 {
|
||||
font-size: 1.125rem;
|
||||
line-height: 1.75rem;
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.5rem;
|
||||
line-height: 2rem;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.25rem;
|
||||
line-height: 1.75rem;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
p {
|
||||
color: var(--secondary);
|
||||
color: var(--secondary);
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--primary);
|
||||
background-color: var(--link);
|
||||
text-align: center;
|
||||
font-family: var(--font_heading);
|
||||
letter-spacing: 0.025em;
|
||||
color: var(--primary);
|
||||
background-color: var(--link);
|
||||
text-align: center;
|
||||
font-family: var(--font_heading);
|
||||
letter-spacing: 0.025em;
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
color: var(--primary);
|
||||
border-width: 1px;
|
||||
padding: 0.5rem;
|
||||
width: 100%;
|
||||
color: var(--primary);
|
||||
border-width: 1px;
|
||||
padding: 0.5rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
color: var(--secondary);
|
||||
opacity: 0.5;
|
||||
color: var(--secondary);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
table {
|
||||
border-color: var(--primary);
|
||||
border-width: 1px;
|
||||
color: var(--primary);
|
||||
border-color: var(--primary);
|
||||
border-width: 1px;
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
td {
|
||||
gap: 0.25rem;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
tr {
|
||||
border-color: var(--primary);
|
||||
border-bottom-width: 1px;
|
||||
color: var(--primary);
|
||||
border-color: var(--primary);
|
||||
border-bottom-width: 1px;
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
th {
|
||||
padding-right: 0.75rem;
|
||||
padding-left: 0.75rem;
|
||||
border-right-width: 1px;
|
||||
border-style: dotted;
|
||||
border-color: var(--tertiary);
|
||||
padding-right: 0.75rem;
|
||||
padding-left: 0.75rem;
|
||||
border-right-width: 1px;
|
||||
border-style: dotted;
|
||||
border-color: var(--tertiary);
|
||||
}
|
||||
|
||||
td {
|
||||
padding-right: 0.75rem;
|
||||
padding-left: 0.75rem;
|
||||
padding-right: 0.75rem;
|
||||
padding-left: 0.75rem;
|
||||
}
|
||||
|
||||
/* END OF ELEMENTS */
|
||||
@@ -212,146 +231,146 @@ td {
|
||||
/* CLASSES */
|
||||
|
||||
.img-stamp {
|
||||
width: 99px;
|
||||
height: 55px;
|
||||
width: 99px;
|
||||
height: 55px;
|
||||
}
|
||||
|
||||
/* BORDERS */
|
||||
.bdr-1 {
|
||||
border-width: 30px;
|
||||
border-image: url("/img/borders/border1.gif") 30 round;
|
||||
border-width: 30px;
|
||||
border-image: url("/img/borders/border1.gif") 30 round;
|
||||
}
|
||||
|
||||
.bdr-1-inv {
|
||||
border-width: 30px;
|
||||
border-image: url("/img/borders/border1inv.gif") 30 round;
|
||||
border-width: 30px;
|
||||
border-image: url("/img/borders/border1inv.gif") 30 round;
|
||||
}
|
||||
|
||||
.bdr-2 {
|
||||
border-width: 5px;
|
||||
border-image: url("/img/borders/border4.gif") 7 round;
|
||||
border-width: 5px;
|
||||
border-image: url("/img/borders/border4.gif") 7 round;
|
||||
}
|
||||
|
||||
.bdr-cv {
|
||||
border-width: 30px;
|
||||
border-image: url("/img/borders/bordercv.png") 30 round;
|
||||
border-width: 30px;
|
||||
border-image: url("/img/borders/bordercv.png") 30 round;
|
||||
}
|
||||
|
||||
/* A5 Page */
|
||||
.a5page-landscape {
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
height: 148mm;
|
||||
width: 210mm;
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
height: 148mm;
|
||||
width: 210mm;
|
||||
}
|
||||
|
||||
.a5page-portrait {
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
width: 148mm;
|
||||
height: 210mm;
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
width: 148mm;
|
||||
height: 210mm;
|
||||
}
|
||||
|
||||
/* A4 Page */
|
||||
.a4page-portrait {
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
width: 210mm;
|
||||
height: 297mm;
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
width: 210mm;
|
||||
height: 297mm;
|
||||
}
|
||||
|
||||
.a4page-landscape {
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
height: 210mm;
|
||||
width: 297mm;
|
||||
margin: 0;
|
||||
box-sizing: content-box;
|
||||
height: 210mm;
|
||||
width: 297mm;
|
||||
}
|
||||
|
||||
/* END OF CLASSES */
|
||||
|
||||
/* PHONE */
|
||||
@media (max-width: 850px) {
|
||||
.a4page-portrait {
|
||||
width: 100%;
|
||||
/* fill mobile width */
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
/* center horizontally */
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.a4page-portrait {
|
||||
width: 100%;
|
||||
/* fill mobile width */
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
/* center horizontally */
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.a4page-landscape {
|
||||
width: 100%;
|
||||
/* fill mobile width */
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
/* center horizontally */
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.a4page-landscape {
|
||||
width: 100%;
|
||||
/* fill mobile width */
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
/* center horizontally */
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.a5page-portrait {
|
||||
width: 100%;
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.a5page-portrait {
|
||||
width: 100%;
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.a5page-landscape {
|
||||
width: 100%;
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.a5page-landscape {
|
||||
width: 100%;
|
||||
height: fit-content;
|
||||
margin: 0 auto;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
.tl {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.tr {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.bl {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.br {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.background {
|
||||
position: fixed;
|
||||
position: fixed;
|
||||
}
|
||||
|
||||
.halftone {
|
||||
--dot_size: 4px;
|
||||
--bg_size: 12px;
|
||||
--bg_pos: calc(var(--bg_size) / 2);
|
||||
--blur: 0%;
|
||||
--dot_size: 4px;
|
||||
--bg_size: 12px;
|
||||
--bg_pos: calc(var(--bg_size) / 2);
|
||||
--blur: 0%;
|
||||
|
||||
background-color: var(--bg_secondary);
|
||||
background-image:
|
||||
linear-gradient(to top, transparent 0%, var(--bg_primary) 100%),
|
||||
radial-gradient(
|
||||
circle at center,
|
||||
var(--bg_tertiary) var(--dot_size),
|
||||
transparent var(--blur)
|
||||
);
|
||||
background-size:
|
||||
100% 100%,
|
||||
var(--bg_size) var(--bg_size);
|
||||
background-position:
|
||||
0 0,
|
||||
0 0;
|
||||
background-color: var(--bg_secondary);
|
||||
background-image:
|
||||
linear-gradient(to top, transparent 0%, var(--bg_primary) 100%),
|
||||
radial-gradient(
|
||||
circle at center,
|
||||
var(--bg_tertiary) var(--dot_size),
|
||||
transparent var(--blur)
|
||||
);
|
||||
background-size:
|
||||
100% 100%,
|
||||
var(--bg_size) var(--bg_size);
|
||||
background-position:
|
||||
0 0,
|
||||
0 0;
|
||||
}
|
||||
|
||||
@@ -5,128 +5,128 @@ const clock = ref("");
|
||||
let timer;
|
||||
|
||||
function updateClock() {
|
||||
const now = new Date();
|
||||
clock.value = now.toLocaleDateString("en-US", {
|
||||
weekday: "short",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
const now = new Date();
|
||||
clock.value = now.toLocaleDateString("en-US", {
|
||||
weekday: "short",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
updateClock();
|
||||
timer = setInterval(updateClock, 1000);
|
||||
updateClock();
|
||||
timer = setInterval(updateClock, 1000);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
clearInterval(timer);
|
||||
clearInterval(timer);
|
||||
});
|
||||
|
||||
const user = "visitor";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<footer class="waybar">
|
||||
<div class="modules-left">
|
||||
<span class="workspace active">ツ</span>
|
||||
</div>
|
||||
<footer class="waybar">
|
||||
<div class="modules-left">
|
||||
<span class="workspace active">ツ</span>
|
||||
</div>
|
||||
|
||||
<div class="modules-right">
|
||||
<span class="module greeting">Hi, {{ user }}!</span>
|
||||
<span class="module cpu hide-sm">CPU 3%</span>
|
||||
<span class="module mem hide-sm">MEM 42%</span>
|
||||
<span class="module disk hide-sm">DISK 67%</span>
|
||||
<span class="module network hide-sm">↑ 12K ↓ 84K</span>
|
||||
<span class="module battery hide-sm">BAT 98%</span>
|
||||
<span class="module clock">{{ clock }}</span>
|
||||
</div>
|
||||
</footer>
|
||||
<div class="modules-right">
|
||||
<span class="module greeting">Hi, {{ user }}!</span>
|
||||
<span class="module cpu hide-sm">CPU 3%</span>
|
||||
<span class="module mem hide-sm">MEM 42%</span>
|
||||
<span class="module disk hide-sm">DISK 67%</span>
|
||||
<span class="module network hide-sm">↑ 12K ↓ 84K</span>
|
||||
<span class="module battery hide-sm">BAT 98%</span>
|
||||
<span class="module clock">{{ clock }}</span>
|
||||
</div>
|
||||
</footer>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.waybar {
|
||||
font-family: "URWGothic-Book", monospace;
|
||||
background-color: var(--bg_primary);
|
||||
color: var(--primary);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 4px 8px;
|
||||
font-size: 14px;
|
||||
min-height: 36px;
|
||||
flex-shrink: 0;
|
||||
font-family: "URWGothic-Book", monospace;
|
||||
background-color: var(--bg_primary);
|
||||
color: var(--primary);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 4px 8px;
|
||||
font-size: 14px;
|
||||
min-height: 36px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.modules-left {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.workspace {
|
||||
background: var(--quaternary);
|
||||
border: none;
|
||||
border-bottom: 2px solid var(--secondary);
|
||||
color: var(--secondary);
|
||||
padding: 2px 10px;
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
background: var(--quaternary);
|
||||
border: none;
|
||||
border-bottom: 2px solid var(--secondary);
|
||||
color: var(--secondary);
|
||||
padding: 2px 10px;
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.modules-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.module {
|
||||
padding: 2px 12px;
|
||||
border-left: 1px solid var(--tertiary);
|
||||
padding: 2px 12px;
|
||||
border-left: 1px solid var(--tertiary);
|
||||
}
|
||||
|
||||
.module:first-child {
|
||||
border-left: none;
|
||||
border-left: none;
|
||||
}
|
||||
|
||||
.greeting {
|
||||
color: var(--secondary);
|
||||
color: var(--secondary);
|
||||
}
|
||||
|
||||
.clock {
|
||||
color: var(--tertiary);
|
||||
color: var(--tertiary);
|
||||
}
|
||||
|
||||
.cpu,
|
||||
.mem,
|
||||
.disk {
|
||||
color: var(--primary);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.network {
|
||||
color: var(--secondary);
|
||||
color: var(--secondary);
|
||||
}
|
||||
|
||||
.battery {
|
||||
color: var(--primary);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.waybar {
|
||||
font-size: 11px;
|
||||
padding: 4px 4px;
|
||||
}
|
||||
.waybar {
|
||||
font-size: 11px;
|
||||
padding: 4px 4px;
|
||||
}
|
||||
|
||||
.workspace {
|
||||
padding: 2px 6px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.workspace {
|
||||
padding: 2px 6px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.module {
|
||||
padding: 2px 6px;
|
||||
}
|
||||
.module {
|
||||
padding: 2px 6px;
|
||||
}
|
||||
|
||||
.hide-sm {
|
||||
display: none;
|
||||
}
|
||||
.hide-sm {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -6,55 +6,55 @@ import { useRoute } from "vue-router";
|
||||
const route = useRoute();
|
||||
|
||||
const parentPath = computed(() => {
|
||||
const segments = route.path.split("/").filter(Boolean);
|
||||
if (segments.length == 1) {
|
||||
return "/";
|
||||
} else {
|
||||
segments.pop();
|
||||
return segments.length ? "/" + segments.join("/") : null;
|
||||
}
|
||||
const segments = route.path.split("/").filter(Boolean);
|
||||
if (segments.length == 1) {
|
||||
return "/";
|
||||
} else {
|
||||
segments.pop();
|
||||
return segments.length ? "/" + segments.join("/") : null;
|
||||
}
|
||||
});
|
||||
|
||||
const faces = [
|
||||
"^_^",
|
||||
"¯\\_(ツ)_/¯",
|
||||
"(◕‿◕✿)",
|
||||
"ಠ_ಠ",
|
||||
"ʘ‿ʘ",
|
||||
"^̮^",
|
||||
">_>",
|
||||
"¬_¬",
|
||||
"˙ ͜ʟ˙",
|
||||
"( ͡° ͜ʖ ͡°)",
|
||||
"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
|
||||
"(ง'̀-'́)ง",
|
||||
"\ (•◡•) /",
|
||||
"( ͡ᵔ ͜ʖ ͡ᵔ )",
|
||||
"ᕙ(⇀‸↼‶)ᕗ",
|
||||
"⚆ _ ⚆",
|
||||
"(。◕‿◕。)",
|
||||
"(╯°□°)╯︵ ʞooqǝɔɐɟ",
|
||||
"̿ ̿ ̿'̿'\̵͇̿̿\з=(•_•)=ε/̵͇̿̿/'̿'̿ ̿",
|
||||
"(☞゚ヮ゚)☞ ☜(゚ヮ゚☜)",
|
||||
"^_^",
|
||||
"¯\\_(ツ)_/¯",
|
||||
"(◕‿◕✿)",
|
||||
"ಠ_ಠ",
|
||||
"ʘ‿ʘ",
|
||||
"^̮^",
|
||||
">_>",
|
||||
"¬_¬",
|
||||
"˙ ͜ʟ˙",
|
||||
"( ͡° ͜ʖ ͡°)",
|
||||
"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
|
||||
"(ง'̀-'́)ง",
|
||||
"\ (•◡•) /",
|
||||
"( ͡ᵔ ͜ʖ ͡ᵔ )",
|
||||
"ᕙ(⇀‸↼‶)ᕗ",
|
||||
"⚆ _ ⚆",
|
||||
"(。◕‿◕。)",
|
||||
"(╯°□°)╯︵ ʞooqǝɔɐɟ",
|
||||
"̿ ̿ ̿'̿'\̵͇̿̿\з=(•_•)=ε/̵͇̿̿/'̿'̿ ̿",
|
||||
"(☞゚ヮ゚)☞ ☜(゚ヮ゚☜)",
|
||||
];
|
||||
const faces_string = faces.join(" ");
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav class="flex flex-row w-full h-fit border border-primary bg-bg_primary">
|
||||
<RouterLink class="bdr-2 bg-bg_primary" v-if="parentPath" :to="parentPath">
|
||||
<span>UP</span>
|
||||
</RouterLink>
|
||||
<Headline class="border flex-1 max-w-full">
|
||||
<code class="whitespace-pre">{{ faces_string }}</code>
|
||||
</Headline>
|
||||
</nav>
|
||||
<nav class="flex flex-row w-full h-fit border border-primary bg-bg_primary">
|
||||
<RouterLink class="bdr-2 bg-bg_primary" v-if="parentPath" :to="parentPath">
|
||||
<span>UP</span>
|
||||
</RouterLink>
|
||||
<Headline class="border flex-1 max-w-full">
|
||||
<code class="whitespace-pre">{{ faces_string }}</code>
|
||||
</Headline>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.left {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,57 +1,57 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
<img src="/img/borders/utena.png" class="flower tl antirotate" />
|
||||
<img src="/img/borders/utena.png" class="flower tr rotate" />
|
||||
<img src="/img/borders/utena.png" class="flower bl rotate" />
|
||||
<img src="/img/borders/utena.png" class="flower br antirotate" />
|
||||
<slot />
|
||||
</div>
|
||||
<div class="container">
|
||||
<img src="/img/borders/utena.png" class="flower tl antirotate" />
|
||||
<img src="/img/borders/utena.png" class="flower tr rotate" />
|
||||
<img src="/img/borders/utena.png" class="flower bl rotate" />
|
||||
<img src="/img/borders/utena.png" class="flower br antirotate" />
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.container {
|
||||
position: relative;
|
||||
margin: 100px;
|
||||
position: relative;
|
||||
margin: 100px;
|
||||
}
|
||||
|
||||
.flower {
|
||||
position: absolute;
|
||||
width: 150px;
|
||||
position: absolute;
|
||||
width: 150px;
|
||||
}
|
||||
.tl {
|
||||
top: -80px;
|
||||
left: -80px;
|
||||
--start: 0deg;
|
||||
top: -80px;
|
||||
left: -80px;
|
||||
--start: 0deg;
|
||||
}
|
||||
.tr {
|
||||
top: -80px;
|
||||
right: -80px;
|
||||
--start: 90deg;
|
||||
top: -80px;
|
||||
right: -80px;
|
||||
--start: 90deg;
|
||||
}
|
||||
.bl {
|
||||
bottom: -80px;
|
||||
left: -80px;
|
||||
--start: 180deg;
|
||||
bottom: -80px;
|
||||
left: -80px;
|
||||
--start: 180deg;
|
||||
}
|
||||
.br {
|
||||
bottom: -80px;
|
||||
right: -80px;
|
||||
--start: 270deg;
|
||||
bottom: -80px;
|
||||
right: -80px;
|
||||
--start: 270deg;
|
||||
}
|
||||
.rotate {
|
||||
animation: spin 3s linear infinite;
|
||||
animation: spin 3s linear infinite;
|
||||
}
|
||||
|
||||
.antirotate {
|
||||
animation: spin 3s linear infinite reverse;
|
||||
animation: spin 3s linear infinite reverse;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from {
|
||||
transform: rotate(var(--start));
|
||||
}
|
||||
to {
|
||||
transform: rotate(calc(var(--start) + 360deg));
|
||||
}
|
||||
from {
|
||||
transform: rotate(var(--start));
|
||||
}
|
||||
to {
|
||||
transform: rotate(calc(var(--start) + 360deg));
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -6,11 +6,11 @@ const container = ref(null);
|
||||
|
||||
// List of (offset, width)
|
||||
function generateOffsets(width = 100, step = 10, n = 20) {
|
||||
return Array.from({ length: n }, (_, i) => ({
|
||||
width,
|
||||
offset: step * i,
|
||||
color: getRandomColor(),
|
||||
}));
|
||||
return Array.from({ length: n }, (_, i) => ({
|
||||
width,
|
||||
offset: step * i,
|
||||
color: getRandomColor(),
|
||||
}));
|
||||
}
|
||||
const offsets = ref(generateOffsets((150, 15, 10)));
|
||||
let rafId;
|
||||
@@ -18,71 +18,71 @@ let rafId;
|
||||
const speed = 0.5; // pixels per frame
|
||||
|
||||
function animate() {
|
||||
const ctnr = container.value;
|
||||
for (const item of offsets.value) {
|
||||
const width = Math.max(ctnr.offsetWidth, item.width);
|
||||
const ctnr = container.value;
|
||||
for (const item of offsets.value) {
|
||||
const width = Math.max(ctnr.offsetWidth, item.width);
|
||||
|
||||
console.log(ctnr.offsetWidth);
|
||||
console.log(ctnr.offsetWidth);
|
||||
|
||||
item.offset -= speed;
|
||||
if (item.offset <= -width) {
|
||||
item.color = getRandomColor();
|
||||
item.offset = 0;
|
||||
}
|
||||
item.offset -= speed;
|
||||
if (item.offset <= -width) {
|
||||
item.color = getRandomColor();
|
||||
item.offset = 0;
|
||||
}
|
||||
rafId = requestAnimationFrame(animate);
|
||||
}
|
||||
rafId = requestAnimationFrame(animate);
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
rafId = requestAnimationFrame(animate);
|
||||
rafId = requestAnimationFrame(animate);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
cancelAnimationFrame(rafId);
|
||||
cancelAnimationFrame(rafId);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="bg-primary container" ref="container">
|
||||
<div :key="index" v-for="(item, index) in offsets">
|
||||
<div
|
||||
:style="{
|
||||
width: item.width + 'px',
|
||||
translate: item.offset + 'px',
|
||||
backgroundColor: item.color,
|
||||
}"
|
||||
class="item item1"
|
||||
/>
|
||||
<div
|
||||
:style="{
|
||||
width: item.width + 'px',
|
||||
right: -item.width + 'px',
|
||||
translate: item.offset + 'px',
|
||||
backgroundColor: item.color,
|
||||
}"
|
||||
class="item item2"
|
||||
/>
|
||||
</div>
|
||||
<div class="bg-primary container" ref="container">
|
||||
<div :key="index" v-for="(item, index) in offsets">
|
||||
<div
|
||||
:style="{
|
||||
width: item.width + 'px',
|
||||
translate: item.offset + 'px',
|
||||
backgroundColor: item.color,
|
||||
}"
|
||||
class="item item1"
|
||||
/>
|
||||
<div
|
||||
:style="{
|
||||
width: item.width + 'px',
|
||||
right: -item.width + 'px',
|
||||
translate: item.offset + 'px',
|
||||
backgroundColor: item.color,
|
||||
}"
|
||||
class="item item2"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.container {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
will-change: transform;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
will-change: transform;
|
||||
}
|
||||
.item {
|
||||
opacity: 40%;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
opacity: 40%;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
}
|
||||
.item1 {
|
||||
left: 0px;
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
top: 0px;
|
||||
}
|
||||
.item2 {
|
||||
top: 0px;
|
||||
top: 0px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<script setup></script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
class="text-primary bg-link text-center border cursor-pointer transition-colors duration-150 ease-in-out hover:bg-bg_primary active:scale-95"
|
||||
>
|
||||
<slot />
|
||||
</button>
|
||||
<button
|
||||
class="text-primary bg-link text-center border cursor-pointer transition-colors duration-150 ease-in-out hover:bg-bg_primary active:scale-95"
|
||||
>
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
|
||||
@@ -2,30 +2,30 @@
|
||||
import { ref } from "vue";
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(["update:modelValue"]);
|
||||
|
||||
function toggle() {
|
||||
emit("update:modelValue", !props.modelValue);
|
||||
emit("update:modelValue", !props.modelValue);
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<button
|
||||
@click="toggle"
|
||||
class="box-content border-2 border-primary w-20 h-fit rounded-full cursor-pointer"
|
||||
:class="[props.modelValue ? 'bg-bg_secondary' : 'bg-bg_primary']"
|
||||
<button
|
||||
@click="toggle"
|
||||
class="box-content border-2 border-primary w-10 h-fit rounded-full cursor-pointer"
|
||||
:class="[props.modelValue ? 'bg-bg_secondary' : 'bg-bg_primary']"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 40 40"
|
||||
class="w-5 h-5 transition-all duration-300 ease-in-out"
|
||||
:class="[props.modelValue ? 'ml-5' : 'ml-0']"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 40 40"
|
||||
class="w-10 h-10 transition-all duration-300 ease-in-out"
|
||||
:class="[props.modelValue ? 'ml-10' : 'ml-0']"
|
||||
>
|
||||
<circle class="fill-primary" cx="20" cy="20" r="20" />
|
||||
</svg>
|
||||
</button>
|
||||
<circle class="fill-primary" cx="20" cy="20" r="20" />
|
||||
</svg>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="w-full border-b border-primary pb-2 mb-4">
|
||||
<h1 class="p-0 m-0">
|
||||
<slot />
|
||||
</h1>
|
||||
</div>
|
||||
<div class="w-full border-b border-primary pb-0.5">
|
||||
<h1 class="p-0 m-0">
|
||||
<slot />
|
||||
</h1>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -12,74 +12,74 @@ let rafId;
|
||||
const speed = 0.5; // pixels per frame
|
||||
|
||||
function measureWidth() {
|
||||
const ctnr = container.value;
|
||||
const it1 = item1.value;
|
||||
if (ctnr && it1) {
|
||||
cachedWidth = Math.max(ctnr.offsetWidth, it1.scrollWidth);
|
||||
}
|
||||
const ctnr = container.value;
|
||||
const it1 = item1.value;
|
||||
if (ctnr && it1) {
|
||||
cachedWidth = Math.max(ctnr.offsetWidth, it1.scrollWidth);
|
||||
}
|
||||
}
|
||||
|
||||
function animate() {
|
||||
const ctnr = container.value;
|
||||
if (!ctnr || cachedWidth === 0) {
|
||||
rafId = requestAnimationFrame(animate);
|
||||
return;
|
||||
}
|
||||
|
||||
offset -= speed;
|
||||
|
||||
if (offset <= -cachedWidth) {
|
||||
offset += cachedWidth;
|
||||
}
|
||||
|
||||
ctnr.style.transform = `translateX(${offset}px)`;
|
||||
|
||||
const ctnr = container.value;
|
||||
if (!ctnr || cachedWidth === 0) {
|
||||
rafId = requestAnimationFrame(animate);
|
||||
return;
|
||||
}
|
||||
|
||||
offset -= speed;
|
||||
|
||||
if (offset <= -cachedWidth) {
|
||||
offset += cachedWidth;
|
||||
}
|
||||
|
||||
ctnr.style.transform = `translateX(${offset}px)`;
|
||||
|
||||
rafId = requestAnimationFrame(animate);
|
||||
}
|
||||
|
||||
let resizeObserver;
|
||||
|
||||
onMounted(() => {
|
||||
measureWidth();
|
||||
rafId = requestAnimationFrame(animate);
|
||||
measureWidth();
|
||||
rafId = requestAnimationFrame(animate);
|
||||
|
||||
resizeObserver = new ResizeObserver(measureWidth);
|
||||
resizeObserver.observe(container.value);
|
||||
resizeObserver = new ResizeObserver(measureWidth);
|
||||
resizeObserver.observe(container.value);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
cancelAnimationFrame(rafId);
|
||||
resizeObserver?.disconnect();
|
||||
cancelAnimationFrame(rafId);
|
||||
resizeObserver?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="root">
|
||||
<div class="container" ref="container">
|
||||
<div ref="item1">
|
||||
<slot />
|
||||
</div>
|
||||
<div>
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
<div class="root">
|
||||
<div class="container" ref="container">
|
||||
<div ref="item1">
|
||||
<slot />
|
||||
</div>
|
||||
<div>
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.root {
|
||||
overflow: hidden;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.container {
|
||||
width: fit-content;
|
||||
height: fit-content;
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: max-content;
|
||||
/* Each column fits its content */
|
||||
overflow-x: visible;
|
||||
will-change: transform;
|
||||
gap: 10em;
|
||||
width: fit-content;
|
||||
height: fit-content;
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: max-content;
|
||||
/* Each column fits its content */
|
||||
overflow-x: visible;
|
||||
will-change: transform;
|
||||
gap: 10em;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -2,38 +2,44 @@
|
||||
import { computed } from "vue";
|
||||
|
||||
const props = defineProps({
|
||||
href: { type: String, default: "" },
|
||||
to: { type: String, default: "" },
|
||||
target: { type: String, default: undefined },
|
||||
rel: { type: String, default: undefined },
|
||||
href: { type: String, default: "" },
|
||||
to: { type: String, default: "" },
|
||||
target: { type: String, default: undefined },
|
||||
rel: { type: String, default: undefined },
|
||||
});
|
||||
|
||||
const computedRel = computed(() => {
|
||||
if (props.rel !== undefined) return props.rel;
|
||||
if (props.target === "_blank") return "noopener noreferrer";
|
||||
return undefined;
|
||||
if (props.rel !== undefined) return props.rel;
|
||||
if (props.target === "_blank") return "noopener noreferrer";
|
||||
return undefined;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RouterLink v-if="to" :to="to" class="inline-link">
|
||||
<slot />
|
||||
</RouterLink>
|
||||
<a v-else :href="href" :target="target" :rel="computedRel" class="inline-link">
|
||||
<slot />
|
||||
</a>
|
||||
<RouterLink v-if="to" :to="to" class="inline-link">
|
||||
<slot />
|
||||
</RouterLink>
|
||||
<a
|
||||
v-else
|
||||
:href="href"
|
||||
:target="target"
|
||||
:rel="computedRel"
|
||||
class="inline-link"
|
||||
>
|
||||
<slot />
|
||||
</a>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.inline-link {
|
||||
color: var(--primary);
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
color: var(--primary);
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
}
|
||||
|
||||
.inline-link:hover {
|
||||
color: var(--tertiary);
|
||||
color: var(--tertiary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -2,37 +2,43 @@
|
||||
import { computed } from "vue";
|
||||
|
||||
const props = defineProps({
|
||||
href: { type: String, default: "" },
|
||||
to: { type: String, default: "" },
|
||||
target: { type: String, default: undefined },
|
||||
rel: { type: String, default: undefined },
|
||||
bare: { type: Boolean, default: false },
|
||||
href: { type: String, default: "" },
|
||||
to: { type: String, default: "" },
|
||||
target: { type: String, default: undefined },
|
||||
rel: { type: String, default: undefined },
|
||||
bare: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const computedRel = computed(() => {
|
||||
if (props.rel !== undefined) return props.rel;
|
||||
if (props.target === "_blank") return "noopener noreferrer";
|
||||
return undefined;
|
||||
if (props.rel !== undefined) return props.rel;
|
||||
if (props.target === "_blank") return "noopener noreferrer";
|
||||
return undefined;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RouterLink v-if="to" :to="to" :class="{ link: !bare }">
|
||||
<slot />
|
||||
</RouterLink>
|
||||
<a v-else :href="href" :target="target" :rel="computedRel" :class="{ link: !bare }">
|
||||
<slot />
|
||||
</a>
|
||||
<RouterLink v-if="to" :to="to" :class="{ link: !bare }">
|
||||
<slot />
|
||||
</RouterLink>
|
||||
<a
|
||||
v-else
|
||||
:href="href"
|
||||
:target="target"
|
||||
:rel="computedRel"
|
||||
:class="{ link: !bare }"
|
||||
>
|
||||
<slot />
|
||||
</a>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.link {
|
||||
color: var(--primary);
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
color: var(--primary);
|
||||
text-decoration: none;
|
||||
transition: color 0.15s ease;
|
||||
}
|
||||
|
||||
.link:hover {
|
||||
color: var(--tertiary);
|
||||
color: var(--tertiary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<p class="p-1">
|
||||
<slot />
|
||||
</p>
|
||||
<p class="p-1">
|
||||
<slot />
|
||||
</p>
|
||||
</template>
|
||||
|
||||
@@ -3,35 +3,36 @@ import { ref } from "vue";
|
||||
import ToggleButton from "@/components/input/ToggleButton.vue";
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
});
|
||||
|
||||
const emit = defineEmits(["update:modelValue"]);
|
||||
const toggleButtonRef = ref(null);
|
||||
|
||||
const updateValue = (newValue) => {
|
||||
emit("update:modelValue", newValue);
|
||||
emit("update:modelValue", newValue);
|
||||
};
|
||||
const handleClick = () => {
|
||||
toggleButtonRef.value?.$el?.click();
|
||||
toggleButtonRef.value?.$el?.click();
|
||||
};
|
||||
</script>
|
||||
<template>
|
||||
<div
|
||||
class="w-full border-b border-primary cursor-pointer"
|
||||
@click="handleClick"
|
||||
>
|
||||
<h1 class="pl-2 m-0">
|
||||
<slot />
|
||||
</h1>
|
||||
<ToggleButton
|
||||
class="pointer-events-none"
|
||||
:model-value="props.modelValue"
|
||||
@update:model-value="updateValue"
|
||||
ref="toggleButtonRef"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="w-full border-b border-primary cursor-pointer"
|
||||
@click="handleClick"
|
||||
>
|
||||
<h3 class="pl-2 m-0">
|
||||
<slot />
|
||||
</h3>
|
||||
<ToggleButton
|
||||
class="pointer-events-none"
|
||||
:model-value="props.modelValue"
|
||||
@update:model-value="updateValue"
|
||||
@click.stop
|
||||
ref="toggleButtonRef"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
<template>
|
||||
<div ref="container" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave" class="overflow-y-auto">
|
||||
<slot />
|
||||
</div>
|
||||
<div
|
||||
ref="container"
|
||||
@mouseenter="onMouseEnter"
|
||||
@mouseleave="onMouseLeave"
|
||||
class="overflow-y-auto"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
@@ -20,89 +25,89 @@ let pauseTimeoutId = null;
|
||||
let cachedScrollHeight = 0;
|
||||
|
||||
function measureScrollHeight() {
|
||||
const el = container.value;
|
||||
if (el) cachedScrollHeight = el.scrollHeight;
|
||||
const el = container.value;
|
||||
if (el) cachedScrollHeight = el.scrollHeight;
|
||||
}
|
||||
|
||||
function stopLoop() {
|
||||
if (rafId !== null) {
|
||||
cancelAnimationFrame(rafId);
|
||||
rafId = null;
|
||||
}
|
||||
if (pauseTimeoutId !== null) {
|
||||
clearTimeout(pauseTimeoutId);
|
||||
pauseTimeoutId = null;
|
||||
}
|
||||
if (rafId !== null) {
|
||||
cancelAnimationFrame(rafId);
|
||||
rafId = null;
|
||||
}
|
||||
if (pauseTimeoutId !== null) {
|
||||
clearTimeout(pauseTimeoutId);
|
||||
pauseTimeoutId = null;
|
||||
}
|
||||
}
|
||||
|
||||
function startLoop() {
|
||||
stopLoop();
|
||||
rafId = requestAnimationFrame(tick);
|
||||
stopLoop();
|
||||
rafId = requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
function onMouseEnter() {
|
||||
hovered = true;
|
||||
stopLoop();
|
||||
hovered = true;
|
||||
stopLoop();
|
||||
}
|
||||
|
||||
function onMouseLeave() {
|
||||
hovered = false;
|
||||
const el = container.value;
|
||||
if (el && cachedScrollHeight > 0) {
|
||||
pos = el.scrollTop / cachedScrollHeight;
|
||||
}
|
||||
startLoop();
|
||||
hovered = false;
|
||||
const el = container.value;
|
||||
if (el && cachedScrollHeight > 0) {
|
||||
pos = el.scrollTop / cachedScrollHeight;
|
||||
}
|
||||
startLoop();
|
||||
}
|
||||
|
||||
function schedulePause(callback) {
|
||||
stopLoop();
|
||||
pauseTimeoutId = setTimeout(callback, PAUSE);
|
||||
stopLoop();
|
||||
pauseTimeoutId = setTimeout(callback, PAUSE);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
rafId = null;
|
||||
const el = container.value;
|
||||
if (hovered) return;
|
||||
|
||||
if (!el || cachedScrollHeight === 0) {
|
||||
rafId = requestAnimationFrame(tick);
|
||||
return;
|
||||
}
|
||||
|
||||
const reachedBottom = pos >= 1;
|
||||
const reachedTop = pos <= 0;
|
||||
|
||||
if (reachedBottom) {
|
||||
pos = 0.999;
|
||||
direction = -1;
|
||||
schedulePause(startLoop);
|
||||
return;
|
||||
} else if (reachedTop && direction === -1) {
|
||||
pos = 0.001;
|
||||
direction = 1;
|
||||
schedulePause(startLoop);
|
||||
return;
|
||||
}
|
||||
|
||||
pos += direction * SPEED;
|
||||
|
||||
el.scrollTop = pos * cachedScrollHeight;
|
||||
rafId = null;
|
||||
const el = container.value;
|
||||
if (hovered) return;
|
||||
|
||||
if (!el || cachedScrollHeight === 0) {
|
||||
rafId = requestAnimationFrame(tick);
|
||||
return;
|
||||
}
|
||||
|
||||
const reachedBottom = pos >= 1;
|
||||
const reachedTop = pos <= 0;
|
||||
|
||||
if (reachedBottom) {
|
||||
pos = 0.999;
|
||||
direction = -1;
|
||||
schedulePause(startLoop);
|
||||
return;
|
||||
} else if (reachedTop && direction === -1) {
|
||||
pos = 0.001;
|
||||
direction = 1;
|
||||
schedulePause(startLoop);
|
||||
return;
|
||||
}
|
||||
|
||||
pos += direction * SPEED;
|
||||
|
||||
el.scrollTop = pos * cachedScrollHeight;
|
||||
|
||||
rafId = requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
let resizeObserver;
|
||||
|
||||
onMounted(() => {
|
||||
measureScrollHeight();
|
||||
schedulePause(startLoop);
|
||||
measureScrollHeight();
|
||||
schedulePause(startLoop);
|
||||
|
||||
resizeObserver = new ResizeObserver(measureScrollHeight);
|
||||
resizeObserver.observe(container.value);
|
||||
resizeObserver = new ResizeObserver(measureScrollHeight);
|
||||
resizeObserver.observe(container.value);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopLoop();
|
||||
resizeObserver?.disconnect();
|
||||
stopLoop();
|
||||
resizeObserver?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -19,210 +19,205 @@ const SCROLL_THRESHOLD = 100;
|
||||
let resizeObserver = null;
|
||||
|
||||
function scrollToBottom() {
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.scrollTop =
|
||||
messagesContainer.value.scrollHeight;
|
||||
}
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
function scrollToBottomIfNear() {
|
||||
if (isNearBottom.value) {
|
||||
scrollToBottom();
|
||||
}
|
||||
if (isNearBottom.value) {
|
||||
scrollToBottom();
|
||||
}
|
||||
}
|
||||
|
||||
function onScroll() {
|
||||
if (!messagesContainer.value) return;
|
||||
const { scrollHeight, scrollTop, clientHeight } = messagesContainer.value;
|
||||
isNearBottom.value =
|
||||
scrollHeight - scrollTop - clientHeight < SCROLL_THRESHOLD;
|
||||
if (!messagesContainer.value) return;
|
||||
const { scrollHeight, scrollTop, clientHeight } = messagesContainer.value;
|
||||
isNearBottom.value =
|
||||
scrollHeight - scrollTop - clientHeight < SCROLL_THRESHOLD;
|
||||
}
|
||||
|
||||
function goToBottom() {
|
||||
isNearBottom.value = true;
|
||||
scrollToBottom();
|
||||
isNearBottom.value = true;
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
watch(
|
||||
() => messages.value.length,
|
||||
() => {
|
||||
nextTick(scrollToBottomIfNear);
|
||||
},
|
||||
() => messages.value.length,
|
||||
() => {
|
||||
nextTick(scrollToBottomIfNear);
|
||||
},
|
||||
);
|
||||
|
||||
function sendMessage() {
|
||||
const text = messageInput.value.trim();
|
||||
if (!text) return;
|
||||
isNearBottom.value = true;
|
||||
messagesStore.sendMessage(text);
|
||||
messageInput.value = "";
|
||||
const text = messageInput.value.trim();
|
||||
if (!text) return;
|
||||
isNearBottom.value = true;
|
||||
messagesStore.sendMessage(text);
|
||||
messageInput.value = "";
|
||||
}
|
||||
|
||||
async function onFileSelected(e) {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
isNearBottom.value = true;
|
||||
await messagesStore.uploadAndSendFile(file);
|
||||
fileInput.value.value = "";
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
isNearBottom.value = true;
|
||||
await messagesStore.uploadAndSendFile(file);
|
||||
fileInput.value.value = "";
|
||||
}
|
||||
|
||||
function isImageUrl(url) {
|
||||
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
|
||||
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
|
||||
}
|
||||
|
||||
function isVideoUrl(url) {
|
||||
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
||||
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
||||
}
|
||||
|
||||
function isSafeFileUrl(url) {
|
||||
return typeof url === "string" && url.startsWith("/uploads/");
|
||||
return typeof url === "string" && url.startsWith("/uploads/");
|
||||
}
|
||||
|
||||
const urlRegex = /(https?:\/\/[^\s<]+)/g;
|
||||
|
||||
function parseMessageParts(text) {
|
||||
const parts = [];
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = urlRegex.exec(text)) !== null) {
|
||||
if (match.index > lastIndex) {
|
||||
parts.push({
|
||||
type: "text",
|
||||
value: text.slice(lastIndex, match.index),
|
||||
});
|
||||
}
|
||||
parts.push({ type: "link", value: match[1] });
|
||||
lastIndex = urlRegex.lastIndex;
|
||||
const parts = [];
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
while ((match = urlRegex.exec(text)) !== null) {
|
||||
if (match.index > lastIndex) {
|
||||
parts.push({
|
||||
type: "text",
|
||||
value: text.slice(lastIndex, match.index),
|
||||
});
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
parts.push({ type: "text", value: text.slice(lastIndex) });
|
||||
}
|
||||
return parts;
|
||||
parts.push({ type: "link", value: match[1] });
|
||||
lastIndex = urlRegex.lastIndex;
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
parts.push({ type: "text", value: text.slice(lastIndex) });
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
messagesStore.connect();
|
||||
messagesStore.connect();
|
||||
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.addEventListener("scroll", onScroll, {
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.addEventListener("scroll", onScroll, {
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (messagesInner.value) {
|
||||
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
|
||||
resizeObserver.observe(messagesInner.value);
|
||||
}
|
||||
if (messagesInner.value) {
|
||||
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
|
||||
resizeObserver.observe(messagesInner.value);
|
||||
}
|
||||
|
||||
scrollToBottom();
|
||||
scrollToBottom();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
messagesStore.disconnect();
|
||||
messagesStore.disconnect();
|
||||
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.removeEventListener("scroll", onScroll);
|
||||
}
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.removeEventListener("scroll", onScroll);
|
||||
}
|
||||
|
||||
if (resizeObserver) {
|
||||
resizeObserver.disconnect();
|
||||
resizeObserver = null;
|
||||
}
|
||||
if (resizeObserver) {
|
||||
resizeObserver.disconnect();
|
||||
resizeObserver = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="chat-root flex-col flex min-h-0">
|
||||
<Header>Chat</Header>
|
||||
<div
|
||||
ref="messagesContainer"
|
||||
class="flex flex-col flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-2 min-w-0"
|
||||
<div class="chat-root flex-col flex min-h-0">
|
||||
<Header>Chat</Header>
|
||||
<div
|
||||
ref="messagesContainer"
|
||||
class="flex flex-col flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-2 min-w-0"
|
||||
>
|
||||
<div ref="messagesInner">
|
||||
<p
|
||||
v-for="message in messages"
|
||||
:key="message.id"
|
||||
class="break-words min-w-0 w-full"
|
||||
>
|
||||
<div ref="messagesInner">
|
||||
<p
|
||||
v-for="message in messages"
|
||||
:key="message.id"
|
||||
class="break-words min-w-0 w-full"
|
||||
>
|
||||
<span class="text-tertiary">{{ message.authorId }}:</span>
|
||||
<template
|
||||
v-for="(part, i) in parseMessageParts(
|
||||
message.text || '',
|
||||
)"
|
||||
:key="i"
|
||||
>
|
||||
<Link
|
||||
v-if="part.type === 'link'"
|
||||
bare
|
||||
:href="part.value"
|
||||
target="_blank"
|
||||
class="text-primary underline break-all"
|
||||
>{{ part.value }}</Link
|
||||
>
|
||||
<span v-else>{{ part.value }}</span>
|
||||
</template>
|
||||
<template
|
||||
v-if="message.fileUrl && isSafeFileUrl(message.fileUrl)"
|
||||
>
|
||||
<img
|
||||
v-if="isImageUrl(message.fileUrl)"
|
||||
:src="message.fileUrl"
|
||||
alt="Uploaded image"
|
||||
loading="lazy"
|
||||
class="w-full max-w-full rounded block"
|
||||
/>
|
||||
<video
|
||||
v-else-if="isVideoUrl(message.fileUrl)"
|
||||
:src="message.fileUrl"
|
||||
controls
|
||||
preload="none"
|
||||
class="w-full max-w-full max-h-48 rounded block"
|
||||
/>
|
||||
<Link
|
||||
v-else
|
||||
bare
|
||||
:href="message.fileUrl"
|
||||
target="_blank"
|
||||
class="underline break-all"
|
||||
>{{ message.fileUrl.split("/").pop() }}</Link
|
||||
>
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<input
|
||||
v-model="messageInput"
|
||||
@keyup.enter="sendMessage"
|
||||
aria-label="Chat message"
|
||||
<span class="text-tertiary">{{ message.authorId }}:</span>
|
||||
<template
|
||||
v-for="(part, i) in parseMessageParts(message.text || '')"
|
||||
:key="i"
|
||||
>
|
||||
<Link
|
||||
v-if="part.type === 'link'"
|
||||
bare
|
||||
:href="part.value"
|
||||
target="_blank"
|
||||
class="text-primary underline break-all"
|
||||
>{{ part.value }}</Link
|
||||
>
|
||||
<span v-else>{{ part.value }}</span>
|
||||
</template>
|
||||
<template v-if="message.fileUrl && isSafeFileUrl(message.fileUrl)">
|
||||
<img
|
||||
v-if="isImageUrl(message.fileUrl)"
|
||||
:src="message.fileUrl"
|
||||
alt="Uploaded image"
|
||||
loading="lazy"
|
||||
class="w-full max-w-full rounded block"
|
||||
/>
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
class="hidden"
|
||||
@change="onFileSelected"
|
||||
<video
|
||||
v-else-if="isVideoUrl(message.fileUrl)"
|
||||
:src="message.fileUrl"
|
||||
controls
|
||||
preload="none"
|
||||
class="w-full max-w-full max-h-48 rounded block"
|
||||
/>
|
||||
<div class="flex gap-2">
|
||||
<Button class="flex-1" @click="sendMessage">Send</Button>
|
||||
<Button
|
||||
v-if="authStore.user.admin"
|
||||
class="flex-1"
|
||||
@click="fileInput.click()"
|
||||
>Attach</Button
|
||||
>
|
||||
<Button v-if="!isNearBottom" class="flex-1" @click="goToBottom"
|
||||
>Bottom</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<Link
|
||||
v-else
|
||||
bare
|
||||
:href="message.fileUrl"
|
||||
target="_blank"
|
||||
class="underline break-all"
|
||||
>{{ message.fileUrl.split("/").pop() }}</Link
|
||||
>
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<input
|
||||
v-model="messageInput"
|
||||
@keyup.enter="sendMessage"
|
||||
aria-label="Chat message"
|
||||
/>
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
class="hidden"
|
||||
@change="onFileSelected"
|
||||
/>
|
||||
<div class="flex gap-2">
|
||||
<Button class="flex-1" @click="sendMessage">Send</Button>
|
||||
<Button
|
||||
v-if="authStore.user.admin"
|
||||
class="flex-1"
|
||||
@click="fileInput.click()"
|
||||
>Attach</Button
|
||||
>
|
||||
<Button v-if="!isNearBottom" class="flex-1" @click="goToBottom"
|
||||
>Bottom</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
@media (max-width: 850px) {
|
||||
.chat-root {
|
||||
max-height: none;
|
||||
height: 100%;
|
||||
}
|
||||
.chat-root {
|
||||
max-height: none;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -9,37 +9,42 @@ const { gitFeed: feed, loaded } = storeToRefs(homeData);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col text-center min-h-0 h-full overflow-x-hidden">
|
||||
<Header class="text-left">Commits</Header>
|
||||
<div class="flex flex-col text-center min-h-0 h-full overflow-x-hidden">
|
||||
<Header class="text-left">Commits</Header>
|
||||
|
||||
<div v-if="!loaded" class="flex-1 overflow-y-auto">
|
||||
<p>Loading latest activity...</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="feed"
|
||||
class="flex-1 flex flex-col items-center overflow-y-auto overflow-x-hidden"
|
||||
>
|
||||
<h3>Last git activity</h3>
|
||||
<img :src="feed.avatarUrl" alt="User avatar" class="avatar" loading="lazy" />
|
||||
<Link :href="feed.repoUrl">
|
||||
<h3>repo: {{ feed.repoName }}</h3>
|
||||
</Link>
|
||||
<p>Action: {{ feed.opType }}</p>
|
||||
<p>Message: {{ feed.commitMessage }}</p>
|
||||
<small> {{ new Date(feed.createdAt).toLocaleString() }}</small>
|
||||
</div>
|
||||
|
||||
<div v-else class="flex-1 overflow-y-auto">
|
||||
<p>No activity found.</p>
|
||||
</div>
|
||||
<div v-if="!loaded" class="flex-1 overflow-y-auto">
|
||||
<p>Loading latest activity...</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="feed"
|
||||
class="flex-1 flex flex-col items-center overflow-y-auto overflow-x-hidden"
|
||||
>
|
||||
<h3>Last git activity</h3>
|
||||
<img
|
||||
:src="feed.avatarUrl"
|
||||
alt="User avatar"
|
||||
class="avatar"
|
||||
loading="lazy"
|
||||
/>
|
||||
<Link :href="feed.repoUrl">
|
||||
<h3>repo: {{ feed.repoName }}</h3>
|
||||
</Link>
|
||||
<p>Action: {{ feed.opType }}</p>
|
||||
<p>Message: {{ feed.commitMessage }}</p>
|
||||
<small> {{ new Date(feed.createdAt).toLocaleString() }}</small>
|
||||
</div>
|
||||
|
||||
<div v-else class="flex-1 overflow-y-auto">
|
||||
<p>No activity found.</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.avatar {
|
||||
max-width: 200px;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-width: 200px;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -4,70 +4,66 @@ import Link from "@/components/text/Link.vue";
|
||||
import ToggleHeader from "@/components/text/ToggleHeader.vue";
|
||||
|
||||
const props = defineProps({
|
||||
items: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
variant: {
|
||||
type: String,
|
||||
default: "list",
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
items: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
variant: {
|
||||
type: String,
|
||||
default: "list",
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
});
|
||||
|
||||
const show = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="title" class="h-fit w-full">
|
||||
<ToggleHeader v-model="show" class="justify-between flex">
|
||||
{{ title }}
|
||||
</ToggleHeader>
|
||||
<template v-if="show">
|
||||
<Link
|
||||
v-if="variant === 'list'"
|
||||
v-for="(item, i) in items"
|
||||
:key="i"
|
||||
:href="item.link"
|
||||
>
|
||||
<p class="bdr-2 bg-bg_tertiary">{{ item.name }}</p>
|
||||
</Link>
|
||||
<table class="w-full" v-else>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.id">
|
||||
<th>{{ item.type }}</th>
|
||||
<td v-if="item.link">
|
||||
<Link :href="item.link">{{ item.name }}</Link>
|
||||
</td>
|
||||
<td v-else>{{ item.name }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
</div>
|
||||
<template v-else>
|
||||
<template v-if="variant === 'list'">
|
||||
<Link
|
||||
v-for="(item, i) in items"
|
||||
:key="i"
|
||||
:href="item.link"
|
||||
>
|
||||
<p class="bdr-2 bg-bg_tertiary">{{ item.name }}</p>
|
||||
</Link>
|
||||
</template>
|
||||
<table class="w-full" v-else>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.id">
|
||||
<th>{{ item.type }}</th>
|
||||
<td v-if="item.link">
|
||||
<Link :href="item.link">{{ item.name }}</Link>
|
||||
</td>
|
||||
<td v-else>{{ item.name }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-if="title" class="h-fit w-full">
|
||||
<ToggleHeader v-model="show" class="justify-between flex items-center">
|
||||
{{ title }}
|
||||
</ToggleHeader>
|
||||
<template v-if="show">
|
||||
<Link
|
||||
v-if="variant === 'list'"
|
||||
v-for="(item, i) in items"
|
||||
:key="i"
|
||||
:href="item.link"
|
||||
>
|
||||
<p class="bdr-2 bg-bg_tertiary">{{ item.name }}</p>
|
||||
</Link>
|
||||
<table class="w-full" v-else>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.id">
|
||||
<th>{{ item.type }}</th>
|
||||
<td v-if="item.link">
|
||||
<Link :href="item.link">{{ item.name }}</Link>
|
||||
</td>
|
||||
<td v-else>{{ item.name }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
</div>
|
||||
<template v-else>
|
||||
<template v-if="variant === 'list'">
|
||||
<Link v-for="(item, i) in items" :key="i" :href="item.link">
|
||||
<p class="bdr-2 bg-bg_tertiary">{{ item.name }}</p>
|
||||
</Link>
|
||||
</template>
|
||||
<table class="w-full" v-else>
|
||||
<tbody>
|
||||
<tr v-for="item in items" :key="item.id">
|
||||
<th>{{ item.type }}</th>
|
||||
<td v-if="item.link">
|
||||
<Link :href="item.link">{{ item.name }}</Link>
|
||||
</td>
|
||||
<td v-else>{{ item.name }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -6,19 +6,19 @@ import DOMPurify from "dompurify";
|
||||
const mdIt = MarkdownIt().use(katex);
|
||||
|
||||
const props = defineProps({
|
||||
source: String,
|
||||
source: String,
|
||||
});
|
||||
|
||||
function renderMarkdown(source) {
|
||||
return DOMPurify.sanitize(mdIt.render(source));
|
||||
return DOMPurify.sanitize(mdIt.render(source));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-html="renderMarkdown(props.source)"
|
||||
class="flex flex-col items-center"
|
||||
></div>
|
||||
<div
|
||||
v-html="renderMarkdown(props.source)"
|
||||
class="flex flex-col items-center"
|
||||
></div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -1,93 +1,92 @@
|
||||
<script setup>
|
||||
import Button from "@/components/input/Button.vue";
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<audio/>
|
||||
<div class="musicPlayerGrid">
|
||||
<div class="album_cover">
|
||||
<img src="/img/Untitled.png" alt=""></img>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<div class="sliders">
|
||||
<div class="timeline"/>
|
||||
<div class="volume"/>
|
||||
</div>
|
||||
<div class="buttons">
|
||||
<div class="rewind"/>
|
||||
<div class="playPause"/>
|
||||
<div class="fastforward"/>
|
||||
</div>
|
||||
</div>
|
||||
<audio />
|
||||
<div class="musicPlayerGrid">
|
||||
<div class="album_cover">
|
||||
<img src="/img/Untitled.png" alt="" />
|
||||
</div>
|
||||
<div class="controls">
|
||||
<div class="sliders">
|
||||
<div class="timeline" />
|
||||
<div class="volume" />
|
||||
</div>
|
||||
<div class="buttons">
|
||||
<div class="rewind" />
|
||||
<div class="playPause" />
|
||||
<div class="fastforward" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.musicPlayerGrid {
|
||||
display: grid;
|
||||
grid-gap: 5px;
|
||||
grid-template-rows: repeat(4, 1fr);
|
||||
background-color: blue;
|
||||
align-items: stretch; /* rows (block axis) */
|
||||
justify-items: stretch; /* columns (inline axis) */
|
||||
padding: 5px;
|
||||
display: grid;
|
||||
grid-gap: 5px;
|
||||
grid-template-rows: repeat(4, 1fr);
|
||||
background-color: blue;
|
||||
align-items: stretch; /* rows (block axis) */
|
||||
justify-items: stretch; /* columns (inline axis) */
|
||||
padding: 5px;
|
||||
}
|
||||
img {
|
||||
width: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.album_cover {
|
||||
grid-row: 1 / span 3;
|
||||
background-color: grey;
|
||||
box-sizing: border-box;
|
||||
grid-row: 1 / span 3;
|
||||
background-color: grey;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.controls {
|
||||
width: 100%;
|
||||
grid-row: 4 / span 1;
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
grid-row: 4 / span 1;
|
||||
box-sizing: border-box;
|
||||
|
||||
display: grid;
|
||||
grid-template-rows: repeat(4, 1fr);
|
||||
grid-gap: 5px;
|
||||
display: grid;
|
||||
grid-template-rows: repeat(4, 1fr);
|
||||
grid-gap: 5px;
|
||||
}
|
||||
|
||||
.sliders {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
grid-gap: 5px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
grid-gap: 5px;
|
||||
}
|
||||
|
||||
.timeline {
|
||||
grid-column: 1;
|
||||
background-color: white;
|
||||
grid-column: 1;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
.volume {
|
||||
grid-column: 2;
|
||||
background-color: white;
|
||||
grid-column: 2;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
.buttons {
|
||||
background-color: black;
|
||||
grid-row: 2 / -1;
|
||||
background-color: black;
|
||||
grid-row: 2 / -1;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-gap: 5px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-gap: 5px;
|
||||
}
|
||||
|
||||
.rewind {
|
||||
grid-column: 1;
|
||||
background-color: grey;
|
||||
grid-column: 1;
|
||||
background-color: grey;
|
||||
}
|
||||
.fastforward {
|
||||
grid-column: 4;
|
||||
background-color: grey;
|
||||
grid-column: 4;
|
||||
background-color: grey;
|
||||
}
|
||||
.playPause {
|
||||
grid-column: 2/span 2;
|
||||
background-color: grey;
|
||||
grid-column: 2 / span 2;
|
||||
background-color: grey;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -2,42 +2,42 @@
|
||||
import { computed } from "vue";
|
||||
|
||||
const props = defineProps({
|
||||
objArr: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
objArr: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
});
|
||||
|
||||
const resolvedColumns = computed(() => {
|
||||
const keys = new Set();
|
||||
const keys = new Set();
|
||||
|
||||
for (const obj of props.objArr) {
|
||||
Object.keys(obj).forEach((key) => keys.add(key));
|
||||
}
|
||||
for (const obj of props.objArr) {
|
||||
Object.keys(obj).forEach((key) => keys.add(key));
|
||||
}
|
||||
|
||||
return Array.from(keys).map((key) => ({
|
||||
key,
|
||||
label: key,
|
||||
}));
|
||||
return Array.from(keys).map((key) => ({
|
||||
key,
|
||||
label: key,
|
||||
}));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-for="col in resolvedColumns" :key="col.key">
|
||||
{{ col.label }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-for="col in resolvedColumns" :key="col.key">
|
||||
{{ col.label }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in objArr" :key="rowIndex">
|
||||
<td v-for="col in resolvedColumns" :key="col.key">
|
||||
{{ row[col.key] ?? "" }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in objArr" :key="rowIndex">
|
||||
<td v-for="col in resolvedColumns" :key="col.key">
|
||||
{{ row[col.key] ?? "" }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</template>
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
<template>
|
||||
<div v-if="streamLive" class="overflow-auto">
|
||||
<Header>Radio</Header>
|
||||
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
||||
<audio controls :src="streamUrl" ref="audio"></audio>
|
||||
</div>
|
||||
<div v-else class="overflow-auto">
|
||||
<Header>Radio</Header>
|
||||
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
||||
<div class="m-1 text-center">
|
||||
<p>Radio is offline. Message for info!</p>
|
||||
<Button class="w-full" @click="checkStream()">Check Stream</Button>
|
||||
</div>
|
||||
<div v-if="streamLive" class="overflow-auto">
|
||||
<Header>Radio</Header>
|
||||
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
||||
<audio controls :src="streamUrl" ref="audio"></audio>
|
||||
</div>
|
||||
<div v-else class="overflow-auto">
|
||||
<Header>Radio</Header>
|
||||
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
||||
<div class="m-1 text-center">
|
||||
<p>Radio is offline. Message for info!</p>
|
||||
<Button class="w-full" @click="checkStream()">Check Stream</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
@@ -25,32 +25,32 @@ const streamLive = ref(false);
|
||||
const audio = useTemplateRef("audio");
|
||||
|
||||
async function checkStream() {
|
||||
try {
|
||||
await axios.head("/radio/stream");
|
||||
if (!streamLive.value) {
|
||||
streamLive.value = true;
|
||||
streamUrl.value = "/radio/stream";
|
||||
await nextTick();
|
||||
if (audio.value) {
|
||||
audio.value.load();
|
||||
audio.value.volume = 0.2;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
streamLive.value = false;
|
||||
try {
|
||||
await axios.head("/radio/stream");
|
||||
if (!streamLive.value) {
|
||||
streamLive.value = true;
|
||||
streamUrl.value = "/radio/stream";
|
||||
await nextTick();
|
||||
if (audio.value) {
|
||||
audio.value.load();
|
||||
audio.value.volume = 0.2;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
streamLive.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
checkStream();
|
||||
setInterval(checkStream, 120000);
|
||||
checkStream();
|
||||
setInterval(checkStream, 120000);
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
img {
|
||||
width: 100%;
|
||||
max-height: 150px;
|
||||
object-fit: cover;
|
||||
width: 100%;
|
||||
max-height: 150px;
|
||||
object-fit: cover;
|
||||
}
|
||||
</style>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user