Compare commits
68 Commits
7afd1be81b
...
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 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -17,6 +17,9 @@ gitea-runner/nohup.out
|
|||||||
# Rust build artifacts
|
# Rust build artifacts
|
||||||
**/target/
|
**/target/
|
||||||
|
|
||||||
|
# Generated WASM output
|
||||||
|
vue/src/wasm/
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs
|
logs
|
||||||
*.log
|
*.log
|
||||||
|
|||||||
351
README.md
351
README.md
@@ -1,54 +1,359 @@
|
|||||||
# web_server
|
# My Web
|
||||||
|
|
||||||
Dockerized multi-service personal website.
|

|
||||||
|
|
||||||
## Untracked Files Requiring Manual Setup
|
Welcome to the source code for my website! Please contact me if you would like to collaborate and thank you for visiting.
|
||||||
|
|
||||||
These files are git-ignored and must be created or obtained manually before running the stack.
|
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`
|
### `.env`
|
||||||
|
|
||||||
Environment variables used by all services. No example file is provided — see `docker-compose.yml` for the full list of referenced variables (database credentials, hostnames, secrets, Spotify OAuth, Gitea tokens, etc.).
|
Create a `.env` file in the project root. All services read from this file.
|
||||||
|
|
||||||
### `gitea/config/app.ini`
|
| 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 application config. Copy from the template and fill in secrets:
|
### Gitea Config
|
||||||
|
|
||||||
|
Copy from the template and fill in secrets:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cp gitea/config/app.ini.template gitea/config/app.ini
|
cp gitea/config/app.ini.template gitea/config/app.ini
|
||||||
```
|
```
|
||||||
|
|
||||||
Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the database `PASSWD`.
|
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/settings.yml`
|
### SearXNG Config
|
||||||
|
|
||||||
SearXNG settings. Copy from the template:
|
Copy from the template:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cp searxng/settings.yml.template searxng/settings.yml
|
cp searxng/settings.yml.template searxng/settings.yml
|
||||||
```
|
```
|
||||||
|
|
||||||
The template uses environment variable substitution (`${BASE_URL}`, `${SEARXNG_SECRET_KEY}`) at container build time, so this file is generated by the Dockerfile's `entrypoint.sh`. If running outside Docker, fill in values manually.
|
The Docker entrypoint handles environment variable substitution (`${BASE_URL}`, `${SEARXNG_SECRET_KEY}`) automatically, so manual setup is only needed when running outside Docker.
|
||||||
|
|
||||||
### `certbot/conf/` and `certbot/www/`
|
### Spotify Token Setup
|
||||||
|
|
||||||
Let's Encrypt certificate storage. In production, certbot populates these automatically on first run. For local/dev use, either:
|
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
|
||||||
|
|
||||||
- Use dev mode (`docker-compose.dev.yml`) which skips SSL, or
|
### Obsidian Notes Setup
|
||||||
- Place self-signed certs in `certbot/conf/live/localhost/` (`fullchain.pem`, `privkey.pem`).
|
|
||||||
|
|
||||||
### `backend/token/`
|
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)
|
||||||
|
|
||||||
Directory where the backend persists Spotify OAuth tokens (`spotify_token.json`). Created automatically at runtime — no manual setup needed, but the directory is git-ignored so it won't exist on a fresh clone. Docker mounts `./backend/token/:/backend/token` so the directory is created by Docker.
|
### SSL Certificates (Certbot)
|
||||||
|
|
||||||
### `icecast2/fallback_music/`
|
**Initial setup (production):**
|
||||||
|
|
||||||
MP3 files used as fallback music for the Icecast2/Liquidsoap radio stream. Place at least one `.mp3` file here. A `.gitkeep` is tracked to preserve the directory.
|
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
|
||||||
|
|
||||||
### `gitea-runner/act_runner`
|
**Dev mode:** Nginx generates a self-signed certificate for localhost automatically.
|
||||||
|
|
||||||
The Gitea Actions runner binary. Download from [Gitea's releases](https://gitea.com/gitea/act_runner/releases) for your platform and place in `gitea-runner/`.
|
### Icecast Radio
|
||||||
|
|
||||||
### `gitea-runner/.runner`
|
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`.
|
||||||
|
|
||||||
Runner registration state file. Generated automatically when `gitea-runner/run.sh` runs for the first time (requires `GITEA_RUNNER_REGISTRATION_TOKEN` in `.env`).
|
### 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 v1.14.0 // indirect
|
||||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||||
github.com/cloudwego/base64x v0.1.6 // 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/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // 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/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 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
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.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.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
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.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.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.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.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.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
|
|||||||
@@ -57,3 +57,21 @@ models:
|
|||||||
fields:
|
fields:
|
||||||
deletedAt:
|
deletedAt:
|
||||||
resolver: false
|
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 (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"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
|
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.
|
// Activity returns ActivityResolver implementation.
|
||||||
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
|
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 (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"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
|
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.
|
// Favorite returns FavoriteResolver implementation.
|
||||||
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
|
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
|
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.
|
// Message returns MessageResolver implementation.
|
||||||
func (r *Resolver) Message() MessageResolver { return &messageResolver{r} }
|
func (r *Resolver) Message() MessageResolver { return &messageResolver{r} }
|
||||||
|
|
||||||
|
|||||||
@@ -18,12 +18,35 @@ type CreateActivityInput struct {
|
|||||||
Link *string `json:"link,omitempty"`
|
Link *string `json:"link,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CreateBookmarkInput struct {
|
||||||
|
Category string `json:"category"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Link string `json:"link"`
|
||||||
|
}
|
||||||
|
|
||||||
type CreateFavoriteInput struct {
|
type CreateFavoriteInput struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Link *string `json:"link,omitempty"`
|
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 {
|
type CreatePostInput struct {
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
@@ -96,6 +119,23 @@ type SteamStatus struct {
|
|||||||
RecentGames []*SteamGame `json:"recentGames"`
|
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 {
|
type UpdatePostInput struct {
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
|
|||||||
@@ -7,15 +7,111 @@ package graph
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"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.
|
// ID is the resolver for the id field.
|
||||||
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||||
return int(obj.ID), nil
|
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.
|
// Post returns PostResolver implementation.
|
||||||
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,19 @@ import (
|
|||||||
"adam-french.co.uk/backend/models"
|
"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.
|
// ID is the resolver for the id field.
|
||||||
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||||
return int(obj.ID), nil
|
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.
|
// 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
|
// 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.
|
// Mutation returns MutationResolver implementation.
|
||||||
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
|
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
|
||||||
|
|
||||||
|
|||||||
@@ -12,3 +12,11 @@ input CreateActivityInput {
|
|||||||
name: String!
|
name: String!
|
||||||
link: String
|
link: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
activities: [Activity!]!
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
createActivity(input: CreateActivityInput!): Activity!
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,3 +6,13 @@ input LoginInput {
|
|||||||
type AuthPayload {
|
type AuthPayload {
|
||||||
user: User!
|
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!
|
name: String!
|
||||||
link: String
|
link: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
favorites: [Favorite!]!
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
createFavorite(input: CreateFavoriteInput!): Favorite!
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,3 +6,7 @@ type GiteaFeedItem {
|
|||||||
commitMessage: String!
|
commitMessage: String!
|
||||||
createdAt: Time!
|
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
|
fileUrl: String
|
||||||
createdAt: Time!
|
createdAt: Time!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
messages: [Message!]!
|
||||||
|
}
|
||||||
|
|||||||
@@ -16,3 +16,14 @@ input UpdatePostInput {
|
|||||||
title: String!
|
title: String!
|
||||||
content: 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!
|
timePer500m: Float!
|
||||||
calories: Float!
|
calories: Float!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
rowingSessions: [Rowing!]!
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,31 +1,4 @@
|
|||||||
scalar Time
|
scalar Time
|
||||||
|
|
||||||
type Query {
|
type Query
|
||||||
users: [User!]!
|
type Mutation
|
||||||
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!
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -26,3 +26,8 @@ type SpotifyRecentItem {
|
|||||||
track: SpotifyTrack!
|
track: SpotifyTrack!
|
||||||
playedAt: Time!
|
playedAt: Time!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
spotifyListening: SpotifyPlaying
|
||||||
|
spotifyRecent: [SpotifyRecentItem!]
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,3 +10,7 @@ type SteamStatus {
|
|||||||
online: Boolean!
|
online: Boolean!
|
||||||
recentGames: [SteamGame!]!
|
recentGames: [SteamGame!]!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
steamStatus: SteamStatus
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,3 +10,14 @@ input CreateUserInput {
|
|||||||
username: String!
|
username: String!
|
||||||
password: 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 (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"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.
|
// ID is the resolver for the id field.
|
||||||
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
||||||
return int(obj.ID), nil
|
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"
|
"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) {
|
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
||||||
access_token, err := ctx.Cookie("access_token")
|
access_token, err := ctx.Cookie("access_token")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -50,6 +55,87 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
|||||||
ctx.Next()
|
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) {
|
func (store *Store) CheckToken(ctx *gin.Context) {
|
||||||
access_token, err := ctx.Cookie("access_token")
|
access_token, err := ctx.Cookie("access_token")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -123,7 +209,7 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
|||||||
"access_token",
|
"access_token",
|
||||||
tokens.AccessToken,
|
tokens.AccessToken,
|
||||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||||
store.Auth.Config.Endpoint,
|
"/",
|
||||||
store.Auth.Config.Domain,
|
store.Auth.Config.Domain,
|
||||||
true, true,
|
true, true,
|
||||||
)
|
)
|
||||||
@@ -131,7 +217,7 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
|||||||
"refresh_token",
|
"refresh_token",
|
||||||
tokens.RefreshToken,
|
tokens.RefreshToken,
|
||||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||||
store.Auth.Config.Endpoint,
|
"/",
|
||||||
store.Auth.Config.Domain,
|
store.Auth.Config.Domain,
|
||||||
true, true,
|
true, true,
|
||||||
)
|
)
|
||||||
@@ -140,6 +226,11 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (store *Store) Login(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
|
var input UserCredentials
|
||||||
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||||
@@ -169,7 +260,7 @@ func (store *Store) Login(ctx *gin.Context) {
|
|||||||
"access_token",
|
"access_token",
|
||||||
tokens.AccessToken,
|
tokens.AccessToken,
|
||||||
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
int(store.Auth.Config.AccessTokenLifetime.Seconds()),
|
||||||
store.Auth.Config.Endpoint,
|
"/",
|
||||||
store.Auth.Config.Domain,
|
store.Auth.Config.Domain,
|
||||||
true, true,
|
true, true,
|
||||||
)
|
)
|
||||||
@@ -177,7 +268,7 @@ func (store *Store) Login(ctx *gin.Context) {
|
|||||||
"refresh_token",
|
"refresh_token",
|
||||||
tokens.RefreshToken,
|
tokens.RefreshToken,
|
||||||
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
int(store.Auth.Config.RefreshTokenLifetime.Seconds()),
|
||||||
store.Auth.Config.Endpoint,
|
"/",
|
||||||
store.Auth.Config.Domain,
|
store.Auth.Config.Domain,
|
||||||
true, true,
|
true, true,
|
||||||
)
|
)
|
||||||
@@ -197,7 +288,7 @@ func (store *Store) removeCookies(ctx *gin.Context) {
|
|||||||
"access_token",
|
"access_token",
|
||||||
"",
|
"",
|
||||||
-1,
|
-1,
|
||||||
store.Auth.Config.Endpoint,
|
"/",
|
||||||
store.Auth.Config.Domain,
|
store.Auth.Config.Domain,
|
||||||
true, true,
|
true, true,
|
||||||
)
|
)
|
||||||
@@ -205,7 +296,7 @@ func (store *Store) removeCookies(ctx *gin.Context) {
|
|||||||
"refresh_token",
|
"refresh_token",
|
||||||
"",
|
"",
|
||||||
-1,
|
-1,
|
||||||
store.Auth.Config.Endpoint,
|
"/",
|
||||||
store.Auth.Config.Domain,
|
store.Auth.Config.Domain,
|
||||||
true, true,
|
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)
|
filename := filepath.Base(file.Filename)
|
||||||
dest := filepath.Join(fallbackMusicDir, 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 {
|
if _, err := os.Stat(dest); err == nil {
|
||||||
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
|
ctx.JSON(http.StatusConflict, gin.H{"error": "file already exists"})
|
||||||
return
|
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
|
ClaudeClient *anthropic.Client
|
||||||
Auth *services.Auth
|
Auth *services.Auth
|
||||||
Notes *services.Notes
|
Notes *services.Notes
|
||||||
|
LoginLimiter *services.RateLimiter
|
||||||
|
EmailSync *services.EmailSyncService
|
||||||
|
|
||||||
RecentSongs *[]spotify.RecentlyPlayedItem
|
RecentSongs *[]spotify.RecentlyPlayedItem
|
||||||
RecentSongsFetchedAt time.Time
|
RecentSongsFetchedAt time.Time
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
@@ -28,6 +29,10 @@ func main() {
|
|||||||
}
|
}
|
||||||
gin.DefaultWriter = io.MultiWriter(os.Stdout, logFile)
|
gin.DefaultWriter = io.MultiWriter(os.Stdout, logFile)
|
||||||
|
|
||||||
|
if os.Getenv("DEV_MODE") != "true" {
|
||||||
|
gin.SetMode(gin.ReleaseMode)
|
||||||
|
}
|
||||||
|
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
|
|
||||||
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
|
err = r.SetTrustedProxies([]string{"172.28.0.0/16"})
|
||||||
@@ -66,7 +71,7 @@ func main() {
|
|||||||
|
|
||||||
authSecret := os.Getenv("BACKEND_SECRET")
|
authSecret := os.Getenv("BACKEND_SECRET")
|
||||||
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
||||||
accessTokenLifetime := 24 * time.Hour
|
accessTokenLifetime := 7 * 24 * time.Hour
|
||||||
refreshTokenLifetime := 365 * 24 * time.Hour
|
refreshTokenLifetime := 365 * 24 * time.Hour
|
||||||
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
|
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
|
||||||
auth := services.InitAuth(&authConfig)
|
auth := services.InitAuth(&authConfig)
|
||||||
@@ -81,43 +86,51 @@ func main() {
|
|||||||
steamAPIKey := os.Getenv("STEAM_API_KEY")
|
steamAPIKey := os.Getenv("STEAM_API_KEY")
|
||||||
steamID := os.Getenv("STEAM_ID")
|
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)
|
protected := r.Group("/", store.AuthMiddlewear)
|
||||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||||
|
|
||||||
// FAVORITES
|
|
||||||
r.GET("/favorites", store.GetFavorites)
|
|
||||||
admin.POST("/favorites", store.CreateFavorite)
|
|
||||||
|
|
||||||
// ROWING
|
// ROWING
|
||||||
r.GET("/rowing", store.GetRowing)
|
r.GET("/rowing", store.GetRowing)
|
||||||
admin.POST("/rowing", store.CreateRowing)
|
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
|
// AUTH
|
||||||
r.POST("/auth/login", store.Login)
|
r.POST("/auth/login", store.Login)
|
||||||
r.POST("/auth/refresh", store.RefreshToken)
|
r.POST("/auth/refresh", store.RefreshToken)
|
||||||
r.GET("/auth/check", store.CheckToken)
|
r.GET("/auth/check", store.CheckToken)
|
||||||
r.POST("/auth/logout", store.Logout)
|
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
|
// SPOTIFY
|
||||||
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
|
r.GET("/spotify/callback", store.CompleteSpotifyAuth)
|
||||||
@@ -137,7 +150,7 @@ func main() {
|
|||||||
protected.POST("/messages/upload", store.UploadMessageFile)
|
protected.POST("/messages/upload", store.UploadMessageFile)
|
||||||
|
|
||||||
// NOTES
|
// NOTES
|
||||||
r.GET("/notes/*path", store.GetNoteFile)
|
admin.GET("/notes/*path", store.GetNoteFile)
|
||||||
|
|
||||||
// GRAPHQL
|
// GRAPHQL
|
||||||
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
||||||
@@ -145,18 +158,18 @@ func main() {
|
|||||||
}))
|
}))
|
||||||
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
|
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
|
||||||
gqlSrv.AddTransport(transport.Options{})
|
gqlSrv.AddTransport(transport.Options{})
|
||||||
gqlSrv.AddTransport(transport.GET{})
|
|
||||||
gqlSrv.AddTransport(transport.POST{})
|
gqlSrv.AddTransport(transport.POST{})
|
||||||
gqlSrv.AddTransport(transport.MultipartForm{})
|
gqlSrv.AddTransport(transport.MultipartForm{})
|
||||||
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
|
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
|
||||||
gqlSrv.Use(extension.FixedComplexityLimit(200))
|
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{})
|
gqlSrv.Use(extension.Introspection{})
|
||||||
}
|
}
|
||||||
r.POST("/graphql", graph.AuthContextMiddleware(auth), func(c *gin.Context) {
|
r.POST("/graphql", graph.AuthContextMiddleware(auth), func(c *gin.Context) {
|
||||||
gqlSrv.ServeHTTP(c.Writer, c.Request)
|
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) {
|
r.GET("/graphql", func(c *gin.Context) {
|
||||||
playground.Handler("GraphQL Playground", "/graphql").ServeHTTP(c.Writer, c.Request)
|
playground.Handler("GraphQL Playground", "/graphql").ServeHTTP(c.Writer, c.Request)
|
||||||
})
|
})
|
||||||
@@ -167,6 +180,11 @@ func main() {
|
|||||||
c.JSON(200, gin.H{"message": "Hello World"})
|
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")
|
port := os.Getenv("BACKEND_PORT")
|
||||||
r.Run(fmt.Sprintf(":%s", port))
|
r.Run(fmt.Sprintf(":%s", port))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,3 +66,47 @@ type Rowing struct {
|
|||||||
TimePer500m float64 `json:"timePer500m"`
|
TimePer500m float64 `json:"timePer500m"`
|
||||||
Calories float64 `json:"calories"`
|
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.Favorite{},
|
||||||
&models.Rowing{},
|
&models.Rowing{},
|
||||||
&models.Message{},
|
&models.Message{},
|
||||||
|
&models.JobApplication{},
|
||||||
|
&models.JobAppReference{},
|
||||||
|
&models.Bookmark{},
|
||||||
|
&models.ProcessedEmail{},
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
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 (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"net/url"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -24,11 +24,12 @@ var Upgrader = websocket.Upgrader{
|
|||||||
if origin == "" {
|
if origin == "" {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
origin = strings.TrimPrefix(origin, "https://")
|
u, err := url.Parse(origin)
|
||||||
origin = strings.TrimPrefix(origin, "http://")
|
if err != nil {
|
||||||
// Strip port for localhost comparisons (e.g. "localhost:80")
|
return false
|
||||||
host := strings.Split(origin, ":")[0]
|
}
|
||||||
return origin == allowedDomain || origin == "www."+allowedDomain || host == "localhost"
|
host := u.Hostname()
|
||||||
|
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,8 +41,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
rateLimitWindow = time.Second
|
rateLimitWindow = time.Second
|
||||||
rateLimitMaxMsgs = 10
|
rateLimitMaxMsgs = 10
|
||||||
)
|
)
|
||||||
|
|
||||||
func InitWebSocket(database *gorm.DB, domain string) {
|
func InitWebSocket(database *gorm.DB, domain string) {
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
if [ ! -d /etc/letsencrypt/live/${DOMAIN} ]; then
|
certbot certonly --webroot -w /var/www/certbot \
|
||||||
certbot certonly --webroot -w /var/www/certbot --email ${EMAIL} -d ${DOMAIN} -d www.${DOMAIN} --agree-tos --non-interactive;
|
--email ${EMAIL} \
|
||||||
fi;
|
-d ${DOMAIN} -d www.${DOMAIN} -d chat.${DOMAIN} \
|
||||||
|
--agree-tos --non-interactive --expand;
|
||||||
|
|
||||||
trap exit TERM;
|
trap exit TERM;
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- ./vue:/app
|
- ./vue:/app
|
||||||
- /app/node_modules
|
- /app/node_modules
|
||||||
|
- /app/src/wasm
|
||||||
environment:
|
environment:
|
||||||
- NODE_ENV=development
|
- NODE_ENV=development
|
||||||
backend:
|
backend:
|
||||||
@@ -11,10 +12,11 @@ services:
|
|||||||
- SPOTIFY_REDIRECT_URI=https://localhost/api/spotify/callback
|
- SPOTIFY_REDIRECT_URI=https://localhost/api/spotify/callback
|
||||||
- GQL_PLAYGROUND=true
|
- GQL_PLAYGROUND=true
|
||||||
- GQL_INTROSPECTION=true
|
- GQL_INTROSPECTION=true
|
||||||
|
- DEV_MODE=true
|
||||||
|
- SEED_DB=true
|
||||||
nginx:
|
nginx:
|
||||||
environment:
|
environment:
|
||||||
- DEV_MODE=true
|
- DEV_MODE=true
|
||||||
- SEED_DB=true
|
|
||||||
ports:
|
ports:
|
||||||
- 80:80
|
- 80:80
|
||||||
- 443:443
|
- 443:443
|
||||||
|
|||||||
@@ -1,180 +1,219 @@
|
|||||||
networks:
|
networks:
|
||||||
app-network:
|
app-network:
|
||||||
driver: bridge
|
driver: bridge
|
||||||
|
ipam:
|
||||||
|
config:
|
||||||
|
- subnet: 172.28.0.0/16
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
dbdata:
|
# Postgres database
|
||||||
uploads:
|
dbdata:
|
||||||
vue_dist:
|
# File upload
|
||||||
|
uploads:
|
||||||
searxng_data:
|
# Vue build
|
||||||
|
vue_dist:
|
||||||
|
# Searxng data
|
||||||
|
searxng_data:
|
||||||
|
# Open-WebUI data
|
||||||
|
openwebui_data:
|
||||||
|
|
||||||
services:
|
services:
|
||||||
vue:
|
vue:
|
||||||
build:
|
build:
|
||||||
context: ./vue
|
context: ./vue
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: vue
|
container_name: vue
|
||||||
volumes:
|
volumes:
|
||||||
- vue_dist:/output
|
- vue_dist:/output
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
|
|
||||||
nginx:
|
nginx:
|
||||||
build:
|
build:
|
||||||
context: ./nginx
|
context: ./nginx
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: nginx
|
container_name: nginx
|
||||||
env_file: ./.env
|
env_file: ./.env
|
||||||
restart: always
|
restart: always
|
||||||
depends_on:
|
depends_on:
|
||||||
- vue
|
- vue
|
||||||
- backend
|
- backend
|
||||||
- icecast2
|
- icecast2
|
||||||
- gitea
|
- gitea
|
||||||
- hasura
|
- hasura
|
||||||
- quartz
|
- quartz
|
||||||
- searxng
|
- searxng
|
||||||
networks:
|
- open-webui
|
||||||
- app-network
|
networks:
|
||||||
ports:
|
- app-network
|
||||||
- 80:80
|
ports:
|
||||||
- 443:443
|
- 80:80
|
||||||
volumes:
|
- 443:443
|
||||||
- ./certbot/conf:/etc/letsencrypt
|
volumes:
|
||||||
- ./certbot/www:/var/www/certbot
|
- ./certbot/conf:/etc/letsencrypt
|
||||||
- uploads:/uploads
|
- ./certbot/www:/var/www/certbot
|
||||||
- vue_dist:/etc/nginx/html
|
- uploads:/uploads
|
||||||
|
- vue_dist:/etc/nginx/html
|
||||||
|
|
||||||
certbot:
|
certbot:
|
||||||
image: certbot/certbot:v3.1.0
|
image: certbot/certbot:v3.1.0
|
||||||
container_name: certbot
|
container_name: certbot
|
||||||
volumes:
|
volumes:
|
||||||
- ./certbot/entrypoint.sh:/entrypoint.sh
|
- ./certbot/entrypoint.sh:/entrypoint.sh
|
||||||
- ./certbot/conf:/etc/letsencrypt
|
- ./certbot/conf:/etc/letsencrypt
|
||||||
- ./certbot/www:/var/www/certbot
|
- ./certbot/www:/var/www/certbot
|
||||||
entrypoint: ["/entrypoint.sh"]
|
entrypoint: ["/entrypoint.sh"]
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
|
|
||||||
backend:
|
backend:
|
||||||
build:
|
build:
|
||||||
context: ./backend
|
context: ./backend
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: "${BACKEND_HOST}"
|
container_name: "${BACKEND_HOST}"
|
||||||
restart: always
|
restart: always
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
- db
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
env_file:
|
env_file:
|
||||||
- ./.env
|
- ./.env
|
||||||
volumes:
|
volumes:
|
||||||
- ./backend/token/:/backend/token
|
- ./backend/token/:/backend/token
|
||||||
- ${OBSIDIAN_DIR}:/backend/notes
|
- ${OBSIDIAN_DIR}:/backend/notes
|
||||||
- ./logs:/backend/logs
|
- ./logs:/backend/logs
|
||||||
- uploads:/backend/uploads
|
- uploads:/backend/uploads
|
||||||
- ./icecast2/fallback_music:/backend/fallback_music
|
- ./icecast2/fallback_music:/backend/fallback_music
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-qO-", "http://localhost:8080/"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
db:
|
autoheal:
|
||||||
image: postgres:16
|
image: willfarrell/autoheal:latest
|
||||||
container_name: "${POSTGRES_HOST}"
|
container_name: autoheal
|
||||||
restart: always
|
restart: always
|
||||||
env_file:
|
environment:
|
||||||
- ./.env
|
- AUTOHEAL_CONTAINER_LABEL=all
|
||||||
networks:
|
- AUTOHEAL_INTERVAL=30
|
||||||
- app-network
|
- AUTOHEAL_START_PERIOD=60
|
||||||
volumes:
|
volumes:
|
||||||
- dbdata:/var/lib/postgresql/data
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
|
||||||
hasura:
|
db:
|
||||||
image: hasura/graphql-engine:v2.44.0
|
image: postgres:16
|
||||||
container_name: "${HASURA_HOST}"
|
container_name: "${POSTGRES_HOST}"
|
||||||
restart: always
|
restart: always
|
||||||
depends_on:
|
env_file:
|
||||||
- db
|
- ./.env
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
environment:
|
volumes:
|
||||||
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
- dbdata:/var/lib/postgresql/data
|
||||||
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"
|
|
||||||
|
|
||||||
icecast2:
|
hasura:
|
||||||
build:
|
image: hasura/graphql-engine:v2.44.0
|
||||||
context: ./icecast2
|
container_name: "${HASURA_HOST}"
|
||||||
dockerfile: Dockerfile
|
restart: always
|
||||||
container_name: "${ICECAST_HOST}"
|
depends_on:
|
||||||
restart: always
|
- db
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
env_file:
|
environment:
|
||||||
- ./.env
|
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||||||
volumes:
|
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
|
||||||
- ./icecast2/fallback_music:/music:ro
|
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
|
||||||
ports:
|
HASURA_GRAPHQL_DEV_MODE: "false"
|
||||||
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
|
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
|
||||||
|
|
||||||
quartz:
|
icecast2:
|
||||||
build:
|
build:
|
||||||
context: ./quartz
|
context: ./icecast2
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: "${QUARTZ_HOST}"
|
container_name: "${ICECAST_HOST}"
|
||||||
restart: always
|
restart: always
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
env_file:
|
env_file:
|
||||||
- ./.env
|
- ./.env
|
||||||
volumes:
|
volumes:
|
||||||
- ${OBSIDIAN_DIR}:/quartz/content:ro
|
- ./icecast2/fallback_music:/music:ro
|
||||||
|
ports:
|
||||||
|
- "${LIQUIDSOAP_HARBOR_PORT:-8001}:${LIQUIDSOAP_HARBOR_PORT:-8001}"
|
||||||
|
|
||||||
|
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:
|
searxng:
|
||||||
build:
|
build:
|
||||||
context: ./searxng
|
context: ./searxng
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: "${SEARXNG_HOST}"
|
container_name: "${SEARXNG_HOST}"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
environment:
|
environment:
|
||||||
- BASE_URL=https://www.${DOMAIN}/searxng/
|
- BASE_URL=https://www.${DOMAIN}/searxng/
|
||||||
- INSTANCE_NAME=searxng
|
- INSTANCE_NAME=searxng
|
||||||
- SEARXNG_SECRET_KEY=${SEARXNG_SECRET_KEY}
|
- SEARXNG_SECRET_KEY=${SEARXNG_SECRET_KEY}
|
||||||
volumes:
|
volumes:
|
||||||
- searxng_data:/etc/searxng
|
- searxng_data:/etc/searxng
|
||||||
|
|
||||||
|
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:
|
gitea:
|
||||||
image: docker.gitea.com/gitea:1.25.4-rootless
|
image: docker.gitea.com/gitea:1.25.4-rootless
|
||||||
container_name: "${GITEA_HOST}"
|
container_name: "${GITEA_HOST}"
|
||||||
entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"]
|
entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"]
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
environment:
|
environment:
|
||||||
- GITEA__database__DB_TYPE=postgres
|
- GITEA__database__DB_TYPE=postgres
|
||||||
- GITEA__database__HOST=${POSTGRES_HOST}
|
- GITEA__database__HOST=${POSTGRES_HOST}
|
||||||
- GITEA__database__NAME=${POSTGRES_GITEA_DB}
|
- GITEA__database__NAME=${POSTGRES_GITEA_DB}
|
||||||
- GITEA__database__USER=${POSTGRES_USER}
|
- GITEA__database__USER=${POSTGRES_USER}
|
||||||
- GITEA__database__PASSWD=${POSTGRES_PASSWORD}
|
- GITEA__database__PASSWD=${POSTGRES_PASSWORD}
|
||||||
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
|
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
|
||||||
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
|
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
|
||||||
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
|
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
|
||||||
- USER_UID=1000
|
- USER_UID=1000
|
||||||
- USER_GID=1000
|
- USER_GID=1000
|
||||||
restart: always
|
restart: always
|
||||||
volumes:
|
volumes:
|
||||||
- ./gitea/data:/var/lib/gitea
|
- ./gitea/data:/var/lib/gitea
|
||||||
- ./gitea/config:/etc/gitea
|
- ./gitea/config:/etc/gitea
|
||||||
- ./gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro
|
- ./gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro
|
||||||
- /etc/timezone:/etc/timezone:ro
|
- /etc/timezone:/etc/timezone:ro
|
||||||
- /etc/localtime:/etc/localtime:ro
|
- /etc/localtime:/etc/localtime:ro
|
||||||
ports:
|
ports:
|
||||||
- "2222:2222"
|
- "2222:2222"
|
||||||
- "3000:3000"
|
- "3000:3000"
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
- db
|
||||||
|
|||||||
0
gitea/config/entrypoint.sh
Normal file
0
gitea/config/entrypoint.sh
Normal file
@@ -1,7 +1,7 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
# Check if dev mode, certificate exists, or setup mode
|
# Check if DEV_MODE
|
||||||
if [ "$DEV_MODE" = "true" ]; then
|
if [ "$DEV_MODE" = "true" ]; then
|
||||||
echo "Dev mode. Generating self-signed certificate for HTTPS."
|
echo "Dev mode. Generating self-signed certificate for HTTPS."
|
||||||
CERT_DIR="/etc/letsencrypt/live/localhost"
|
CERT_DIR="/etc/letsencrypt/live/localhost"
|
||||||
@@ -12,16 +12,19 @@ if [ "$DEV_MODE" = "true" ]; then
|
|||||||
-out "$CERT_DIR/fullchain.pem" \
|
-out "$CERT_DIR/fullchain.pem" \
|
||||||
-subj "/CN=localhost" 2>/dev/null
|
-subj "/CN=localhost" 2>/dev/null
|
||||||
fi
|
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_dev.conf.template \
|
||||||
>/etc/nginx/nginx.conf
|
>/etc/nginx/nginx.conf
|
||||||
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
||||||
echo "Certificates found. Using production nginx config."
|
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.template \
|
||||||
>/etc/nginx/nginx.conf
|
>/etc/nginx/nginx.conf
|
||||||
else
|
else
|
||||||
echo "Certificates NOT found. Using setup nginx config."
|
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
|
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,13 @@ http {
|
|||||||
server_tokens off;
|
server_tokens off;
|
||||||
charset utf-8;
|
charset utf-8;
|
||||||
|
|
||||||
|
resolver 127.0.0.11 valid=10s;
|
||||||
|
|
||||||
client_max_body_size 50M;
|
client_max_body_size 50M;
|
||||||
|
|
||||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
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=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;
|
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
|
||||||
|
|
||||||
log_format compact
|
log_format compact
|
||||||
@@ -70,6 +73,12 @@ http {
|
|||||||
http2 on;
|
http2 on;
|
||||||
server_name www.$DOMAIN;
|
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;
|
root /etc/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
@@ -138,7 +147,7 @@ http {
|
|||||||
|
|
||||||
location $BACKEND_ENDPOINT/ws {
|
location $BACKEND_ENDPOINT/ws {
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection "upgrade";
|
||||||
@@ -151,7 +160,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/auth/login {
|
location $BACKEND_ENDPOINT/auth/login {
|
||||||
limit_req zone=login burst=3 nodelay;
|
limit_req zone=login burst=3 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -161,7 +170,17 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/messages/upload {
|
location $BACKEND_ENDPOINT/messages/upload {
|
||||||
limit_req zone=upload burst=3 nodelay;
|
limit_req zone=upload burst=3 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -171,7 +190,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/ {
|
location $BACKEND_ENDPOINT/ {
|
||||||
limit_req zone=api burst=20 nodelay;
|
limit_req zone=api burst=20 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -183,7 +202,8 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /radio/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -195,7 +215,8 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /gitea/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -207,7 +228,10 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /hasura/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -222,7 +246,10 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /notes/ {
|
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_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection "upgrade";
|
||||||
@@ -233,12 +260,28 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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 @auth_denied {
|
||||||
|
return 302 /admin/login?redirect=$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
location /searxng {
|
location /searxng {
|
||||||
return 301 /searxng/;
|
return 301 /searxng/;
|
||||||
}
|
}
|
||||||
|
|
||||||
location /searxng/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -246,6 +289,67 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
server_tokens off;
|
||||||
charset utf-8;
|
charset utf-8;
|
||||||
|
|
||||||
|
resolver 127.0.0.11 valid=10s;
|
||||||
|
|
||||||
client_max_body_size 50M;
|
client_max_body_size 50M;
|
||||||
|
|
||||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||||
@@ -44,6 +46,13 @@ http {
|
|||||||
listen 80;
|
listen 80;
|
||||||
server_name $DOMAIN www.$DOMAIN;
|
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/ {
|
location /uploads/ {
|
||||||
alias /uploads/;
|
alias /uploads/;
|
||||||
add_header X-Content-Type-Options nosniff always;
|
add_header X-Content-Type-Options nosniff always;
|
||||||
@@ -65,7 +74,7 @@ http {
|
|||||||
|
|
||||||
location $BACKEND_ENDPOINT/ws {
|
location $BACKEND_ENDPOINT/ws {
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection "upgrade";
|
||||||
@@ -78,7 +87,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/auth/login {
|
location $BACKEND_ENDPOINT/auth/login {
|
||||||
limit_req zone=login burst=3 nodelay;
|
limit_req zone=login burst=3 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -88,7 +97,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/messages/upload {
|
location $BACKEND_ENDPOINT/messages/upload {
|
||||||
limit_req zone=upload burst=3 nodelay;
|
limit_req zone=upload burst=3 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -98,7 +107,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/ {
|
location $BACKEND_ENDPOINT/ {
|
||||||
limit_req zone=api burst=20 nodelay;
|
limit_req zone=api burst=20 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -110,7 +119,8 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /radio/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -122,7 +132,8 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /gitea/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -134,7 +145,10 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /hasura/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -149,7 +163,10 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /notes/ {
|
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_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection "upgrade";
|
||||||
@@ -160,19 +177,34 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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 @auth_denied {
|
||||||
|
return 302 /admin/login?redirect=$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
location /searxng {
|
location /searxng {
|
||||||
return 301 /searxng/;
|
return 301 /searxng/;
|
||||||
}
|
}
|
||||||
|
|
||||||
location /searxng/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
@@ -182,6 +214,13 @@ http {
|
|||||||
ssl_certificate /etc/letsencrypt/live/localhost/fullchain.pem;
|
ssl_certificate /etc/letsencrypt/live/localhost/fullchain.pem;
|
||||||
ssl_certificate_key /etc/letsencrypt/live/localhost/privkey.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/ {
|
location /uploads/ {
|
||||||
alias /uploads/;
|
alias /uploads/;
|
||||||
add_header X-Content-Type-Options nosniff always;
|
add_header X-Content-Type-Options nosniff always;
|
||||||
@@ -203,7 +242,7 @@ http {
|
|||||||
|
|
||||||
location $BACKEND_ENDPOINT/ws {
|
location $BACKEND_ENDPOINT/ws {
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection "upgrade";
|
||||||
@@ -216,7 +255,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/auth/login {
|
location $BACKEND_ENDPOINT/auth/login {
|
||||||
limit_req zone=login burst=3 nodelay;
|
limit_req zone=login burst=3 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -226,7 +265,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/messages/upload {
|
location $BACKEND_ENDPOINT/messages/upload {
|
||||||
limit_req zone=upload burst=3 nodelay;
|
limit_req zone=upload burst=3 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -236,7 +275,7 @@ http {
|
|||||||
location $BACKEND_ENDPOINT/ {
|
location $BACKEND_ENDPOINT/ {
|
||||||
limit_req zone=api burst=20 nodelay;
|
limit_req zone=api burst=20 nodelay;
|
||||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
proxy_pass http://$BACKEND_HOST:$BACKEND_PORT/;
|
proxy_pass $upstream_backend;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -248,7 +287,8 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /radio/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -260,7 +300,8 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /gitea/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -272,7 +313,10 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /hasura/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -287,7 +331,10 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
location /notes/ {
|
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_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection "upgrade";
|
||||||
@@ -298,19 +345,34 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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 @auth_denied {
|
||||||
|
return 302 /admin/login?redirect=$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
location /searxng {
|
location /searxng {
|
||||||
return 301 /searxng/;
|
return 301 /searxng/;
|
||||||
}
|
}
|
||||||
|
|
||||||
location /searxng/ {
|
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 Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
143
readme.md
143
readme.md
@@ -1,143 +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
|
|
||||||
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=
|
|
||||||
|
|
||||||
|
|
||||||
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,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
|
FROM node:22-slim
|
||||||
RUN apt-get update && apt-get install -y make git && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y make git && rm -rf /var/lib/apt/lists/*
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
COPY . .
|
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"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
crate-type = ["cdylib"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
js-sys = "0.3.85"
|
js-sys = "0.3.85"
|
||||||
wasm-bindgen = "0.2.108"
|
wasm-bindgen = "0.2.108"
|
||||||
@@ -10,6 +13,13 @@ web-sys = { version = "0.3.85", features = [
|
|||||||
"console",
|
"console",
|
||||||
"Document",
|
"Document",
|
||||||
"Element",
|
"Element",
|
||||||
|
"HtmlElement",
|
||||||
"Window",
|
"Window",
|
||||||
"Animation",
|
"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 use auto_scroll::AutoScroller;
|
||||||
pub struct BadApplePlayer {
|
pub use headline::HeadlineScroller;
|
||||||
is_playing: bool,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,33 +1,33 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="description" content="Adam French's personal website">
|
<meta name="description" content="Adam French's personal website" />
|
||||||
<title>AF</title>
|
<title>AF</title>
|
||||||
<link rel="preconnect" href="https://i.scdn.co" crossorigin>
|
<link rel="preconnect" href="https://i.scdn.co" crossorigin />
|
||||||
<link
|
<link
|
||||||
rel="preconnect"
|
rel="preconnect"
|
||||||
href="https://cdn.akamai.steamstatic.com"
|
href="https://cdn.akamai.steamstatic.com"
|
||||||
crossorigin
|
crossorigin
|
||||||
>
|
/>
|
||||||
<link rel="icon" type="/img/x-icon" href="/img/favicon.ico">
|
<link rel="icon" type="/img/x-icon" href="/img/favicon.ico" />
|
||||||
<link
|
<link
|
||||||
rel="preload"
|
rel="preload"
|
||||||
href="/fonts/big_noodle_titling.woff2"
|
href="/fonts/big_noodle_titling.woff2"
|
||||||
as="font"
|
as="font"
|
||||||
type="font/woff2"
|
type="font/woff2"
|
||||||
crossorigin
|
crossorigin
|
||||||
>
|
/>
|
||||||
<link
|
<link
|
||||||
rel="preload"
|
rel="preload"
|
||||||
href="/fonts/CreatoDisplay-Bold.woff2"
|
href="/fonts/CreatoDisplay-Bold.woff2"
|
||||||
as="font"
|
as="font"
|
||||||
type="font/woff2"
|
type="font/woff2"
|
||||||
crossorigin
|
crossorigin
|
||||||
>
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body id="app">
|
<body id="app">
|
||||||
<script type="module" src="/src/main.js"></script>
|
<script type="module" src="/src/main.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
357
vue/package-lock.json
generated
357
vue/package-lock.json
generated
@@ -24,8 +24,10 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-vue": "^6.0.1",
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
"vite": "^7.1.11",
|
"vite": "^7.3.2",
|
||||||
"vite-plugin-vue-devtools": "^8.0.3"
|
"vite-plugin-top-level-await": "^1.6.0",
|
||||||
|
"vite-plugin-vue-devtools": "^8.0.3",
|
||||||
|
"vite-plugin-wasm": "^3.6.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
@@ -1024,6 +1026,24 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/@rollup/rollup-android-arm-eabi": {
|
||||||
"version": "4.59.0",
|
"version": "4.59.0",
|
||||||
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
|
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz",
|
||||||
@@ -1349,6 +1369,293 @@
|
|||||||
"win32"
|
"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": {
|
"node_modules/@tailwindcss/node": {
|
||||||
"version": "4.1.18",
|
"version": "4.1.18",
|
||||||
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",
|
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",
|
||||||
@@ -3518,10 +3825,24 @@
|
|||||||
"integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",
|
"integrity": "sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==",
|
||||||
"license": "(WTFPL OR MIT)"
|
"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": {
|
"node_modules/vite": {
|
||||||
"version": "7.3.1",
|
"version": "7.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
|
||||||
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==",
|
"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.27.0",
|
"esbuild": "^0.27.0",
|
||||||
@@ -3661,6 +3982,22 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/vite-plugin-vue-devtools": {
|
||||||
"version": "8.0.5",
|
"version": "8.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/vite-plugin-vue-devtools/-/vite-plugin-vue-devtools-8.0.5.tgz",
|
"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"
|
"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": {
|
"node_modules/vue": {
|
||||||
"version": "3.5.26",
|
"version": "3.5.26",
|
||||||
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.26.tgz",
|
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.26.tgz",
|
||||||
|
|||||||
@@ -7,8 +7,9 @@
|
|||||||
"node": "^20.19.0 || >=22.12.0"
|
"node": "^20.19.0 || >=22.12.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"build:wasm": "wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm",
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "npm run build:wasm && vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -28,7 +29,9 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-vue": "^6.0.1",
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
"vite": "^7.1.11",
|
"vite": "^7.3.2",
|
||||||
"vite-plugin-vue-devtools": "^8.0.3"
|
"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>
|
<script setup>
|
||||||
import { RouterView } from "vue-router";
|
import { RouterView } from "vue-router";
|
||||||
import Navbar from "@/components/Navbar.vue";
|
|
||||||
import Footer from "@/components/Footer.vue";
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="app-layout halftone">
|
<RouterView />
|
||||||
<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>
|
|
||||||
</template>
|
</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 */
|
/* Route transitions */
|
||||||
.slide-enter-active,
|
.slide-enter-active,
|
||||||
.slide-leave-active {
|
.slide-leave-active {
|
||||||
transition:
|
transition:
|
||||||
transform 0.3s ease,
|
transform 0.3s ease,
|
||||||
opacity 0.3s ease;
|
opacity 0.3s ease;
|
||||||
}
|
}
|
||||||
.slide-enter-from {
|
.slide-enter-from {
|
||||||
transform: translateX(30px);
|
transform: translateX(30px);
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
}
|
}
|
||||||
.slide-leave-to {
|
.slide-leave-to {
|
||||||
transform: translateX(-30px);
|
transform: translateX(-30px);
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* PRINTING */
|
/* PRINTING */
|
||||||
@media print {
|
@media print {
|
||||||
.no-print,
|
.no-print,
|
||||||
.no-print * {
|
.no-print * {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
margin: 0px;
|
margin: 0px;
|
||||||
padding: 0px;
|
padding: 0px;
|
||||||
width: 0x;
|
width: 0x;
|
||||||
height: 0px;
|
height: 0px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* END OF PRINTING */
|
/* END OF PRINTING */
|
||||||
|
|
||||||
/* FONTS */
|
/* FONTS */
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "big_noodle_titling";
|
font-family: "big_noodle_titling";
|
||||||
src: url("/fonts/big_noodle_titling.woff2") format("woff2");
|
src: url("/fonts/big_noodle_titling.woff2") format("woff2");
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
}
|
}
|
||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "CreatoDisplay";
|
font-family: "CreatoDisplay";
|
||||||
src: url("/fonts/CreatoDisplay-Bold.woff2") format("woff2");
|
src: url("/fonts/CreatoDisplay-Bold.woff2") format("woff2");
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
font-style: normal;
|
font-style: normal;
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* END OF FONTS */
|
/* END OF FONTS */
|
||||||
|
|
||||||
/* VARIABLES */
|
/* VARIABLES */
|
||||||
:root {
|
:root {
|
||||||
/* RED, WHITE, BLACK are standard*/
|
/* RED, WHITE, BLACK are standard*/
|
||||||
--portal_grey: #dddddd;
|
--portal_grey: #dddddd;
|
||||||
--portal_orange: #ff9a00;
|
--portal_orange: #ff9a00;
|
||||||
--portal_light_orange: #ff5d00;
|
--portal_light_orange: #ff5d00;
|
||||||
--portal_blue: #0065ff;
|
--portal_blue: #0065ff;
|
||||||
--portal_light_blue: #00a2ff;
|
--portal_light_blue: #00a2ff;
|
||||||
|
|
||||||
/* MAIN COLORS */
|
/* MAIN COLORS */
|
||||||
--primary: #55ffbb;
|
--primary: #55ffbb;
|
||||||
--secondary: #62ff57;
|
--secondary: #62ff57;
|
||||||
--tertiary: #ff579a;
|
--tertiary: #ff579a;
|
||||||
--quaternary: #024942;
|
--quaternary: #024942;
|
||||||
|
|
||||||
/* BACKGROUND COLORS */
|
/* BACKGROUND COLORS */
|
||||||
--bg_primary: #1b110e;
|
--bg_primary: #1b110e;
|
||||||
--bg_secondary: #04080f;
|
--bg_secondary: #04080f;
|
||||||
--bg_tertiary: #0c1c10;
|
--bg_tertiary: #0c1c10;
|
||||||
--link: #222;
|
--link: #222;
|
||||||
|
|
||||||
--bdr: 2px;
|
--bdr: 2px;
|
||||||
|
|
||||||
--spacing: 3px;
|
--spacing: 3px;
|
||||||
|
|
||||||
/* FONTS USED */
|
/* FONTS USED */
|
||||||
--font_heading: big_noodle_titling;
|
--font_heading: big_noodle_titling;
|
||||||
--font_default: CreatoDisplay;
|
--font_default: CreatoDisplay;
|
||||||
}
|
}
|
||||||
|
|
||||||
@theme {
|
@theme {
|
||||||
--color-primary: var(--primary);
|
--color-primary: var(--primary);
|
||||||
--color-secondary: var(--secondary);
|
--color-secondary: var(--secondary);
|
||||||
--color-tertiary: var(--tertiary);
|
--color-tertiary: var(--tertiary);
|
||||||
--color-quaternary: var(--quaternary);
|
--color-quaternary: var(--quaternary);
|
||||||
|
|
||||||
--color-bg_primary: var(--bg_primary);
|
--color-bg_primary: var(--bg_primary);
|
||||||
--color-bg_secondary: var(--bg_secondary);
|
--color-bg_secondary: var(--bg_secondary);
|
||||||
--color-link: var(--link);
|
--color-link: var(--link);
|
||||||
|
|
||||||
--borderWidth-primary: var(--primary);
|
--borderWidth-primary: var(--primary);
|
||||||
--borderWidth-secondary: var(--secondary);
|
--borderWidth-secondary: var(--secondary);
|
||||||
--borderWidth-tertiary: var(--tertiary);
|
--borderWidth-tertiary: var(--tertiary);
|
||||||
|
|
||||||
--font-heading: var(--font_heading);
|
--font-heading: var(--font_heading);
|
||||||
--default-font-family: var(--font_default);
|
--default-font-family: var(--font_default);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* END OF VARIABLES */
|
/* END OF VARIABLES */
|
||||||
/* ELEMENTS */
|
/* ELEMENTS */
|
||||||
body {
|
body {
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
width: 100vw;
|
width: 100%;
|
||||||
height: 100vh;
|
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 {
|
input {
|
||||||
color: var(--secondary);
|
color: var(--secondary);
|
||||||
border-color: var(--primary);
|
border-color: var(--primary);
|
||||||
border-width: 1px;
|
border-width: 1px;
|
||||||
}
|
}
|
||||||
|
|
||||||
small {
|
small {
|
||||||
color: var(--tertiary);
|
color: var(--tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
code {
|
code {
|
||||||
color: var(--tertiary);
|
color: var(--tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
ul {
|
ul {
|
||||||
color: var(--tertiary);
|
color: var(--tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
li {
|
li {
|
||||||
color: var(--tertiary);
|
color: var(--tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
h1,
|
h1,
|
||||||
h2,
|
h2,
|
||||||
h3,
|
h3,
|
||||||
h4 {
|
h4 {
|
||||||
margin: 0.25rem;
|
margin: 0.25rem;
|
||||||
font-family: var(--font_heading);
|
font-family: var(--font_heading);
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
h3,
|
h3,
|
||||||
h4 {
|
h4 {
|
||||||
font-size: 1.125rem;
|
font-size: 1.125rem;
|
||||||
line-height: 1.75rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 {
|
h1 {
|
||||||
font-size: 1.5rem;
|
font-size: 1.5rem;
|
||||||
line-height: 2rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h2 {
|
h2 {
|
||||||
font-size: 1.25rem;
|
font-size: 1.25rem;
|
||||||
line-height: 1.75rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
p {
|
p {
|
||||||
color: var(--secondary);
|
color: var(--secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
a {
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
background-color: var(--link);
|
background-color: var(--link);
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-family: var(--font_heading);
|
font-family: var(--font_heading);
|
||||||
letter-spacing: 0.025em;
|
letter-spacing: 0.025em;
|
||||||
}
|
}
|
||||||
|
|
||||||
input,
|
input,
|
||||||
textarea {
|
textarea {
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
border-width: 1px;
|
border-width: 1px;
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
input::placeholder,
|
input::placeholder,
|
||||||
textarea::placeholder {
|
textarea::placeholder {
|
||||||
color: var(--secondary);
|
color: var(--secondary);
|
||||||
opacity: 0.5;
|
opacity: 0.5;
|
||||||
}
|
}
|
||||||
|
|
||||||
table {
|
table {
|
||||||
border-color: var(--primary);
|
border-color: var(--primary);
|
||||||
border-width: 1px;
|
border-width: 1px;
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
td {
|
td {
|
||||||
gap: 0.25rem;
|
gap: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
tr {
|
tr {
|
||||||
border-color: var(--primary);
|
border-color: var(--primary);
|
||||||
border-bottom-width: 1px;
|
border-bottom-width: 1px;
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
th {
|
th {
|
||||||
padding-right: 0.75rem;
|
padding-right: 0.75rem;
|
||||||
padding-left: 0.75rem;
|
padding-left: 0.75rem;
|
||||||
border-right-width: 1px;
|
border-right-width: 1px;
|
||||||
border-style: dotted;
|
border-style: dotted;
|
||||||
border-color: var(--tertiary);
|
border-color: var(--tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
td {
|
td {
|
||||||
padding-right: 0.75rem;
|
padding-right: 0.75rem;
|
||||||
padding-left: 0.75rem;
|
padding-left: 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* END OF ELEMENTS */
|
/* END OF ELEMENTS */
|
||||||
@@ -212,146 +231,146 @@ td {
|
|||||||
/* CLASSES */
|
/* CLASSES */
|
||||||
|
|
||||||
.img-stamp {
|
.img-stamp {
|
||||||
width: 99px;
|
width: 99px;
|
||||||
height: 55px;
|
height: 55px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* BORDERS */
|
/* BORDERS */
|
||||||
.bdr-1 {
|
.bdr-1 {
|
||||||
border-width: 30px;
|
border-width: 30px;
|
||||||
border-image: url("/img/borders/border1.gif") 30 round;
|
border-image: url("/img/borders/border1.gif") 30 round;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bdr-1-inv {
|
.bdr-1-inv {
|
||||||
border-width: 30px;
|
border-width: 30px;
|
||||||
border-image: url("/img/borders/border1inv.gif") 30 round;
|
border-image: url("/img/borders/border1inv.gif") 30 round;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bdr-2 {
|
.bdr-2 {
|
||||||
border-width: 5px;
|
border-width: 5px;
|
||||||
border-image: url("/img/borders/border4.gif") 7 round;
|
border-image: url("/img/borders/border4.gif") 7 round;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bdr-cv {
|
.bdr-cv {
|
||||||
border-width: 30px;
|
border-width: 30px;
|
||||||
border-image: url("/img/borders/bordercv.png") 30 round;
|
border-image: url("/img/borders/bordercv.png") 30 round;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* A5 Page */
|
/* A5 Page */
|
||||||
.a5page-landscape {
|
.a5page-landscape {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
box-sizing: content-box;
|
box-sizing: content-box;
|
||||||
height: 148mm;
|
height: 148mm;
|
||||||
width: 210mm;
|
width: 210mm;
|
||||||
}
|
}
|
||||||
|
|
||||||
.a5page-portrait {
|
.a5page-portrait {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
box-sizing: content-box;
|
box-sizing: content-box;
|
||||||
width: 148mm;
|
width: 148mm;
|
||||||
height: 210mm;
|
height: 210mm;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* A4 Page */
|
/* A4 Page */
|
||||||
.a4page-portrait {
|
.a4page-portrait {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
box-sizing: content-box;
|
box-sizing: content-box;
|
||||||
width: 210mm;
|
width: 210mm;
|
||||||
height: 297mm;
|
height: 297mm;
|
||||||
}
|
}
|
||||||
|
|
||||||
.a4page-landscape {
|
.a4page-landscape {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
box-sizing: content-box;
|
box-sizing: content-box;
|
||||||
height: 210mm;
|
height: 210mm;
|
||||||
width: 297mm;
|
width: 297mm;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* END OF CLASSES */
|
/* END OF CLASSES */
|
||||||
|
|
||||||
/* PHONE */
|
/* PHONE */
|
||||||
@media (max-width: 850px) {
|
@media (max-width: 850px) {
|
||||||
.a4page-portrait {
|
.a4page-portrait {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
/* fill mobile width */
|
/* fill mobile width */
|
||||||
height: fit-content;
|
height: fit-content;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
/* center horizontally */
|
/* center horizontally */
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.a4page-landscape {
|
.a4page-landscape {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
/* fill mobile width */
|
/* fill mobile width */
|
||||||
height: fit-content;
|
height: fit-content;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
/* center horizontally */
|
/* center horizontally */
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 600px) {
|
@media (max-width: 600px) {
|
||||||
.a5page-portrait {
|
.a5page-portrait {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: fit-content;
|
height: fit-content;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.a5page-landscape {
|
.a5page-landscape {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: fit-content;
|
height: fit-content;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.tl {
|
.tl {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.tr {
|
.tr {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 0;
|
top: 0;
|
||||||
right: 0;
|
right: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bl {
|
.bl {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 0;
|
bottom: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.br {
|
.br {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 0;
|
bottom: 0;
|
||||||
right: 0;
|
right: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.background {
|
.background {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
}
|
}
|
||||||
|
|
||||||
.halftone {
|
.halftone {
|
||||||
--dot_size: 4px;
|
--dot_size: 4px;
|
||||||
--bg_size: 12px;
|
--bg_size: 12px;
|
||||||
--bg_pos: calc(var(--bg_size) / 2);
|
--bg_pos: calc(var(--bg_size) / 2);
|
||||||
--blur: 0%;
|
--blur: 0%;
|
||||||
|
|
||||||
background-color: var(--bg_secondary);
|
background-color: var(--bg_secondary);
|
||||||
background-image:
|
background-image:
|
||||||
linear-gradient(to top, transparent 0%, var(--bg_primary) 100%),
|
linear-gradient(to top, transparent 0%, var(--bg_primary) 100%),
|
||||||
radial-gradient(
|
radial-gradient(
|
||||||
circle at center,
|
circle at center,
|
||||||
var(--bg_tertiary) var(--dot_size),
|
var(--bg_tertiary) var(--dot_size),
|
||||||
transparent var(--blur)
|
transparent var(--blur)
|
||||||
);
|
);
|
||||||
background-size:
|
background-size:
|
||||||
100% 100%,
|
100% 100%,
|
||||||
var(--bg_size) var(--bg_size);
|
var(--bg_size) var(--bg_size);
|
||||||
background-position:
|
background-position:
|
||||||
0 0,
|
0 0,
|
||||||
0 0;
|
0 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,128 +5,128 @@ const clock = ref("");
|
|||||||
let timer;
|
let timer;
|
||||||
|
|
||||||
function updateClock() {
|
function updateClock() {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
clock.value = now.toLocaleDateString("en-US", {
|
clock.value = now.toLocaleDateString("en-US", {
|
||||||
weekday: "short",
|
weekday: "short",
|
||||||
month: "short",
|
month: "short",
|
||||||
day: "numeric",
|
day: "numeric",
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
updateClock();
|
updateClock();
|
||||||
timer = setInterval(updateClock, 1000);
|
timer = setInterval(updateClock, 1000);
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
});
|
});
|
||||||
|
|
||||||
const user = "visitor";
|
const user = "visitor";
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<footer class="waybar">
|
<footer class="waybar">
|
||||||
<div class="modules-left">
|
<div class="modules-left">
|
||||||
<span class="workspace active">ツ</span>
|
<span class="workspace active">ツ</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="modules-right">
|
<div class="modules-right">
|
||||||
<span class="module greeting">Hi, {{ user }}!</span>
|
<span class="module greeting">Hi, {{ user }}!</span>
|
||||||
<span class="module cpu hide-sm">CPU 3%</span>
|
<span class="module cpu hide-sm">CPU 3%</span>
|
||||||
<span class="module mem hide-sm">MEM 42%</span>
|
<span class="module mem hide-sm">MEM 42%</span>
|
||||||
<span class="module disk hide-sm">DISK 67%</span>
|
<span class="module disk hide-sm">DISK 67%</span>
|
||||||
<span class="module network hide-sm">↑ 12K ↓ 84K</span>
|
<span class="module network hide-sm">↑ 12K ↓ 84K</span>
|
||||||
<span class="module battery hide-sm">BAT 98%</span>
|
<span class="module battery hide-sm">BAT 98%</span>
|
||||||
<span class="module clock">{{ clock }}</span>
|
<span class="module clock">{{ clock }}</span>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.waybar {
|
.waybar {
|
||||||
font-family: "URWGothic-Book", monospace;
|
font-family: "URWGothic-Book", monospace;
|
||||||
background-color: var(--bg_primary);
|
background-color: var(--bg_primary);
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 4px 8px;
|
padding: 4px 8px;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
min-height: 36px;
|
min-height: 36px;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.modules-left {
|
.modules-left {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.workspace {
|
.workspace {
|
||||||
background: var(--quaternary);
|
background: var(--quaternary);
|
||||||
border: none;
|
border: none;
|
||||||
border-bottom: 2px solid var(--secondary);
|
border-bottom: 2px solid var(--secondary);
|
||||||
color: var(--secondary);
|
color: var(--secondary);
|
||||||
padding: 2px 10px;
|
padding: 2px 10px;
|
||||||
font-family: inherit;
|
font-family: inherit;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.modules-right {
|
.modules-right {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.module {
|
.module {
|
||||||
padding: 2px 12px;
|
padding: 2px 12px;
|
||||||
border-left: 1px solid var(--tertiary);
|
border-left: 1px solid var(--tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.module:first-child {
|
.module:first-child {
|
||||||
border-left: none;
|
border-left: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.greeting {
|
.greeting {
|
||||||
color: var(--secondary);
|
color: var(--secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.clock {
|
.clock {
|
||||||
color: var(--tertiary);
|
color: var(--tertiary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.cpu,
|
.cpu,
|
||||||
.mem,
|
.mem,
|
||||||
.disk {
|
.disk {
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.network {
|
.network {
|
||||||
color: var(--secondary);
|
color: var(--secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.battery {
|
.battery {
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 800px) {
|
@media (max-width: 800px) {
|
||||||
.waybar {
|
.waybar {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
padding: 4px 4px;
|
padding: 4px 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.workspace {
|
.workspace {
|
||||||
padding: 2px 6px;
|
padding: 2px 6px;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.module {
|
.module {
|
||||||
padding: 2px 6px;
|
padding: 2px 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.hide-sm {
|
.hide-sm {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -6,55 +6,55 @@ import { useRoute } from "vue-router";
|
|||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
|
|
||||||
const parentPath = computed(() => {
|
const parentPath = computed(() => {
|
||||||
const segments = route.path.split("/").filter(Boolean);
|
const segments = route.path.split("/").filter(Boolean);
|
||||||
if (segments.length == 1) {
|
if (segments.length == 1) {
|
||||||
return "/";
|
return "/";
|
||||||
} else {
|
} else {
|
||||||
segments.pop();
|
segments.pop();
|
||||||
return segments.length ? "/" + segments.join("/") : null;
|
return segments.length ? "/" + segments.join("/") : null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const faces = [
|
const faces = [
|
||||||
"^_^",
|
"^_^",
|
||||||
"¯\\_(ツ)_/¯",
|
"¯\\_(ツ)_/¯",
|
||||||
"(◕‿◕✿)",
|
"(◕‿◕✿)",
|
||||||
"ಠ_ಠ",
|
"ಠ_ಠ",
|
||||||
"ʘ‿ʘ",
|
"ʘ‿ʘ",
|
||||||
"^̮^",
|
"^̮^",
|
||||||
">_>",
|
">_>",
|
||||||
"¬_¬",
|
"¬_¬",
|
||||||
"˙ ͜ʟ˙",
|
"˙ ͜ʟ˙",
|
||||||
"( ͡° ͜ʖ ͡°)",
|
"( ͡° ͜ʖ ͡°)",
|
||||||
"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
|
"[̲̅$̲̅(̲̅5̲̅)̲̅$̲̅]",
|
||||||
"(ง'̀-'́)ง",
|
"(ง'̀-'́)ง",
|
||||||
"\ (•◡•) /",
|
"\ (•◡•) /",
|
||||||
"( ͡ᵔ ͜ʖ ͡ᵔ )",
|
"( ͡ᵔ ͜ʖ ͡ᵔ )",
|
||||||
"ᕙ(⇀‸↼‶)ᕗ",
|
"ᕙ(⇀‸↼‶)ᕗ",
|
||||||
"⚆ _ ⚆",
|
"⚆ _ ⚆",
|
||||||
"(。◕‿◕。)",
|
"(。◕‿◕。)",
|
||||||
"(╯°□°)╯︵ ʞooqǝɔɐɟ",
|
"(╯°□°)╯︵ ʞooqǝɔɐɟ",
|
||||||
"̿ ̿ ̿'̿'\̵͇̿̿\з=(•_•)=ε/̵͇̿̿/'̿'̿ ̿",
|
"̿ ̿ ̿'̿'\̵͇̿̿\з=(•_•)=ε/̵͇̿̿/'̿'̿ ̿",
|
||||||
"(☞゚ヮ゚)☞ ☜(゚ヮ゚☜)",
|
"(☞゚ヮ゚)☞ ☜(゚ヮ゚☜)",
|
||||||
];
|
];
|
||||||
const faces_string = faces.join(" ");
|
const faces_string = faces.join(" ");
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<nav class="flex flex-row w-full h-fit border border-primary bg-bg_primary">
|
<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">
|
<RouterLink class="bdr-2 bg-bg_primary" v-if="parentPath" :to="parentPath">
|
||||||
<span>UP</span>
|
<span>UP</span>
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<Headline class="border flex-1 max-w-full">
|
<Headline class="border flex-1 max-w-full">
|
||||||
<code class="whitespace-pre">{{ faces_string }}</code>
|
<code class="whitespace-pre">{{ faces_string }}</code>
|
||||||
</Headline>
|
</Headline>
|
||||||
</nav>
|
</nav>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.left {
|
.left {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,57 +1,57 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<img src="/img/borders/utena.png" class="flower tl antirotate" />
|
<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 tr rotate" />
|
||||||
<img src="/img/borders/utena.png" class="flower bl rotate" />
|
<img src="/img/borders/utena.png" class="flower bl rotate" />
|
||||||
<img src="/img/borders/utena.png" class="flower br antirotate" />
|
<img src="/img/borders/utena.png" class="flower br antirotate" />
|
||||||
<slot />
|
<slot />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.container {
|
.container {
|
||||||
position: relative;
|
position: relative;
|
||||||
margin: 100px;
|
margin: 100px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.flower {
|
.flower {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
width: 150px;
|
width: 150px;
|
||||||
}
|
}
|
||||||
.tl {
|
.tl {
|
||||||
top: -80px;
|
top: -80px;
|
||||||
left: -80px;
|
left: -80px;
|
||||||
--start: 0deg;
|
--start: 0deg;
|
||||||
}
|
}
|
||||||
.tr {
|
.tr {
|
||||||
top: -80px;
|
top: -80px;
|
||||||
right: -80px;
|
right: -80px;
|
||||||
--start: 90deg;
|
--start: 90deg;
|
||||||
}
|
}
|
||||||
.bl {
|
.bl {
|
||||||
bottom: -80px;
|
bottom: -80px;
|
||||||
left: -80px;
|
left: -80px;
|
||||||
--start: 180deg;
|
--start: 180deg;
|
||||||
}
|
}
|
||||||
.br {
|
.br {
|
||||||
bottom: -80px;
|
bottom: -80px;
|
||||||
right: -80px;
|
right: -80px;
|
||||||
--start: 270deg;
|
--start: 270deg;
|
||||||
}
|
}
|
||||||
.rotate {
|
.rotate {
|
||||||
animation: spin 3s linear infinite;
|
animation: spin 3s linear infinite;
|
||||||
}
|
}
|
||||||
|
|
||||||
.antirotate {
|
.antirotate {
|
||||||
animation: spin 3s linear infinite reverse;
|
animation: spin 3s linear infinite reverse;
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes spin {
|
@keyframes spin {
|
||||||
from {
|
from {
|
||||||
transform: rotate(var(--start));
|
transform: rotate(var(--start));
|
||||||
}
|
}
|
||||||
to {
|
to {
|
||||||
transform: rotate(calc(var(--start) + 360deg));
|
transform: rotate(calc(var(--start) + 360deg));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ const container = ref(null);
|
|||||||
|
|
||||||
// List of (offset, width)
|
// List of (offset, width)
|
||||||
function generateOffsets(width = 100, step = 10, n = 20) {
|
function generateOffsets(width = 100, step = 10, n = 20) {
|
||||||
return Array.from({ length: n }, (_, i) => ({
|
return Array.from({ length: n }, (_, i) => ({
|
||||||
width,
|
width,
|
||||||
offset: step * i,
|
offset: step * i,
|
||||||
color: getRandomColor(),
|
color: getRandomColor(),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
const offsets = ref(generateOffsets((150, 15, 10)));
|
const offsets = ref(generateOffsets((150, 15, 10)));
|
||||||
let rafId;
|
let rafId;
|
||||||
@@ -18,71 +18,71 @@ let rafId;
|
|||||||
const speed = 0.5; // pixels per frame
|
const speed = 0.5; // pixels per frame
|
||||||
|
|
||||||
function animate() {
|
function animate() {
|
||||||
const ctnr = container.value;
|
const ctnr = container.value;
|
||||||
for (const item of offsets.value) {
|
for (const item of offsets.value) {
|
||||||
const width = Math.max(ctnr.offsetWidth, item.width);
|
const width = Math.max(ctnr.offsetWidth, item.width);
|
||||||
|
|
||||||
console.log(ctnr.offsetWidth);
|
console.log(ctnr.offsetWidth);
|
||||||
|
|
||||||
item.offset -= speed;
|
item.offset -= speed;
|
||||||
if (item.offset <= -width) {
|
if (item.offset <= -width) {
|
||||||
item.color = getRandomColor();
|
item.color = getRandomColor();
|
||||||
item.offset = 0;
|
item.offset = 0;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
rafId = requestAnimationFrame(animate);
|
}
|
||||||
|
rafId = requestAnimationFrame(animate);
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
rafId = requestAnimationFrame(animate);
|
rafId = requestAnimationFrame(animate);
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
cancelAnimationFrame(rafId);
|
cancelAnimationFrame(rafId);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="bg-primary container" ref="container">
|
<div class="bg-primary container" ref="container">
|
||||||
<div :key="index" v-for="(item, index) in offsets">
|
<div :key="index" v-for="(item, index) in offsets">
|
||||||
<div
|
<div
|
||||||
:style="{
|
:style="{
|
||||||
width: item.width + 'px',
|
width: item.width + 'px',
|
||||||
translate: item.offset + 'px',
|
translate: item.offset + 'px',
|
||||||
backgroundColor: item.color,
|
backgroundColor: item.color,
|
||||||
}"
|
}"
|
||||||
class="item item1"
|
class="item item1"
|
||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
:style="{
|
:style="{
|
||||||
width: item.width + 'px',
|
width: item.width + 'px',
|
||||||
right: -item.width + 'px',
|
right: -item.width + 'px',
|
||||||
translate: item.offset + 'px',
|
translate: item.offset + 'px',
|
||||||
backgroundColor: item.color,
|
backgroundColor: item.color,
|
||||||
}"
|
}"
|
||||||
class="item item2"
|
class="item item2"
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.container {
|
.container {
|
||||||
position: relative;
|
position: relative;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
will-change: transform;
|
will-change: transform;
|
||||||
}
|
}
|
||||||
.item {
|
.item {
|
||||||
opacity: 40%;
|
opacity: 40%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
}
|
}
|
||||||
.item1 {
|
.item1 {
|
||||||
left: 0px;
|
left: 0px;
|
||||||
top: 0px;
|
top: 0px;
|
||||||
}
|
}
|
||||||
.item2 {
|
.item2 {
|
||||||
top: 0px;
|
top: 0px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
<script setup></script>
|
<script setup></script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<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"
|
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 />
|
<slot />
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped></style>
|
<style scoped></style>
|
||||||
|
|||||||
@@ -2,30 +2,30 @@
|
|||||||
import { ref } from "vue";
|
import { ref } from "vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
modelValue: {
|
modelValue: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false,
|
default: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const emit = defineEmits(["update:modelValue"]);
|
const emit = defineEmits(["update:modelValue"]);
|
||||||
|
|
||||||
function toggle() {
|
function toggle() {
|
||||||
emit("update:modelValue", !props.modelValue);
|
emit("update:modelValue", !props.modelValue);
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<button
|
<button
|
||||||
@click="toggle"
|
@click="toggle"
|
||||||
class="box-content border-2 border-primary w-20 h-fit rounded-full cursor-pointer"
|
class="box-content border-2 border-primary w-10 h-fit rounded-full cursor-pointer"
|
||||||
:class="[props.modelValue ? 'bg-bg_secondary' : 'bg-bg_primary']"
|
: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
|
<circle class="fill-primary" cx="20" cy="20" r="20" />
|
||||||
viewBox="0 0 40 40"
|
</svg>
|
||||||
class="w-10 h-10 transition-all duration-300 ease-in-out"
|
</button>
|
||||||
:class="[props.modelValue ? 'ml-10' : 'ml-0']"
|
|
||||||
>
|
|
||||||
<circle class="fill-primary" cx="20" cy="20" r="20" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="w-full border-b border-primary pb-2 mb-4">
|
<div class="w-full border-b border-primary pb-0.5">
|
||||||
<h1 class="p-0 m-0">
|
<h1 class="p-0 m-0">
|
||||||
<slot />
|
<slot />
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -12,74 +12,74 @@ let rafId;
|
|||||||
const speed = 0.5; // pixels per frame
|
const speed = 0.5; // pixels per frame
|
||||||
|
|
||||||
function measureWidth() {
|
function measureWidth() {
|
||||||
const ctnr = container.value;
|
const ctnr = container.value;
|
||||||
const it1 = item1.value;
|
const it1 = item1.value;
|
||||||
if (ctnr && it1) {
|
if (ctnr && it1) {
|
||||||
cachedWidth = Math.max(ctnr.offsetWidth, it1.scrollWidth);
|
cachedWidth = Math.max(ctnr.offsetWidth, it1.scrollWidth);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function animate() {
|
function animate() {
|
||||||
const ctnr = container.value;
|
const ctnr = container.value;
|
||||||
if (!ctnr || cachedWidth === 0) {
|
if (!ctnr || cachedWidth === 0) {
|
||||||
rafId = requestAnimationFrame(animate);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
offset -= speed;
|
|
||||||
|
|
||||||
if (offset <= -cachedWidth) {
|
|
||||||
offset += cachedWidth;
|
|
||||||
}
|
|
||||||
|
|
||||||
ctnr.style.transform = `translateX(${offset}px)`;
|
|
||||||
|
|
||||||
rafId = requestAnimationFrame(animate);
|
rafId = requestAnimationFrame(animate);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
offset -= speed;
|
||||||
|
|
||||||
|
if (offset <= -cachedWidth) {
|
||||||
|
offset += cachedWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctnr.style.transform = `translateX(${offset}px)`;
|
||||||
|
|
||||||
|
rafId = requestAnimationFrame(animate);
|
||||||
}
|
}
|
||||||
|
|
||||||
let resizeObserver;
|
let resizeObserver;
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
measureWidth();
|
measureWidth();
|
||||||
rafId = requestAnimationFrame(animate);
|
rafId = requestAnimationFrame(animate);
|
||||||
|
|
||||||
resizeObserver = new ResizeObserver(measureWidth);
|
resizeObserver = new ResizeObserver(measureWidth);
|
||||||
resizeObserver.observe(container.value);
|
resizeObserver.observe(container.value);
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
cancelAnimationFrame(rafId);
|
cancelAnimationFrame(rafId);
|
||||||
resizeObserver?.disconnect();
|
resizeObserver?.disconnect();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="root">
|
<div class="root">
|
||||||
<div class="container" ref="container">
|
<div class="container" ref="container">
|
||||||
<div ref="item1">
|
<div ref="item1">
|
||||||
<slot />
|
<slot />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<slot />
|
<slot />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.root {
|
.root {
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.container {
|
.container {
|
||||||
width: fit-content;
|
width: fit-content;
|
||||||
height: fit-content;
|
height: fit-content;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-auto-flow: column;
|
grid-auto-flow: column;
|
||||||
grid-auto-columns: max-content;
|
grid-auto-columns: max-content;
|
||||||
/* Each column fits its content */
|
/* Each column fits its content */
|
||||||
overflow-x: visible;
|
overflow-x: visible;
|
||||||
will-change: transform;
|
will-change: transform;
|
||||||
gap: 10em;
|
gap: 10em;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -2,38 +2,44 @@
|
|||||||
import { computed } from "vue";
|
import { computed } from "vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
href: { type: String, default: "" },
|
href: { type: String, default: "" },
|
||||||
to: { type: String, default: "" },
|
to: { type: String, default: "" },
|
||||||
target: { type: String, default: undefined },
|
target: { type: String, default: undefined },
|
||||||
rel: { type: String, default: undefined },
|
rel: { type: String, default: undefined },
|
||||||
});
|
});
|
||||||
|
|
||||||
const computedRel = computed(() => {
|
const computedRel = computed(() => {
|
||||||
if (props.rel !== undefined) return props.rel;
|
if (props.rel !== undefined) return props.rel;
|
||||||
if (props.target === "_blank") return "noopener noreferrer";
|
if (props.target === "_blank") return "noopener noreferrer";
|
||||||
return undefined;
|
return undefined;
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<RouterLink v-if="to" :to="to" class="inline-link">
|
<RouterLink v-if="to" :to="to" class="inline-link">
|
||||||
<slot />
|
<slot />
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<a v-else :href="href" :target="target" :rel="computedRel" class="inline-link">
|
<a
|
||||||
<slot />
|
v-else
|
||||||
</a>
|
:href="href"
|
||||||
|
:target="target"
|
||||||
|
:rel="computedRel"
|
||||||
|
class="inline-link"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</a>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.inline-link {
|
.inline-link {
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
transition: color 0.15s ease;
|
transition: color 0.15s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
.inline-link:hover {
|
.inline-link:hover {
|
||||||
color: var(--tertiary);
|
color: var(--tertiary);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -2,37 +2,43 @@
|
|||||||
import { computed } from "vue";
|
import { computed } from "vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
href: { type: String, default: "" },
|
href: { type: String, default: "" },
|
||||||
to: { type: String, default: "" },
|
to: { type: String, default: "" },
|
||||||
target: { type: String, default: undefined },
|
target: { type: String, default: undefined },
|
||||||
rel: { type: String, default: undefined },
|
rel: { type: String, default: undefined },
|
||||||
bare: { type: Boolean, default: false },
|
bare: { type: Boolean, default: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
const computedRel = computed(() => {
|
const computedRel = computed(() => {
|
||||||
if (props.rel !== undefined) return props.rel;
|
if (props.rel !== undefined) return props.rel;
|
||||||
if (props.target === "_blank") return "noopener noreferrer";
|
if (props.target === "_blank") return "noopener noreferrer";
|
||||||
return undefined;
|
return undefined;
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<RouterLink v-if="to" :to="to" :class="{ link: !bare }">
|
<RouterLink v-if="to" :to="to" :class="{ link: !bare }">
|
||||||
<slot />
|
<slot />
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<a v-else :href="href" :target="target" :rel="computedRel" :class="{ link: !bare }">
|
<a
|
||||||
<slot />
|
v-else
|
||||||
</a>
|
:href="href"
|
||||||
|
:target="target"
|
||||||
|
:rel="computedRel"
|
||||||
|
:class="{ link: !bare }"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</a>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.link {
|
.link {
|
||||||
color: var(--primary);
|
color: var(--primary);
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
transition: color 0.15s ease;
|
transition: color 0.15s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
.link:hover {
|
.link:hover {
|
||||||
color: var(--tertiary);
|
color: var(--tertiary);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<template>
|
<template>
|
||||||
<p class="p-1">
|
<p class="p-1">
|
||||||
<slot />
|
<slot />
|
||||||
</p>
|
</p>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -3,35 +3,36 @@ import { ref } from "vue";
|
|||||||
import ToggleButton from "@/components/input/ToggleButton.vue";
|
import ToggleButton from "@/components/input/ToggleButton.vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
modelValue: {
|
modelValue: {
|
||||||
type: Boolean,
|
type: Boolean,
|
||||||
default: false,
|
default: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const emit = defineEmits(["update:modelValue"]);
|
const emit = defineEmits(["update:modelValue"]);
|
||||||
const toggleButtonRef = ref(null);
|
const toggleButtonRef = ref(null);
|
||||||
|
|
||||||
const updateValue = (newValue) => {
|
const updateValue = (newValue) => {
|
||||||
emit("update:modelValue", newValue);
|
emit("update:modelValue", newValue);
|
||||||
};
|
};
|
||||||
const handleClick = () => {
|
const handleClick = () => {
|
||||||
toggleButtonRef.value?.$el?.click();
|
toggleButtonRef.value?.$el?.click();
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<div
|
<div
|
||||||
class="w-full border-b border-primary cursor-pointer"
|
class="w-full border-b border-primary cursor-pointer"
|
||||||
@click="handleClick"
|
@click="handleClick"
|
||||||
>
|
>
|
||||||
<h1 class="pl-2 m-0">
|
<h3 class="pl-2 m-0">
|
||||||
<slot />
|
<slot />
|
||||||
</h1>
|
</h3>
|
||||||
<ToggleButton
|
<ToggleButton
|
||||||
class="pointer-events-none"
|
class="pointer-events-none"
|
||||||
:model-value="props.modelValue"
|
:model-value="props.modelValue"
|
||||||
@update:model-value="updateValue"
|
@update:model-value="updateValue"
|
||||||
ref="toggleButtonRef"
|
@click.stop
|
||||||
/>
|
ref="toggleButtonRef"
|
||||||
</div>
|
/>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
<template>
|
<template>
|
||||||
<div ref="container" @mouseenter="onMouseEnter" @mouseleave="onMouseLeave" class="overflow-y-auto">
|
<div
|
||||||
<slot />
|
ref="container"
|
||||||
</div>
|
@mouseenter="onMouseEnter"
|
||||||
|
@mouseleave="onMouseLeave"
|
||||||
|
class="overflow-y-auto"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
@@ -20,89 +25,89 @@ let pauseTimeoutId = null;
|
|||||||
let cachedScrollHeight = 0;
|
let cachedScrollHeight = 0;
|
||||||
|
|
||||||
function measureScrollHeight() {
|
function measureScrollHeight() {
|
||||||
const el = container.value;
|
const el = container.value;
|
||||||
if (el) cachedScrollHeight = el.scrollHeight;
|
if (el) cachedScrollHeight = el.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
function stopLoop() {
|
function stopLoop() {
|
||||||
if (rafId !== null) {
|
if (rafId !== null) {
|
||||||
cancelAnimationFrame(rafId);
|
cancelAnimationFrame(rafId);
|
||||||
rafId = null;
|
rafId = null;
|
||||||
}
|
}
|
||||||
if (pauseTimeoutId !== null) {
|
if (pauseTimeoutId !== null) {
|
||||||
clearTimeout(pauseTimeoutId);
|
clearTimeout(pauseTimeoutId);
|
||||||
pauseTimeoutId = null;
|
pauseTimeoutId = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function startLoop() {
|
function startLoop() {
|
||||||
stopLoop();
|
stopLoop();
|
||||||
rafId = requestAnimationFrame(tick);
|
rafId = requestAnimationFrame(tick);
|
||||||
}
|
}
|
||||||
|
|
||||||
function onMouseEnter() {
|
function onMouseEnter() {
|
||||||
hovered = true;
|
hovered = true;
|
||||||
stopLoop();
|
stopLoop();
|
||||||
}
|
}
|
||||||
|
|
||||||
function onMouseLeave() {
|
function onMouseLeave() {
|
||||||
hovered = false;
|
hovered = false;
|
||||||
const el = container.value;
|
const el = container.value;
|
||||||
if (el && cachedScrollHeight > 0) {
|
if (el && cachedScrollHeight > 0) {
|
||||||
pos = el.scrollTop / cachedScrollHeight;
|
pos = el.scrollTop / cachedScrollHeight;
|
||||||
}
|
}
|
||||||
startLoop();
|
startLoop();
|
||||||
}
|
}
|
||||||
|
|
||||||
function schedulePause(callback) {
|
function schedulePause(callback) {
|
||||||
stopLoop();
|
stopLoop();
|
||||||
pauseTimeoutId = setTimeout(callback, PAUSE);
|
pauseTimeoutId = setTimeout(callback, PAUSE);
|
||||||
}
|
}
|
||||||
|
|
||||||
function tick() {
|
function tick() {
|
||||||
rafId = null;
|
rafId = null;
|
||||||
const el = container.value;
|
const el = container.value;
|
||||||
if (hovered) return;
|
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;
|
|
||||||
|
|
||||||
|
if (!el || cachedScrollHeight === 0) {
|
||||||
rafId = requestAnimationFrame(tick);
|
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;
|
let resizeObserver;
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
measureScrollHeight();
|
measureScrollHeight();
|
||||||
schedulePause(startLoop);
|
schedulePause(startLoop);
|
||||||
|
|
||||||
resizeObserver = new ResizeObserver(measureScrollHeight);
|
resizeObserver = new ResizeObserver(measureScrollHeight);
|
||||||
resizeObserver.observe(container.value);
|
resizeObserver.observe(container.value);
|
||||||
});
|
});
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
stopLoop();
|
stopLoop();
|
||||||
resizeObserver?.disconnect();
|
resizeObserver?.disconnect();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -19,210 +19,205 @@ const SCROLL_THRESHOLD = 100;
|
|||||||
let resizeObserver = null;
|
let resizeObserver = null;
|
||||||
|
|
||||||
function scrollToBottom() {
|
function scrollToBottom() {
|
||||||
if (messagesContainer.value) {
|
if (messagesContainer.value) {
|
||||||
messagesContainer.value.scrollTop =
|
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
|
||||||
messagesContainer.value.scrollHeight;
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function scrollToBottomIfNear() {
|
function scrollToBottomIfNear() {
|
||||||
if (isNearBottom.value) {
|
if (isNearBottom.value) {
|
||||||
scrollToBottom();
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function onScroll() {
|
function onScroll() {
|
||||||
if (!messagesContainer.value) return;
|
if (!messagesContainer.value) return;
|
||||||
const { scrollHeight, scrollTop, clientHeight } = messagesContainer.value;
|
const { scrollHeight, scrollTop, clientHeight } = messagesContainer.value;
|
||||||
isNearBottom.value =
|
isNearBottom.value =
|
||||||
scrollHeight - scrollTop - clientHeight < SCROLL_THRESHOLD;
|
scrollHeight - scrollTop - clientHeight < SCROLL_THRESHOLD;
|
||||||
}
|
}
|
||||||
|
|
||||||
function goToBottom() {
|
function goToBottom() {
|
||||||
isNearBottom.value = true;
|
isNearBottom.value = true;
|
||||||
scrollToBottom();
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => messages.value.length,
|
() => messages.value.length,
|
||||||
() => {
|
() => {
|
||||||
nextTick(scrollToBottomIfNear);
|
nextTick(scrollToBottomIfNear);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
function sendMessage() {
|
function sendMessage() {
|
||||||
const text = messageInput.value.trim();
|
const text = messageInput.value.trim();
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
isNearBottom.value = true;
|
isNearBottom.value = true;
|
||||||
messagesStore.sendMessage(text);
|
messagesStore.sendMessage(text);
|
||||||
messageInput.value = "";
|
messageInput.value = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onFileSelected(e) {
|
async function onFileSelected(e) {
|
||||||
const file = e.target.files[0];
|
const file = e.target.files[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
isNearBottom.value = true;
|
isNearBottom.value = true;
|
||||||
await messagesStore.uploadAndSendFile(file);
|
await messagesStore.uploadAndSendFile(file);
|
||||||
fileInput.value.value = "";
|
fileInput.value.value = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function isImageUrl(url) {
|
function isImageUrl(url) {
|
||||||
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
|
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isVideoUrl(url) {
|
function isVideoUrl(url) {
|
||||||
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isSafeFileUrl(url) {
|
function isSafeFileUrl(url) {
|
||||||
return typeof url === "string" && url.startsWith("/uploads/");
|
return typeof url === "string" && url.startsWith("/uploads/");
|
||||||
}
|
}
|
||||||
|
|
||||||
const urlRegex = /(https?:\/\/[^\s<]+)/g;
|
const urlRegex = /(https?:\/\/[^\s<]+)/g;
|
||||||
|
|
||||||
function parseMessageParts(text) {
|
function parseMessageParts(text) {
|
||||||
const parts = [];
|
const parts = [];
|
||||||
let lastIndex = 0;
|
let lastIndex = 0;
|
||||||
let match;
|
let match;
|
||||||
while ((match = urlRegex.exec(text)) !== null) {
|
while ((match = urlRegex.exec(text)) !== null) {
|
||||||
if (match.index > lastIndex) {
|
if (match.index > lastIndex) {
|
||||||
parts.push({
|
parts.push({
|
||||||
type: "text",
|
type: "text",
|
||||||
value: text.slice(lastIndex, match.index),
|
value: text.slice(lastIndex, match.index),
|
||||||
});
|
});
|
||||||
}
|
|
||||||
parts.push({ type: "link", value: match[1] });
|
|
||||||
lastIndex = urlRegex.lastIndex;
|
|
||||||
}
|
}
|
||||||
if (lastIndex < text.length) {
|
parts.push({ type: "link", value: match[1] });
|
||||||
parts.push({ type: "text", value: text.slice(lastIndex) });
|
lastIndex = urlRegex.lastIndex;
|
||||||
}
|
}
|
||||||
return parts;
|
if (lastIndex < text.length) {
|
||||||
|
parts.push({ type: "text", value: text.slice(lastIndex) });
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
messagesStore.connect();
|
messagesStore.connect();
|
||||||
|
|
||||||
if (messagesContainer.value) {
|
if (messagesContainer.value) {
|
||||||
messagesContainer.value.addEventListener("scroll", onScroll, {
|
messagesContainer.value.addEventListener("scroll", onScroll, {
|
||||||
passive: true,
|
passive: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (messagesInner.value) {
|
if (messagesInner.value) {
|
||||||
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
|
resizeObserver = new ResizeObserver(scrollToBottomIfNear);
|
||||||
resizeObserver.observe(messagesInner.value);
|
resizeObserver.observe(messagesInner.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
scrollToBottom();
|
scrollToBottom();
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
messagesStore.disconnect();
|
messagesStore.disconnect();
|
||||||
|
|
||||||
if (messagesContainer.value) {
|
if (messagesContainer.value) {
|
||||||
messagesContainer.value.removeEventListener("scroll", onScroll);
|
messagesContainer.value.removeEventListener("scroll", onScroll);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (resizeObserver) {
|
if (resizeObserver) {
|
||||||
resizeObserver.disconnect();
|
resizeObserver.disconnect();
|
||||||
resizeObserver = null;
|
resizeObserver = null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="chat-root flex-col flex min-h-0">
|
<div class="chat-root flex-col flex min-h-0">
|
||||||
<Header>Chat</Header>
|
<Header>Chat</Header>
|
||||||
<div
|
<div
|
||||||
ref="messagesContainer"
|
ref="messagesContainer"
|
||||||
class="flex flex-col flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-2 min-w-0"
|
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">
|
<span class="text-tertiary">{{ message.authorId }}:</span>
|
||||||
<p
|
<template
|
||||||
v-for="message in messages"
|
v-for="(part, i) in parseMessageParts(message.text || '')"
|
||||||
:key="message.id"
|
:key="i"
|
||||||
class="break-words min-w-0 w-full"
|
>
|
||||||
>
|
<Link
|
||||||
<span class="text-tertiary">{{ message.authorId }}:</span>
|
v-if="part.type === 'link'"
|
||||||
<template
|
bare
|
||||||
v-for="(part, i) in parseMessageParts(
|
:href="part.value"
|
||||||
message.text || '',
|
target="_blank"
|
||||||
)"
|
class="text-primary underline break-all"
|
||||||
:key="i"
|
>{{ part.value }}</Link
|
||||||
>
|
>
|
||||||
<Link
|
<span v-else>{{ part.value }}</span>
|
||||||
v-if="part.type === 'link'"
|
</template>
|
||||||
bare
|
<template v-if="message.fileUrl && isSafeFileUrl(message.fileUrl)">
|
||||||
:href="part.value"
|
<img
|
||||||
target="_blank"
|
v-if="isImageUrl(message.fileUrl)"
|
||||||
class="text-primary underline break-all"
|
:src="message.fileUrl"
|
||||||
>{{ part.value }}</Link
|
alt="Uploaded image"
|
||||||
>
|
loading="lazy"
|
||||||
<span v-else>{{ part.value }}</span>
|
class="w-full max-w-full rounded block"
|
||||||
</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"
|
|
||||||
/>
|
/>
|
||||||
<input
|
<video
|
||||||
ref="fileInput"
|
v-else-if="isVideoUrl(message.fileUrl)"
|
||||||
type="file"
|
:src="message.fileUrl"
|
||||||
class="hidden"
|
controls
|
||||||
@change="onFileSelected"
|
preload="none"
|
||||||
|
class="w-full max-w-full max-h-48 rounded block"
|
||||||
/>
|
/>
|
||||||
<div class="flex gap-2">
|
<Link
|
||||||
<Button class="flex-1" @click="sendMessage">Send</Button>
|
v-else
|
||||||
<Button
|
bare
|
||||||
v-if="authStore.user.admin"
|
:href="message.fileUrl"
|
||||||
class="flex-1"
|
target="_blank"
|
||||||
@click="fileInput.click()"
|
class="underline break-all"
|
||||||
>Attach</Button
|
>{{ message.fileUrl.split("/").pop() }}</Link
|
||||||
>
|
>
|
||||||
<Button v-if="!isNearBottom" class="flex-1" @click="goToBottom"
|
</template>
|
||||||
>Bottom</Button
|
</p>
|
||||||
>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</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>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@media (max-width: 850px) {
|
@media (max-width: 850px) {
|
||||||
.chat-root {
|
.chat-root {
|
||||||
max-height: none;
|
max-height: none;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -9,37 +9,42 @@ const { gitFeed: feed, loaded } = storeToRefs(homeData);
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col text-center min-h-0 h-full overflow-x-hidden">
|
<div class="flex flex-col text-center min-h-0 h-full overflow-x-hidden">
|
||||||
<Header class="text-left">Commits</Header>
|
<Header class="text-left">Commits</Header>
|
||||||
|
|
||||||
<div v-if="!loaded" class="flex-1 overflow-y-auto">
|
<div v-if="!loaded" class="flex-1 overflow-y-auto">
|
||||||
<p>Loading latest activity...</p>
|
<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>
|
</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>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.avatar {
|
.avatar {
|
||||||
max-width: 200px;
|
max-width: 200px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: auto;
|
height: auto;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -4,70 +4,66 @@ import Link from "@/components/text/Link.vue";
|
|||||||
import ToggleHeader from "@/components/text/ToggleHeader.vue";
|
import ToggleHeader from "@/components/text/ToggleHeader.vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
items: {
|
items: {
|
||||||
type: Array,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
variant: {
|
variant: {
|
||||||
type: String,
|
type: String,
|
||||||
default: "list",
|
default: "list",
|
||||||
},
|
},
|
||||||
title: {
|
title: {
|
||||||
type: String,
|
type: String,
|
||||||
default: "",
|
default: "",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const show = ref(false);
|
const show = ref(false);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="title" class="h-fit w-full">
|
<div v-if="title" class="h-fit w-full">
|
||||||
<ToggleHeader v-model="show" class="justify-between flex">
|
<ToggleHeader v-model="show" class="justify-between flex items-center">
|
||||||
{{ title }}
|
{{ title }}
|
||||||
</ToggleHeader>
|
</ToggleHeader>
|
||||||
<template v-if="show">
|
<template v-if="show">
|
||||||
<Link
|
<Link
|
||||||
v-if="variant === 'list'"
|
v-if="variant === 'list'"
|
||||||
v-for="(item, i) in items"
|
v-for="(item, i) in items"
|
||||||
:key="i"
|
:key="i"
|
||||||
:href="item.link"
|
:href="item.link"
|
||||||
>
|
>
|
||||||
<p class="bdr-2 bg-bg_tertiary">{{ item.name }}</p>
|
<p class="bdr-2 bg-bg_tertiary">{{ item.name }}</p>
|
||||||
</Link>
|
</Link>
|
||||||
<table class="w-full" v-else>
|
<table class="w-full" v-else>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="item in items" :key="item.id">
|
<tr v-for="item in items" :key="item.id">
|
||||||
<th>{{ item.type }}</th>
|
<th>{{ item.type }}</th>
|
||||||
<td v-if="item.link">
|
<td v-if="item.link">
|
||||||
<Link :href="item.link">{{ item.name }}</Link>
|
<Link :href="item.link">{{ item.name }}</Link>
|
||||||
</td>
|
</td>
|
||||||
<td v-else>{{ item.name }}</td>
|
<td v-else>{{ item.name }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</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>
|
||||||
|
</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>
|
</template>
|
||||||
|
|||||||
@@ -6,19 +6,19 @@ import DOMPurify from "dompurify";
|
|||||||
const mdIt = MarkdownIt().use(katex);
|
const mdIt = MarkdownIt().use(katex);
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
source: String,
|
source: String,
|
||||||
});
|
});
|
||||||
|
|
||||||
function renderMarkdown(source) {
|
function renderMarkdown(source) {
|
||||||
return DOMPurify.sanitize(mdIt.render(source));
|
return DOMPurify.sanitize(mdIt.render(source));
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div
|
<div
|
||||||
v-html="renderMarkdown(props.source)"
|
v-html="renderMarkdown(props.source)"
|
||||||
class="flex flex-col items-center"
|
class="flex flex-col items-center"
|
||||||
></div>
|
></div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
@@ -1,93 +1,92 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import Button from "@/components/input/Button.vue";
|
import Button from "@/components/input/Button.vue";
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<audio/>
|
<audio />
|
||||||
<div class="musicPlayerGrid">
|
<div class="musicPlayerGrid">
|
||||||
<div class="album_cover">
|
<div class="album_cover">
|
||||||
<img src="/img/Untitled.png" alt=""></img>
|
<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>
|
</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>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.musicPlayerGrid {
|
.musicPlayerGrid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-gap: 5px;
|
grid-gap: 5px;
|
||||||
grid-template-rows: repeat(4, 1fr);
|
grid-template-rows: repeat(4, 1fr);
|
||||||
background-color: blue;
|
background-color: blue;
|
||||||
align-items: stretch; /* rows (block axis) */
|
align-items: stretch; /* rows (block axis) */
|
||||||
justify-items: stretch; /* columns (inline axis) */
|
justify-items: stretch; /* columns (inline axis) */
|
||||||
padding: 5px;
|
padding: 5px;
|
||||||
}
|
}
|
||||||
img {
|
img {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.album_cover {
|
.album_cover {
|
||||||
grid-row: 1 / span 3;
|
grid-row: 1 / span 3;
|
||||||
background-color: grey;
|
background-color: grey;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.controls {
|
.controls {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
grid-row: 4 / span 1;
|
grid-row: 4 / span 1;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-rows: repeat(4, 1fr);
|
grid-template-rows: repeat(4, 1fr);
|
||||||
grid-gap: 5px;
|
grid-gap: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.sliders {
|
.sliders {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(2, 1fr);
|
grid-template-columns: repeat(2, 1fr);
|
||||||
grid-gap: 5px;
|
grid-gap: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.timeline {
|
.timeline {
|
||||||
grid-column: 1;
|
grid-column: 1;
|
||||||
background-color: white;
|
background-color: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.volume {
|
.volume {
|
||||||
grid-column: 2;
|
grid-column: 2;
|
||||||
background-color: white;
|
background-color: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.buttons {
|
.buttons {
|
||||||
background-color: black;
|
background-color: black;
|
||||||
grid-row: 2 / -1;
|
grid-row: 2 / -1;
|
||||||
|
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(4, 1fr);
|
grid-template-columns: repeat(4, 1fr);
|
||||||
grid-gap: 5px;
|
grid-gap: 5px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.rewind {
|
.rewind {
|
||||||
grid-column: 1;
|
grid-column: 1;
|
||||||
background-color: grey;
|
background-color: grey;
|
||||||
}
|
}
|
||||||
.fastforward {
|
.fastforward {
|
||||||
grid-column: 4;
|
grid-column: 4;
|
||||||
background-color: grey;
|
background-color: grey;
|
||||||
}
|
}
|
||||||
.playPause {
|
.playPause {
|
||||||
grid-column: 2/span 2;
|
grid-column: 2 / span 2;
|
||||||
background-color: grey;
|
background-color: grey;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -2,42 +2,42 @@
|
|||||||
import { computed } from "vue";
|
import { computed } from "vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
objArr: {
|
objArr: {
|
||||||
type: Array,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const resolvedColumns = computed(() => {
|
const resolvedColumns = computed(() => {
|
||||||
const keys = new Set();
|
const keys = new Set();
|
||||||
|
|
||||||
for (const obj of props.objArr) {
|
for (const obj of props.objArr) {
|
||||||
Object.keys(obj).forEach((key) => keys.add(key));
|
Object.keys(obj).forEach((key) => keys.add(key));
|
||||||
}
|
}
|
||||||
|
|
||||||
return Array.from(keys).map((key) => ({
|
return Array.from(keys).map((key) => ({
|
||||||
key,
|
key,
|
||||||
label: key,
|
label: key,
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th v-for="col in resolvedColumns" :key="col.key">
|
<th v-for="col in resolvedColumns" :key="col.key">
|
||||||
{{ col.label }}
|
{{ col.label }}
|
||||||
</th>
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="(row, rowIndex) in objArr" :key="rowIndex">
|
<tr v-for="(row, rowIndex) in objArr" :key="rowIndex">
|
||||||
<td v-for="col in resolvedColumns" :key="col.key">
|
<td v-for="col in resolvedColumns" :key="col.key">
|
||||||
{{ row[col.key] ?? "" }}
|
{{ row[col.key] ?? "" }}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
<template>
|
<template>
|
||||||
<div v-if="streamLive" class="overflow-auto">
|
<div v-if="streamLive" class="overflow-auto">
|
||||||
<Header>Radio</Header>
|
<Header>Radio</Header>
|
||||||
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
||||||
<audio controls :src="streamUrl" ref="audio"></audio>
|
<audio controls :src="streamUrl" ref="audio"></audio>
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="overflow-auto">
|
<div v-else class="overflow-auto">
|
||||||
<Header>Radio</Header>
|
<Header>Radio</Header>
|
||||||
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
<img src="/img/tmpen31z3pe.PNG" alt="Radio" width="176" height="177" />
|
||||||
<div class="m-1 text-center">
|
<div class="m-1 text-center">
|
||||||
<p>Radio is offline. Message for info!</p>
|
<p>Radio is offline. Message for info!</p>
|
||||||
<Button class="w-full" @click="checkStream()">Check Stream</Button>
|
<Button class="w-full" @click="checkStream()">Check Stream</Button>
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
@@ -25,32 +25,32 @@ const streamLive = ref(false);
|
|||||||
const audio = useTemplateRef("audio");
|
const audio = useTemplateRef("audio");
|
||||||
|
|
||||||
async function checkStream() {
|
async function checkStream() {
|
||||||
try {
|
try {
|
||||||
await axios.head("/radio/stream");
|
await axios.head("/radio/stream");
|
||||||
if (!streamLive.value) {
|
if (!streamLive.value) {
|
||||||
streamLive.value = true;
|
streamLive.value = true;
|
||||||
streamUrl.value = "/radio/stream";
|
streamUrl.value = "/radio/stream";
|
||||||
await nextTick();
|
await nextTick();
|
||||||
if (audio.value) {
|
if (audio.value) {
|
||||||
audio.value.load();
|
audio.value.load();
|
||||||
audio.value.volume = 0.2;
|
audio.value.volume = 0.2;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
streamLive.value = false;
|
|
||||||
}
|
}
|
||||||
|
} catch (err) {
|
||||||
|
streamLive.value = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
checkStream();
|
checkStream();
|
||||||
setInterval(checkStream, 120000);
|
setInterval(checkStream, 120000);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
img {
|
img {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-height: 150px;
|
max-height: 150px;
|
||||||
object-fit: cover;
|
object-fit: cover;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -2,22 +2,22 @@
|
|||||||
import { computed } from "vue";
|
import { computed } from "vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
linkArr: {
|
linkArr: {
|
||||||
type: Array,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const keys = ["name", "link"];
|
const keys = ["name", "link"];
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<RouterLink
|
<RouterLink
|
||||||
class="bdr-2 bg-bg_primary"
|
class="bdr-2 bg-bg_primary"
|
||||||
v-for="(row, rowIndex) in linkArr"
|
v-for="(row, rowIndex) in linkArr"
|
||||||
:key="rowIndex"
|
:key="rowIndex"
|
||||||
:to="row.link"
|
:to="row.link"
|
||||||
>
|
>
|
||||||
{{ row.name }}
|
{{ row.name }}
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -3,14 +3,14 @@ import { ref, computed, onMounted, onUnmounted } from "vue";
|
|||||||
import Header from "@/components/text/Header.vue";
|
import Header from "@/components/text/Header.vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
images: {
|
images: {
|
||||||
type: Array,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
interval: {
|
interval: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 10000,
|
default: 10000,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const currentIndex = ref(0);
|
const currentIndex = ref(0);
|
||||||
@@ -20,58 +20,58 @@ const currentUrl = computed(() => props.images[currentIndex.value].url);
|
|||||||
let nextId;
|
let nextId;
|
||||||
|
|
||||||
function nextImage() {
|
function nextImage() {
|
||||||
clearTimeout(nextId);
|
clearTimeout(nextId);
|
||||||
currentIndex.value = (currentIndex.value + 1) % props.images.length;
|
currentIndex.value = (currentIndex.value + 1) % props.images.length;
|
||||||
nextId = setTimeout(nextImage, props.interval);
|
nextId = setTimeout(nextImage, props.interval);
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
nextId = setTimeout(nextImage, props.interval);
|
nextId = setTimeout(nextImage, props.interval);
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
clearTimeout(nextId);
|
clearTimeout(nextId);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="slideshow-wrapper">
|
<div class="slideshow-wrapper">
|
||||||
<Transition name="fade">
|
<Transition name="fade">
|
||||||
<div class="image-viewer" @click="nextImage" :key="currentIndex">
|
<div class="image-viewer" @click="nextImage" :key="currentIndex">
|
||||||
<Header v-if="currentComment">
|
<Header v-if="currentComment">
|
||||||
{{ currentComment }}
|
{{ currentComment }}
|
||||||
</Header>
|
</Header>
|
||||||
<img :src="currentUrl" alt="Image Viewer" fetchpriority="high" />
|
<img :src="currentUrl" alt="Image Viewer" fetchpriority="high" />
|
||||||
</div>
|
</div>
|
||||||
</Transition>
|
</Transition>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.slideshow-wrapper {
|
.slideshow-wrapper {
|
||||||
display: grid;
|
display: grid;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.image-viewer {
|
.image-viewer {
|
||||||
grid-area: 1 / 1;
|
grid-area: 1 / 1;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
img {
|
img {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
object-fit: cover;
|
object-fit: cover;
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.fade-enter-active,
|
.fade-enter-active,
|
||||||
.fade-leave-active {
|
.fade-leave-active {
|
||||||
transition: opacity 0.5s ease;
|
transition: opacity 0.5s ease;
|
||||||
}
|
}
|
||||||
.fade-enter-from,
|
.fade-enter-from,
|
||||||
.fade-leave-to {
|
.fade-leave-to {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -8,14 +8,14 @@ const day = ref("");
|
|||||||
const month = ref("");
|
const month = ref("");
|
||||||
|
|
||||||
function updateDateTime() {
|
function updateDateTime() {
|
||||||
const date = new Date();
|
const date = new Date();
|
||||||
day.value = date.getDate();
|
day.value = date.getDate();
|
||||||
time.value = date.toLocaleTimeString("en-GB", {
|
time.value = date.toLocaleTimeString("en-GB", {
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
});
|
});
|
||||||
weekday.value = date.toLocaleDateString("en-GB", { weekday: "long" });
|
weekday.value = date.toLocaleDateString("en-GB", { weekday: "long" });
|
||||||
month.value = date.toLocaleDateString("en-GB", { month: "long" });
|
month.value = date.toLocaleDateString("en-GB", { month: "long" });
|
||||||
}
|
}
|
||||||
|
|
||||||
updateDateTime();
|
updateDateTime();
|
||||||
@@ -24,15 +24,15 @@ setInterval(updateDateTime, 60000);
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col">
|
<div class="flex flex-col">
|
||||||
<Header>{{ weekday }} {{ day }}, {{ month }}</Header>
|
<Header>{{ weekday }} {{ day }}, {{ month }}</Header>
|
||||||
<h1>{{ time }}</h1>
|
<h1>{{ time }}</h1>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
div {
|
div {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 4px;
|
padding: 4px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -18,109 +18,109 @@ const seconds = ref(0);
|
|||||||
const audio = new Audio("/sound/auughhh.mp3");
|
const audio = new Audio("/sound/auughhh.mp3");
|
||||||
|
|
||||||
function tick() {
|
function tick() {
|
||||||
seconds.value++;
|
seconds.value++;
|
||||||
if (seconds.value === 60) {
|
if (seconds.value === 60) {
|
||||||
minutes.value++;
|
minutes.value++;
|
||||||
seconds.value = 0;
|
seconds.value = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (minutes.value >= minutesInput.value) {
|
if (minutes.value >= minutesInput.value) {
|
||||||
if (seconds.value >= secondsInput.value) {
|
if (seconds.value >= secondsInput.value) {
|
||||||
finished.value = true;
|
finished.value = true;
|
||||||
playFinishedSound();
|
playFinishedSound();
|
||||||
clearInterval(timer.value);
|
clearInterval(timer.value);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function startTimer() {
|
function startTimer() {
|
||||||
finished.value = false;
|
finished.value = false;
|
||||||
paused.value = false;
|
paused.value = false;
|
||||||
timer.value = setInterval(tick, 1000);
|
timer.value = setInterval(tick, 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
function pauseTimer() {
|
function pauseTimer() {
|
||||||
if (finished.value) return;
|
if (finished.value) return;
|
||||||
|
|
||||||
if (paused.value) {
|
if (paused.value) {
|
||||||
timer.value = setInterval(tick, 1000);
|
timer.value = setInterval(tick, 1000);
|
||||||
paused.value = false;
|
paused.value = false;
|
||||||
} else {
|
} else {
|
||||||
clearInterval(timer.value);
|
clearInterval(timer.value);
|
||||||
paused.value = true;
|
paused.value = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetTimer() {
|
function resetTimer() {
|
||||||
finished.value = true;
|
finished.value = true;
|
||||||
paused.value = true;
|
paused.value = true;
|
||||||
clearInterval(timer.value);
|
clearInterval(timer.value);
|
||||||
minutes.value = 0;
|
minutes.value = 0;
|
||||||
seconds.value = 0;
|
seconds.value = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
function playFinishedSound() {
|
function playFinishedSound() {
|
||||||
audio.play();
|
audio.play();
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="timer-root flex flex-col gap-1 p-1 items-center">
|
<div class="timer-root flex flex-col gap-1 p-1 items-center">
|
||||||
<Header>Timer</Header>
|
<Header>Timer</Header>
|
||||||
<div v-if="finished && paused" class="flex flex-col">
|
<div v-if="finished && paused" class="flex flex-col">
|
||||||
<div class="flex flex-row p-2 place-content-around">
|
<div class="flex flex-row p-2 place-content-around">
|
||||||
<input
|
<input
|
||||||
class="w-2/3"
|
class="w-2/3"
|
||||||
v-model="minutesInput"
|
v-model="minutesInput"
|
||||||
type="range"
|
type="range"
|
||||||
min="0"
|
min="0"
|
||||||
max="59"
|
max="59"
|
||||||
aria-label="Minutes"
|
aria-label="Minutes"
|
||||||
/>
|
/>
|
||||||
<p>{{ minutesInput }}m</p>
|
<p>{{ minutesInput }}m</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row p-2 place-content-around">
|
<div class="flex flex-row p-2 place-content-around">
|
||||||
<input
|
<input
|
||||||
class="w-2/3"
|
class="w-2/3"
|
||||||
v-model="secondsInput"
|
v-model="secondsInput"
|
||||||
type="range"
|
type="range"
|
||||||
min="0"
|
min="0"
|
||||||
max="59"
|
max="59"
|
||||||
aria-label="Seconds"
|
aria-label="Seconds"
|
||||||
/>
|
/>
|
||||||
<p>{{ secondsInput }}s</p>
|
<p>{{ secondsInput }}s</p>
|
||||||
</div>
|
</div>
|
||||||
<Button @click="startTimer">Proceed</Button>
|
<Button @click="startTimer">Proceed</Button>
|
||||||
</div>
|
|
||||||
<div v-if="finished && !paused" class="flex flex-col">
|
|
||||||
<h1>Timer finished!</h1>
|
|
||||||
<Button @click="resetTimer">Reset</Button>
|
|
||||||
</div>
|
|
||||||
<div v-if="!finished && paused" class="flex flex-col">
|
|
||||||
<h1>Paused</h1>
|
|
||||||
<Button @click="resetTimer">Reset</Button>
|
|
||||||
</div>
|
|
||||||
<div v-if="!finished && !paused" class="flex flex-col">
|
|
||||||
<p>
|
|
||||||
{{ minutes.toString().padStart(2, "0") }}:{{
|
|
||||||
seconds.toString().padStart(2, "0")
|
|
||||||
}}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
{{ minutesInput.toString().padStart(2, "0") }}:{{
|
|
||||||
secondsInput.toString().padStart(2, "0")
|
|
||||||
}}
|
|
||||||
</p>
|
|
||||||
<Button @click="pauseTimer">Pause</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="finished && !paused" class="flex flex-col">
|
||||||
|
<h1>Timer finished!</h1>
|
||||||
|
<Button @click="resetTimer">Reset</Button>
|
||||||
|
</div>
|
||||||
|
<div v-if="!finished && paused" class="flex flex-col">
|
||||||
|
<h1>Paused</h1>
|
||||||
|
<Button @click="resetTimer">Reset</Button>
|
||||||
|
</div>
|
||||||
|
<div v-if="!finished && !paused" class="flex flex-col">
|
||||||
|
<p>
|
||||||
|
{{ minutes.toString().padStart(2, "0") }}:{{
|
||||||
|
seconds.toString().padStart(2, "0")
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
{{ minutesInput.toString().padStart(2, "0") }}:{{
|
||||||
|
secondsInput.toString().padStart(2, "0")
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
|
<Button @click="pauseTimer">Pause</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@media (max-width: 850px) {
|
@media (max-width: 850px) {
|
||||||
.timer-root {
|
.timer-root {
|
||||||
padding: 2px;
|
padding: 2px;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
<template>
|
<template>
|
||||||
<div
|
<div
|
||||||
ref="container"
|
ref="container"
|
||||||
class="overflow-auto w-full h-full"
|
class="overflow-auto w-full h-full"
|
||||||
@mousedown="handleMouseDown"
|
@mousedown="handleMouseDown"
|
||||||
@mousemove="handleMouseMove"
|
@mousemove="handleMouseMove"
|
||||||
@mouseup="handleMouseUp"
|
@mouseup="handleMouseUp"
|
||||||
@mouseleave="handleMouseLeave"
|
@mouseleave="handleMouseLeave"
|
||||||
:style="{ cursor: isDragging ? 'grabbing' : 'grab' }"
|
:style="{ cursor: isDragging ? 'grabbing' : 'grab' }"
|
||||||
>
|
>
|
||||||
<slot />
|
<slot />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
@@ -23,45 +23,45 @@ const scrollLeft = ref(0);
|
|||||||
const scrollTop = ref(0);
|
const scrollTop = ref(0);
|
||||||
|
|
||||||
const handleMouseDown = (e) => {
|
const handleMouseDown = (e) => {
|
||||||
isDragging.value = true;
|
isDragging.value = true;
|
||||||
startX.value = e.pageX - container.value.offsetLeft;
|
startX.value = e.pageX - container.value.offsetLeft;
|
||||||
startY.value = e.pageY - container.value.offsetTop;
|
startY.value = e.pageY - container.value.offsetTop;
|
||||||
scrollLeft.value = container.value.scrollLeft;
|
scrollLeft.value = container.value.scrollLeft;
|
||||||
scrollTop.value = container.value.scrollTop;
|
scrollTop.value = container.value.scrollTop;
|
||||||
|
|
||||||
// Prevent text selection while dragging
|
// Prevent text selection while dragging
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMouseMove = (e) => {
|
const handleMouseMove = (e) => {
|
||||||
if (!isDragging.value) return;
|
if (!isDragging.value) return;
|
||||||
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
const x = e.pageX - container.value.offsetLeft;
|
const x = e.pageX - container.value.offsetLeft;
|
||||||
const y = e.pageY - container.value.offsetTop;
|
const y = e.pageY - container.value.offsetTop;
|
||||||
const walkX = (x - startX.value) * 1; // Multiply by scroll speed factor
|
const walkX = (x - startX.value) * 1; // Multiply by scroll speed factor
|
||||||
const walkY = (y - startY.value) * 1;
|
const walkY = (y - startY.value) * 1;
|
||||||
|
|
||||||
container.value.scrollLeft = scrollLeft.value - walkX;
|
container.value.scrollLeft = scrollLeft.value - walkX;
|
||||||
container.value.scrollTop = scrollTop.value - walkY;
|
container.value.scrollTop = scrollTop.value - walkY;
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMouseUp = () => {
|
const handleMouseUp = () => {
|
||||||
isDragging.value = false;
|
isDragging.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMouseLeave = () => {
|
const handleMouseLeave = () => {
|
||||||
isDragging.value = false;
|
isDragging.value = false;
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
/* Prevent text selection while dragging */
|
/* Prevent text selection while dragging */
|
||||||
div[style*="cursor: grabbing"] {
|
div[style*="cursor: grabbing"] {
|
||||||
user-select: none;
|
user-select: none;
|
||||||
-webkit-user-select: none;
|
-webkit-user-select: none;
|
||||||
-moz-user-select: none;
|
-moz-user-select: none;
|
||||||
-ms-user-select: none;
|
-ms-user-select: none;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -2,29 +2,29 @@
|
|||||||
import { computed } from "vue";
|
import { computed } from "vue";
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
sourceArr: {
|
sourceArr: {
|
||||||
type: Array,
|
type: Array,
|
||||||
required: true,
|
required: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
function sourceType(link) {
|
function sourceType(link) {
|
||||||
return "video/" + link.split(".").pop();
|
return "video/" + link.split(".").pop();
|
||||||
}
|
}
|
||||||
|
|
||||||
const keys = ["name", "link"];
|
const keys = ["name", "link"];
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<video
|
<video
|
||||||
v-for="(source, rowIndex) in sourceArr"
|
v-for="(source, rowIndex) in sourceArr"
|
||||||
:key="rowIndex"
|
:key="rowIndex"
|
||||||
class="bdr-1"
|
class="bdr-1"
|
||||||
width="300"
|
width="300"
|
||||||
height="400"
|
height="400"
|
||||||
controls
|
controls
|
||||||
preload="none"
|
preload="none"
|
||||||
>
|
>
|
||||||
<source :src="source.link" :type="sourceType(source.link)" />
|
<source :src="source.link" :type="sourceType(source.link)" />
|
||||||
</video>
|
</video>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="a4page-portrait bdr-1 flex flex-col relative overflow-scroll">
|
<div class="a4page-portrait bdr-1 flex flex-col relative overflow-scroll">
|
||||||
<RouterLink to="/" class="bdr-2">
|
<RouterLink to="/" class="bdr-2">
|
||||||
<img src="/img/memes/epic.jpeg" alt="" loading="lazy" />
|
<img src="/img/memes/epic.jpeg" alt="" loading="lazy" />
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<h1>Click her, she will take you home</h1>
|
<h1>Click her, she will take you home</h1>
|
||||||
<span style="height: 100px"></span>
|
<span style="height: 100px"></span>
|
||||||
<h1>WIP</h1>
|
<h1>WIP</h1>
|
||||||
<h4>Sorry for taking you here</h4>
|
<h4>Sorry for taking you here</h4>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
26
vue/src/components/util/wasm/AutoScroll.vue
Normal file
26
vue/src/components/util/wasm/AutoScroll.vue
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<template>
|
||||||
|
<div ref="container" class="overflow-y-auto">
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { useTemplateRef, onMounted, onBeforeUnmount } from "vue";
|
||||||
|
import { AutoScroller } from "@/wasm/stp_wasm.js";
|
||||||
|
|
||||||
|
const container = useTemplateRef("container");
|
||||||
|
|
||||||
|
let scroller = null;
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
if (!container.value) return;
|
||||||
|
scroller = new AutoScroller(container.value);
|
||||||
|
scroller.start();
|
||||||
|
});
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
scroller?.destroy();
|
||||||
|
scroller?.free();
|
||||||
|
scroller = null;
|
||||||
|
});
|
||||||
|
</script>
|
||||||
@@ -2,6 +2,7 @@ import axios from "axios";
|
|||||||
|
|
||||||
export async function gql(query, variables = {}) {
|
export async function gql(query, variables = {}) {
|
||||||
const res = await axios.post("/api/graphql", { query, variables });
|
const res = await axios.post("/api/graphql", { query, variables });
|
||||||
if (res.data.errors && !res.data.data) throw new Error(res.data.errors[0].message);
|
if (res.data.errors && !res.data.data)
|
||||||
|
throw new Error(res.data.errors[0].message);
|
||||||
return res.data.data;
|
return res.data.data;
|
||||||
}
|
}
|
||||||
|
|||||||
71
vue/src/layouts/CVLayout.vue
Normal file
71
vue/src/layouts/CVLayout.vue
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<script setup>
|
||||||
|
import { RouterView } from "vue-router";
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="cv-layout">
|
||||||
|
<RouterView />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.cv-layout {
|
||||||
|
min-height: 100vh;
|
||||||
|
background: white;
|
||||||
|
color: #111;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.cv-layout h1,
|
||||||
|
.cv-layout h2,
|
||||||
|
.cv-layout h3,
|
||||||
|
.cv-layout h4,
|
||||||
|
.cv-layout p,
|
||||||
|
.cv-layout small,
|
||||||
|
.cv-layout code,
|
||||||
|
.cv-layout ul,
|
||||||
|
.cv-layout li,
|
||||||
|
.cv-layout td,
|
||||||
|
.cv-layout tr,
|
||||||
|
.cv-layout table {
|
||||||
|
color: #111;
|
||||||
|
}
|
||||||
|
.cv-layout h1,
|
||||||
|
.cv-layout h2,
|
||||||
|
.cv-layout h3,
|
||||||
|
.cv-layout h4 {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.cv-layout a {
|
||||||
|
color: #111;
|
||||||
|
background-color: transparent !important;
|
||||||
|
letter-spacing: normal;
|
||||||
|
}
|
||||||
|
.cv-layout input,
|
||||||
|
.cv-layout textarea {
|
||||||
|
color: #111;
|
||||||
|
background-color: white;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
padding: 0;
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
.cv-layout input::placeholder,
|
||||||
|
.cv-layout textarea::placeholder {
|
||||||
|
color: #999;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
.cv-layout table {
|
||||||
|
border: 0 solid transparent;
|
||||||
|
}
|
||||||
|
.cv-layout tr {
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
.cv-layout th {
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.cv-layout td {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user