From 1402045001ee552ab7ea8607ea7aa9ab2bfcd443 Mon Sep 17 00:00:00 2001 From: Aran Roig Date: Sun, 11 Oct 2026 22:26:29 +0200 Subject: [PATCH] Foundry and discord bot --- .gitea/workflows/deploy.yml | 6 + .gitignore | 3 +- AGENTS.md | 471 +++++++++++ backend/.env.production | 4 +- backend/src/index.js | 30 +- backend/src/models/Actor.js | 47 ++ backend/src/models/Campaign.js | 11 +- backend/src/models/DiscordGuildLink.js | 11 + backend/src/models/DiscordLinkRequest.js | 20 + backend/src/models/FoundryLinkRequest.js | 24 + backend/src/models/Item.js | 28 + backend/src/routes/actor.js | 111 +++ backend/src/routes/campaign.js | 145 ++++ backend/src/routes/discord.js | 272 +++++++ backend/src/routes/foundry-link.js | 258 +++++++ backend/src/routes/foundry.js | 27 + backend/src/routes/item.js | 60 ++ backend/src/services/actor-foundry.js | 82 ++ backend/src/services/foundry.js | 34 + discord-bot/.dockerignore | 7 + discord-bot/.env.example | 14 + discord-bot/.gitignore | 3 + discord-bot/Dockerfile | 22 + discord-bot/README.md | 48 ++ discord-bot/package-lock.json | 327 ++++++++ discord-bot/package.json | 18 + discord-bot/src/commands.js | 57 ++ discord-bot/src/config.js | 41 + discord-bot/src/deploy-commands.js | 44 ++ discord-bot/src/dragonroll-api.js | 117 +++ discord-bot/src/index.js | 496 ++++++++++++ docker-compose.yml | 24 +- dragonroll-foundry/README.md | 111 +++ dragonroll-foundry/bridge/package.json | 12 + dragonroll-foundry/bridge/server.js | 233 ++++++ dragonroll-foundry/module.json | 14 + dragonroll-foundry/scripts/api.js | 731 ++++++++++++++++++ frontend/app/app.vue | 13 +- .../app/components/partials/CampaignEntry.vue | 24 +- .../components/partials/ContentSidebar.vue | 339 ++++++-- .../components/partials/NestedNoteList.vue | 90 ++- frontend/app/components/viewer/TopBar.vue | 35 +- .../components/viewer/topbar/TopSearchBar.vue | 15 +- .../app/components/views/DiscordAuthorize.vue | 260 +++++++ .../windows/CampaignSettingsWindow.vue | 356 +++++++++ .../windows/CharacterSheetWindow.vue | 399 ++++++++++ .../windows/CreateCampaignEntryWindow.vue | 135 ++++ .../app/components/windows/NewNoteWindow.vue | 129 ++++ frontend/app/services/WindowDefinitions.js | 24 + frontend/i18n/locales/ca/campaigns.json | 69 ++ frontend/i18n/locales/ca/discord.json | 18 + frontend/i18n/locales/ca/foundry.json | 6 + frontend/i18n/locales/ca/general.json | 4 +- frontend/i18n/locales/ca/windows.json | 2 +- frontend/i18n/locales/en/campaigns.json | 67 +- frontend/i18n/locales/en/discord.json | 18 + frontend/i18n/locales/en/foundry.json | 6 + frontend/i18n/locales/en/windows.json | 2 +- frontend/i18n/locales/es/campaigns.json | 69 ++ frontend/i18n/locales/es/discord.json | 18 + frontend/i18n/locales/es/foundry.json | 6 + frontend/i18n/locales/es/general.json | 4 +- frontend/i18n/locales/es/windows.json | 2 +- package.json | 2 +- scripts/run-foundry.js | 31 + 65 files changed, 5962 insertions(+), 144 deletions(-) create mode 100644 AGENTS.md create mode 100644 backend/src/models/Actor.js create mode 100644 backend/src/models/DiscordGuildLink.js create mode 100644 backend/src/models/DiscordLinkRequest.js create mode 100644 backend/src/models/FoundryLinkRequest.js create mode 100644 backend/src/models/Item.js create mode 100644 backend/src/routes/actor.js create mode 100644 backend/src/routes/discord.js create mode 100644 backend/src/routes/foundry-link.js create mode 100644 backend/src/routes/foundry.js create mode 100644 backend/src/routes/item.js create mode 100644 backend/src/services/actor-foundry.js create mode 100644 backend/src/services/foundry.js create mode 100644 discord-bot/.dockerignore create mode 100644 discord-bot/.env.example create mode 100644 discord-bot/.gitignore create mode 100644 discord-bot/Dockerfile create mode 100644 discord-bot/README.md create mode 100644 discord-bot/package-lock.json create mode 100644 discord-bot/package.json create mode 100644 discord-bot/src/commands.js create mode 100644 discord-bot/src/config.js create mode 100644 discord-bot/src/deploy-commands.js create mode 100644 discord-bot/src/dragonroll-api.js create mode 100644 discord-bot/src/index.js create mode 100644 dragonroll-foundry/README.md create mode 100644 dragonroll-foundry/bridge/package.json create mode 100644 dragonroll-foundry/bridge/server.js create mode 100644 dragonroll-foundry/module.json create mode 100644 dragonroll-foundry/scripts/api.js create mode 100644 frontend/app/components/views/DiscordAuthorize.vue create mode 100644 frontend/app/components/windows/CampaignSettingsWindow.vue create mode 100644 frontend/app/components/windows/CharacterSheetWindow.vue create mode 100644 frontend/app/components/windows/CreateCampaignEntryWindow.vue create mode 100644 frontend/app/components/windows/NewNoteWindow.vue create mode 100644 frontend/i18n/locales/ca/campaigns.json create mode 100644 frontend/i18n/locales/ca/discord.json create mode 100644 frontend/i18n/locales/ca/foundry.json create mode 100644 frontend/i18n/locales/en/discord.json create mode 100644 frontend/i18n/locales/en/foundry.json create mode 100644 frontend/i18n/locales/es/campaigns.json create mode 100644 frontend/i18n/locales/es/discord.json create mode 100644 frontend/i18n/locales/es/foundry.json create mode 100644 scripts/run-foundry.js diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 83ca0f63..ab8c9bfa 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -46,6 +46,12 @@ jobs: docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-backend:latest ./backend docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-backend:latest + - name: Build discord bot + run: | + docker build -t git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-discord-bot:latest \ + ./discord-bot + docker push git.aranroig.com/${{ secrets.REGISTRY_USER }}/dragonroll-discord-bot:latest + - name: Copy files run: | scp docker-compose.yml deploy@${{ secrets.DEPLOY_HOST}}:/var/www/app/ diff --git a/.gitignore b/.gitignore index b512c09d..1dcef2d9 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -node_modules \ No newline at end of file +node_modules +.env \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..8e548bf3 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,471 @@ +# AGENTS.md — Dragonroll + +Read this file before touching the code. It is a complete map of the project: layout, architecture, +data model, API, conventions and known landmines. You should not need to explore the rest of the repo +to make a correct change. + +## 1. What this is + +**Dragonroll** is a free/open-source helper for tabletop RPG campaigns (notes, campaigns, folders, +dice widgets, shared markdown, sounds). It is a two-app monorepo: + +- `backend/` — Node + **Express 5** + **Mongoose 9** (MongoDB) REST API, JWT auth. CommonJS. +- `frontend/` — **Nuxt 4 / Vue 3** client (Composition API, ` + +``` + +DOM id conventions that `Windows.js`, `WindowHandle.vue` and drag/resize depend on — do not rename: +`window-wrapper-{id}`, `window-handle-{id}`, `window-resize-handle-{id}`, `context-menu`, `mouse-tooltip`. + +`WindowHandle.vue` reads `title` (translated at mount via `$t`), `close` and `back` off the window +object, exposes `setupHandle()`, and plays `/sounds/close.wav` when closed. + +### 5.3 Services (`app/services/`) — the state layer + +Plain modules with module-scope `ref()`s imported directly. No DI, no Pinia. Singleton by import. + +| Service | Provides | +|---|---| +| `Server.js` | axios instance (fallback baseURL `http://localhost:5000/api`), `initApi(baseURL)` called by `plugins/api.ts`, request interceptor adding `Authorization: Bearer `, `getBaseUrl()`. Default export is a factory: call `Server()` then `.get/.post`. | +| `User.js` | `UserStatus` ref, `GetUser()` (decodes JWT, auto-logout on `exp`), `SetUser(token)`, `LoadUser`, `LogoutUser`, `IsAdmin`, `HasAdmin()`, `GetUserSetting(key)` / `SetUserSetting(key,value)` (server-backed, in `User.settings`) | +| `Campaign.js` | `useCampaignService()` → `Campaign` (`useState('campaign')`), `SetCampaign(data)` (also writes `localStorage.selectedCampaignId`), `RestoreCampaign()` | +| `Content.js` | `ShowContent` ref (drives the campaign workspace). `SetShowContent` is exported but unused — `ContentManager.vue` sets it from a `watch(Campaign)` and never turns it back off | +| `Emitter.js` | `export const emitter = mitt()` — the app-wide event bus | +| `Toaster.js` | `DisplayToast(color, text, duration)` → emits `toast`; `ToastManager.vue` renders it | +| `Tooltip.js` | `SetupTooltip()`, `AddTooltip(el, text, {max_width})` (stores on `el._dr_tooltip`), polled visibility via `elementsFromPoint` | +| `ContextMenu.js` | `SetupContextMenu()`, `AddContextMenu(el, items, {dropdown:true})`, `ShowContextMenu(items)`, `HideContextMenu()`. Items: `{name, icon?, action?, divider?}` or `{name, context:[...]}` for a submenu; built imperatively into `#context-menu` with `motion` animations | +| `Sound.js` | `AddSound(rootEl)` binds `/sounds/snap.wav` to every `.sound-click` inside `rootEl` | +| `Marker.js` | marked `Marked` instance + custom extensions, `ParseMarkdown(src)`, `GetWidget(kind,name)` (§5.4) | +| `ActionRegistry.js` | `register({id,label,description,execute,isActive?})`, `unregister`, `search(q)` (diacritic-insensitive, prefix-first sort), `execute(id,params)` — powers the command palette | +| `Windows.js` / `WindowDefinitions.js` | §5.2 | +| `widgets/DiceParser.js` | recursive-descent dice evaluator (§5.5) | + +### 5.4 Markdown → Vue widgets + +`Marker.js` registers three marked extensions: + +| Syntax | Level | Output | +|---|---|---| +| `@name\n\n@end` | block | `
` | +| `@name[text]` | inline | `` | +| `[[target]]` | inline | `` (renders the literal text `Link`) | + +`Note.vue` renders the HTML with `v-html`, then in a `setTimeout(...,0)` calls `mountComponents()`, +which `querySelectorAll('.vue-component-display'|'.vue-component-inline')` and mounts each node with a +**separate** `createApp(GetWidget(kind, el.dataset.component), { content: el.dataset.content })`. +Widgets are therefore isolated mini-apps: they receive only `content` (a string) and must not rely on +the parent app's provides/injection. + +Registering a widget = add an entry to `widget_map` in `Marker.js`: + +```js +const widget_map = { + inline: { roll: () => import("~/components/viewer/widgets/inline/RollWidgetInline.vue") }, + display: { roll: () => import("~/components/viewer/widgets/display/RollWidgetDisplay.vue") }, +}; +``` + +`Note.vue` also: handles `Ctrl/Cmd+E` (toggle edit/preview, saves on exit) and `Ctrl/Cmd+S` (save via +`POST /note/update`), tracks dirty state (white dot in the vertical title strip), and wires +Obsidian-style collapsible callouts (`setupCallout()`/`toggleCallout()` + `callouts.scss`). + +### 5.5 Dice grammar (`DiceParser.js`) + +`parse(expr) -> { total, steps[] }`. Tokens: `\d*d\d+` with optional `adv|dis|kh|kl`, integers, +`+ - * / ( )`, unary minus. `adv`/`dis` roll 2dN and keep max/min; `kh`/`kl` keep highest/lowest N. +Division is `Math.floor`. Guards: count 1–1000, sides 2–10000. `steps` are `{type:'op'|'const'|'dice'}` +and `RollWidgetDisplay.vue` turns them into the visual breakdown (kept/dropped/max/min classes). + +### 5.6 Event bus contract + +Every listener in the app (there are only these six `emitter.on` call sites): + +| Event | Payload | Listened by | +|---|---|---| +| `toast` | `{color,text,duration}` | `ToastManager.vue` | +| `push-note` | `{key,title,text,date}` | `NoteContainer.vue` | +| `delete-note` | note key (string) | `NoteContainer.vue` | +| `title-updated` | `{key,title}` | `Note.vue`, `NoteContainer.vue` | +| `status-bar-update` | `{text,icon}` | `FetchStatus.vue` | + +Emitters: `Toaster.js` (`toast`), `ContentSidebar` / `TopSearchBar` (`push-note`), `Note.vue` / +`NestedNoteList.vue` (`delete-note`), `ContentSidebar` (`title-updated`), `FetchStatus` (self-test emit). + +**Orphan events** — emitted, never subscribed to anywhere (the matching handlers `handleNoteCreated` / +`handleNoteRenamed` exist in `ContentSidebar.vue` but were never wired with `emitter.on`; see §9.17): + +| Event | Emitted by | Intended handler | +|---|---|---| +| `note-created` | `ContentSidebar.createNote`, `TopSearchBar` | `ContentSidebar.handleNoteCreated` (dead) | +| `note-renamed` | `RenameNoteWindow.vue` | `ContentSidebar.handleNoteRenamed` (dead) | +| `folder-saved` | `NewFolderWindow.vue` | none — sidebar refreshes only via `@reload-notes` from `NestedNoteList` | + +So "create note" currently works because the sidebar mutates its own list, and folder changes need an +explicit `fetchCampaignNotes()`. If you rely on an event, check a listener exists. + +Note object shape in the UI layer is `{ key, title, text, date }` (mapped from the API's +`{_id,title,content,date}`); convert at the boundary as `ContentSidebar.fetchCampaignNotes` does. + +### 5.7 Theming, fonts, icons, sounds + +- `useTheme.ts` owns `theme` (`'light'|'dark'`) and `accent` (`'katlum'`, type currently narrow) as + module singletons, persists to `localStorage`, and sets `data-theme` / `data-accent` on ``. + `app.vue` calls `setupTheme()` then forces `setTheme('dark')` on mount. +- `colors.scss` holds Sass maps `dark`/`light` (and accents `katlum`/`solus`/`silang`) emitted as + **`--color-*` CSS variables**. Always style with `var(--color-...)` (`background`, + `window-background`, `button-hover`, `text`, `border`, `icon-invert`, …), never hardcode hex. +- Icons are inverted via `filter: invert(var(--color-icon-invert))` — white SVGs + `.icon` class. + Reference either as public assets (`/icons/iconoir/regular/xmark.svg`, `/icons/ui/...`, + `/icons/Pixelarticons/white/close.svg`) or from the `pixelarticons` npm package + (`import SearchIcon from 'pixelarticons/svg/search.svg'`). +- Fonts (`fonts.scss` + `public/fonts/5e`): `BookInsanityRemake` (body default), `MrEavesRemake` + (headings/window titles), `ScalySansRemake`, `NodestoCapsCondensed`, `SolberaImitationRemake`, etc. +- Sounds in `public/sounds/`: `snap.wav` (the `.sound-click` default), `close.wav`, `click.wav`, + `dice.wav`, `roll1.wav`, `roll2.wav`, `notify.wav`, `drums.wav`, `lock.wav`, `doors/`. + +### 5.8 i18n + +Locales: `en` (default), `es`, `ca`. Files live at `frontend/i18n/locales//.json`, and +`app/plugins/i18n.ts` globs them and nests each under its **filename** — so the key is +`.`, e.g. `i18n/locales/en/main-menu.json` → `$t('main-menu.create-campaign')`. +Namespaces in use: `general`, `login`, `register`, `main-menu`, `settings`, `windows`, `campaigns` +(`campaigns` currently only exists for `en`). Call it as `$t(...)` in templates or via `useI18n()` in +script; `WindowDefinitions` stores raw keys (`title: 'windows.login'`) and `WindowHandle` translates them. + +**Adding a string = add it to all three locales** (`en`, `es`, `ca`); the Nuxt i18n module is also +configured (`nuxt.config.ts`, `langDir: 'locales/'`, `vueI18n: './i18n.config.ts'`) but its locale files +(`locales/en.json` etc.) are empty `{}` — the custom plugin is what components actually consume. + +## 6. Conventions + +- **Backend**: CommonJS `require`/`module.exports`; files in `services/` are shared infra, `routes/` + are thin Express routers, `models/` one Mongoose schema per file exporting `mongoose.model(...)`. + Every handler is `try/catch` → `{status:'error', msg:'errors.internal'}` + `console.error`. + Route logic helpers (like `userOwnsCampaign`) are duplicated per router file today — match that + style unless you refactor both at once. +- **Frontend**: Vue 3 ` diff --git a/frontend/app/components/viewer/TopBar.vue b/frontend/app/components/viewer/TopBar.vue index 93dbc0ee..faba5934 100644 --- a/frontend/app/components/viewer/TopBar.vue +++ b/frontend/app/components/viewer/TopBar.vue @@ -1,10 +1,16 @@ @@ -40,16 +50,25 @@ const campaignName = computed(() => { left: 6px; } -.left, .right { +.left { flex: 1; } +.center { + display: flex; + align-items: center; +} + .right { display: flex; - justify-content: flex-end; align-items: center; - gap: 8px; - padding-right: 10px; + justify-content: flex-end; + flex: 1; + padding: 0 10px; +} + +.settings-button { + padding: 5px 10px; } .top-bar-title { diff --git a/frontend/app/components/viewer/topbar/TopSearchBar.vue b/frontend/app/components/viewer/topbar/TopSearchBar.vue index 815db6fc..8e35dfb5 100644 --- a/frontend/app/components/viewer/topbar/TopSearchBar.vue +++ b/frontend/app/components/viewer/topbar/TopSearchBar.vue @@ -5,6 +5,7 @@ import PlusIcon from 'pixelarticons/svg/plus.svg' import NoteSearchResult from './SearchResult.vue'; import Server from '~/services/Server'; import { emitter } from '~/services/Emitter'; +import { CreateWindow } from '~/services/Windows'; import { register, search as searchActions, execute as executeAction } from '~/services/ActionRegistry'; import { useCampaignService } from '~/services/Campaign.js'; @@ -41,20 +42,10 @@ function registerCreateNoteAction() { id: 'create_note', label: 'New note', description: 'Create a new note in the current campaign', - execute: async () => { + execute: () => { if (!Campaign.value) return; const campaignId = Campaign.value?._id ?? Campaign.value?.id; - try { - const response = await Server().post('/note/create', { - title: 'New note', - content: '', - campaign: campaignId - }); - if (response.data.status !== 'ok') return; - emitter.emit('note-created', response.data.note); - } catch (err) { - console.error('[ActionRegistry] Failed to create note:', err); - } + CreateWindow('new_note', { campaign: campaignId }); } }; register(action); diff --git a/frontend/app/components/views/DiscordAuthorize.vue b/frontend/app/components/views/DiscordAuthorize.vue new file mode 100644 index 00000000..5d25f28d --- /dev/null +++ b/frontend/app/components/views/DiscordAuthorize.vue @@ -0,0 +1,260 @@ + + + + + diff --git a/frontend/app/components/windows/CampaignSettingsWindow.vue b/frontend/app/components/windows/CampaignSettingsWindow.vue new file mode 100644 index 00000000..e4c4172a --- /dev/null +++ b/frontend/app/components/windows/CampaignSettingsWindow.vue @@ -0,0 +1,356 @@ + + + + + diff --git a/frontend/app/components/windows/CharacterSheetWindow.vue b/frontend/app/components/windows/CharacterSheetWindow.vue new file mode 100644 index 00000000..78e1c5a3 --- /dev/null +++ b/frontend/app/components/windows/CharacterSheetWindow.vue @@ -0,0 +1,399 @@ + + +