Compare commits
30 Commits
v1.0.6
...
redesign/d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
769d75d937 | ||
|
|
f440fd7751 | ||
|
|
29615cb4f3 | ||
|
|
376ed9a98d | ||
|
|
b42a2d7ea7 | ||
|
|
560d023250 | ||
|
|
f91ef84832 | ||
|
|
ef128b47d2 | ||
|
|
1bb810f851 | ||
|
|
b4d1bc8dd0 | ||
|
|
d15ea28e8f | ||
|
|
7d5966839a | ||
|
|
2668014068 | ||
|
|
bb381569e3 | ||
|
|
39622de8dc | ||
|
|
500dca48a5 | ||
|
|
b542f30dcf | ||
|
|
6461417b50 | ||
|
|
380ab2700c | ||
|
|
585e8aa3f7 | ||
|
|
4d087132db | ||
|
|
16f378eada | ||
|
|
3e1af29b38 | ||
|
|
759bd0be2e | ||
|
|
9d28fdfb65 | ||
|
|
eb57c51a24 | ||
|
|
f67b175d39 | ||
|
|
7acdd3654f | ||
|
|
57efc6a5d2 | ||
|
|
854f56a178 |
12
CLAUDE.md
12
CLAUDE.md
@@ -423,3 +423,15 @@ Things I discovered about myself building a sister platform across multiple sess
|
||||
16. **Response shape mismatches are silent killers.** The frontend destructures `data.config` and the backend returns the raw entity — no error thrown, no 500, just `undefined` propagating through the template until Vue hits `Cannot read properties of undefined`. The fix is trivial (wrap in `{ config }`), but finding it requires knowing what the frontend expects. Document the contract.
|
||||
|
||||
17. **Tools that close the feedback loop are worth 10x their cost.** The debugging bottleneck was never the fix — it was the round-trip of push → rebuild → check → paste → interpret → fix. Playwright and Postgres MCP don't make you smarter, they make you faster. And faster means more iterations, which means better outcomes.
|
||||
|
||||
18. **When aggregating across N similar modules, scout for the one that doesn't match the pattern — it's always the oldest or the first-built.** The Loot module was the first plugin config module built, so it uses `fetchProfiles()`/`profiles` while the other 8 use `fetchConfigs()`/`configs`. The first implementation defines its own naming before a convention exists. Every aggregation layer (landing pages, batch operations, monitoring dashboards) will hit this drift. A 30-second recon across all N modules before writing the aggregator prevents a mid-implementation refactor.
|
||||
|
||||
19. **UI scaling problems are invisible when you're adding one item at a time — they only become obvious in aggregate.** Nine plugin config sidebar entries were added across multiple sessions, each one reasonable in isolation. Nobody noticed the sidebar was becoming unusable until all nine were there. When building a repeatable pattern (nav items, config modules, API endpoints), build the aggregation layer early — ideally when N hits 3 or 4 — not after it's already painful.
|
||||
|
||||
20. **Parallel state fields that track related things will drift apart — and the bugs are silent.** When two fields represent aspects of the same state (`captureMode` and `vkiMode`, or `isLoading` and `error`, or `connection_status` and `companion_last_seen`), every code path that mutates one must also update the other. But new code paths get added over time, and they only update the field they know about. Future me: when you see two fields tracking related state, grep for ALL mutation sites of each — if any path updates one but not the other, that's a bug waiting to happen. And when you add a new mutation path, check every sibling field, not just the obvious one.
|
||||
|
||||
21. **Route through the component that survives transitions, not the one that doesn't.** When two systems can handle the same job but one is resilient to failure modes and the other isn't, route through the survivor. Don't build infrastructure to prop up the fragile path when the robust path already exists. In this project: NATS request-reply through the companion agent is the robust path; direct WebSocket to the browser is the fragile one. If a feature can work through either, prefer the path that handles disconnects, reconnects, and restarts gracefully. One routing change beats an entire retry/recovery subsystem.
|
||||
|
||||
22. **Build-green is not render-correct — visually verify UI work before calling it done.** The entire design-system re-skin (50+ files, six green commits) rendered almost completely unstyled in the browser — white background, no surfaces, no accent — because the design tokens never loaded. `vue-tsc -b` + `vite build` passed clean the whole time; CSS that *compiles* can still apply *zero* styles. One Playwright screenshot of the login exposed it in seconds. When the deliverable is visual, a green build is necessary but not sufficient: load it in a real browser (Playwright on the dev server at :5174), screenshot it, and assert on `getComputedStyle` — don't trust compilation alone. This is Lesson 17 with teeth.
|
||||
|
||||
23. **Tailwind v4 silently drops a nested `@import` barrel placed after `@import "tailwindcss"`.** `style.css` did `@import "tailwindcss"; @import "./styles/corrosion.css";` where corrosion.css was a barrel of eight `@import` token files. Once Tailwind v4 expands the tailwindcss import in place, the barrel's inner @imports no longer precede all statements, so PostCSS drops them — emitting only an easily-ignored "@import must precede all other statements" warning. Result: every design token resolved empty and the whole panel rendered unstyled. Import token/design CSS files **directly and contiguously** in the entry stylesheet; never via a nested barrel after the Tailwind import. The build warning you wave off as "pre-existing" may be the entire feature silently failing.
|
||||
|
||||
@@ -35,6 +35,15 @@ import { SetupModule } from './modules/setup/setup.module';
|
||||
import { MigrationModule } from './modules/migration/migration.module';
|
||||
import { ChangelogModule } from './modules/changelog/changelog.module';
|
||||
import { FilesModule } from './modules/files/files.module';
|
||||
import { LootModule } from './modules/loot/loot.module';
|
||||
import { TeleportModule } from './modules/teleport/teleport.module';
|
||||
import { GatherModule } from './modules/gather/gather.module';
|
||||
import { AutoDoorsModule } from './modules/autodoors/autodoors.module';
|
||||
import { KitsModule } from './modules/kits/kits.module';
|
||||
import { FurnaceSplitterModule } from './modules/furnacesplitter/furnacesplitter.module';
|
||||
import { BetterChatModule } from './modules/betterchat/betterchat.module';
|
||||
import { TimedExecuteModule } from './modules/timedexecute/timedexecute.module';
|
||||
import { RaidableBasesModule } from './modules/raidablebases/raidablebases.module';
|
||||
|
||||
// Shared Services
|
||||
import { NatsService } from './services/nats.service';
|
||||
@@ -105,6 +114,15 @@ import { NatsBridgeGateway } from './gateways/nats-bridge.gateway';
|
||||
MigrationModule,
|
||||
ChangelogModule,
|
||||
FilesModule,
|
||||
LootModule,
|
||||
TeleportModule,
|
||||
GatherModule,
|
||||
AutoDoorsModule,
|
||||
KitsModule,
|
||||
FurnaceSplitterModule,
|
||||
BetterChatModule,
|
||||
TimedExecuteModule,
|
||||
RaidableBasesModule,
|
||||
],
|
||||
providers: [
|
||||
// Global guards (order matters: auth first, then license, then permissions)
|
||||
|
||||
33
backend-nest/src/entities/autodoors-config.entity.ts
Normal file
33
backend-nest/src/entities/autodoors-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('autodoors_configs')
|
||||
export class AutoDoorsConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
33
backend-nest/src/entities/betterchat-config.entity.ts
Normal file
33
backend-nest/src/entities/betterchat-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('betterchat_configs')
|
||||
export class BetterChatConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
33
backend-nest/src/entities/furnacesplitter-config.entity.ts
Normal file
33
backend-nest/src/entities/furnacesplitter-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('furnacesplitter_configs')
|
||||
export class FurnaceSplitterConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
33
backend-nest/src/entities/gather-config.entity.ts
Normal file
33
backend-nest/src/entities/gather-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('gather_configs')
|
||||
export class GatherConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
33
backend-nest/src/entities/kits-config.entity.ts
Normal file
33
backend-nest/src/entities/kits-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('kits_configs')
|
||||
export class KitsConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
36
backend-nest/src/entities/loot-profile.entity.ts
Normal file
36
backend-nest/src/entities/loot-profile.entity.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('loot_profiles')
|
||||
export class LootProfile {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
profile_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
loot_table: Record<string, any>;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
loot_groups: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
33
backend-nest/src/entities/raidablebases-config.entity.ts
Normal file
33
backend-nest/src/entities/raidablebases-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('raidablebases_configs')
|
||||
export class RaidableBasesConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
33
backend-nest/src/entities/teleport-config.entity.ts
Normal file
33
backend-nest/src/entities/teleport-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('teleport_configs')
|
||||
export class TeleportConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
33
backend-nest/src/entities/timedexecute-config.entity.ts
Normal file
33
backend-nest/src/entities/timedexecute-config.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
|
||||
import { License } from './license.entity';
|
||||
|
||||
@Entity('timedexecute_configs')
|
||||
export class TimedExecuteConfig {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id: string;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
license_id: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 100 })
|
||||
config_name: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ type: 'jsonb', default: () => "'{}'" })
|
||||
config_data: Record<string, any>;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
is_active: boolean;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
created_at: Date;
|
||||
|
||||
@Column({ type: 'timestamptz', default: () => 'NOW()' })
|
||||
updated_at: Date;
|
||||
|
||||
@ManyToOne(() => License, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'license_id' })
|
||||
license: License;
|
||||
}
|
||||
80
backend-nest/src/modules/autodoors/autodoors.controller.ts
Normal file
80
backend-nest/src/modules/autodoors/autodoors.controller.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { AutoDoorsService } from './autodoors.service';
|
||||
import { CreateAutoDoorsConfigDto } from './dto/create-autodoors-config.dto';
|
||||
import { UpdateAutoDoorsConfigDto } from './dto/update-autodoors-config.dto';
|
||||
import { ImportAutoDoorsConfigDto } from './dto/import-autodoors-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('autodoors')
|
||||
@ApiBearerAuth()
|
||||
@Controller('autodoors')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class AutoDoorsController {
|
||||
constructor(private readonly autoDoorsService: AutoDoorsService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('autodoors.view')
|
||||
@ApiOperation({ summary: 'List AutoDoors configs' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.autoDoorsService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('autodoors.view')
|
||||
@ApiOperation({ summary: 'Get full AutoDoors config' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.autoDoorsService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('autodoors.manage')
|
||||
@ApiOperation({ summary: 'Create AutoDoors config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateAutoDoorsConfigDto) {
|
||||
return this.autoDoorsService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('autodoors.manage')
|
||||
@ApiOperation({ summary: 'Update AutoDoors config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateAutoDoorsConfigDto,
|
||||
) {
|
||||
return this.autoDoorsService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('autodoors.manage')
|
||||
@ApiOperation({ summary: 'Delete AutoDoors config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.autoDoorsService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('autodoors.manage')
|
||||
@ApiOperation({ summary: 'Deploy AutoDoors config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.autoDoorsService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('autodoors.manage')
|
||||
@ApiOperation({ summary: 'Import AutoDoors.json from server' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportAutoDoorsConfigDto) {
|
||||
return this.autoDoorsService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
14
backend-nest/src/modules/autodoors/autodoors.module.ts
Normal file
14
backend-nest/src/modules/autodoors/autodoors.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AutoDoorsController } from './autodoors.controller';
|
||||
import { AutoDoorsService } from './autodoors.service';
|
||||
import { AutoDoorsConfig } from '../../entities/autodoors-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([AutoDoorsConfig])],
|
||||
controllers: [AutoDoorsController],
|
||||
providers: [AutoDoorsService, NatsService],
|
||||
exports: [AutoDoorsService],
|
||||
})
|
||||
export class AutoDoorsModule {}
|
||||
180
backend-nest/src/modules/autodoors/autodoors.service.ts
Normal file
180
backend-nest/src/modules/autodoors/autodoors.service.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { AutoDoorsConfig } from '../../entities/autodoors-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateAutoDoorsConfigDto } from './dto/create-autodoors-config.dto';
|
||||
import { UpdateAutoDoorsConfigDto } from './dto/update-autodoors-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AutoDoorsService {
|
||||
private readonly logger = new Logger(AutoDoorsService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(AutoDoorsConfig)
|
||||
private readonly autoDoorsRepo: Repository<AutoDoorsConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.autoDoorsRepo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.autoDoorsRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('AutoDoors config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateAutoDoorsConfigDto) {
|
||||
const config = this.autoDoorsRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.autoDoorsRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateAutoDoorsConfigDto) {
|
||||
const config = await this.autoDoorsRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('AutoDoors config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.autoDoorsRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.autoDoorsRepo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('AutoDoors config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.autoDoorsRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('AutoDoors config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write AutoDoors.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/AutoDoors.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload AutoDoors plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload AutoDoors',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.autoDoorsRepo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.autoDoorsRepo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy AutoDoors config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy AutoDoors config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import AutoDoors.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read AutoDoors.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/AutoDoors.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new AutoDoors config row
|
||||
const config = this.autoDoorsRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.autoDoorsRepo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import AutoDoors config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import AutoDoors config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateAutoDoorsConfigDto {
|
||||
@ApiProperty({ example: 'Default AutoDoors' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard auto-close settings' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportAutoDoorsConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateAutoDoorsConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
80
backend-nest/src/modules/betterchat/betterchat.controller.ts
Normal file
80
backend-nest/src/modules/betterchat/betterchat.controller.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { BetterChatService } from './betterchat.service';
|
||||
import { CreateBetterChatConfigDto } from './dto/create-betterchat-config.dto';
|
||||
import { UpdateBetterChatConfigDto } from './dto/update-betterchat-config.dto';
|
||||
import { ImportBetterChatConfigDto } from './dto/import-betterchat-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('betterchat')
|
||||
@ApiBearerAuth()
|
||||
@Controller('betterchat')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class BetterChatController {
|
||||
constructor(private readonly betterChatService: BetterChatService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('betterchat.view')
|
||||
@ApiOperation({ summary: 'List BetterChat configs (summaries)' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.betterChatService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('betterchat.view')
|
||||
@ApiOperation({ summary: 'Get full BetterChat config with data' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.betterChatService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('betterchat.manage')
|
||||
@ApiOperation({ summary: 'Create BetterChat config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateBetterChatConfigDto) {
|
||||
return this.betterChatService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('betterchat.manage')
|
||||
@ApiOperation({ summary: 'Update BetterChat config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateBetterChatConfigDto,
|
||||
) {
|
||||
return this.betterChatService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('betterchat.manage')
|
||||
@ApiOperation({ summary: 'Delete BetterChat config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.betterChatService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('betterchat.manage')
|
||||
@ApiOperation({ summary: 'Deploy BetterChat config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.betterChatService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('betterchat.manage')
|
||||
@ApiOperation({ summary: 'Import BetterChat.json from server via NATS' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportBetterChatConfigDto) {
|
||||
return this.betterChatService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
14
backend-nest/src/modules/betterchat/betterchat.module.ts
Normal file
14
backend-nest/src/modules/betterchat/betterchat.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { BetterChatController } from './betterchat.controller';
|
||||
import { BetterChatService } from './betterchat.service';
|
||||
import { BetterChatConfig } from '../../entities/betterchat-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([BetterChatConfig])],
|
||||
controllers: [BetterChatController],
|
||||
providers: [BetterChatService, NatsService],
|
||||
exports: [BetterChatService],
|
||||
})
|
||||
export class BetterChatModule {}
|
||||
180
backend-nest/src/modules/betterchat/betterchat.service.ts
Normal file
180
backend-nest/src/modules/betterchat/betterchat.service.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { BetterChatConfig } from '../../entities/betterchat-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateBetterChatConfigDto } from './dto/create-betterchat-config.dto';
|
||||
import { UpdateBetterChatConfigDto } from './dto/update-betterchat-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class BetterChatService {
|
||||
private readonly logger = new Logger(BetterChatService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(BetterChatConfig)
|
||||
private readonly repo: Repository<BetterChatConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.repo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.repo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('BetterChat config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateBetterChatConfigDto) {
|
||||
const config = this.repo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.repo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateBetterChatConfigDto) {
|
||||
const config = await this.repo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('BetterChat config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.repo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.repo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('BetterChat config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.repo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('BetterChat config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write BetterChat.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/BetterChat.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload BetterChat plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload BetterChat',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.repo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.repo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy BetterChat config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy BetterChat config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import BetterChat.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read BetterChat.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/BetterChat.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new config row
|
||||
const config = this.repo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.repo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import BetterChat config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import BetterChat config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateBetterChatConfigDto {
|
||||
@ApiProperty({ example: 'Default Chat Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard BetterChat settings' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportBetterChatConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateBetterChatConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated Chat Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateFurnaceSplitterConfigDto {
|
||||
@ApiProperty({ example: 'Default FurnaceSplitter' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard furnace splitter settings' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportFurnaceSplitterConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateFurnaceSplitterConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated FurnaceSplitter' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { FurnaceSplitterService } from './furnacesplitter.service';
|
||||
import { CreateFurnaceSplitterConfigDto } from './dto/create-furnacesplitter-config.dto';
|
||||
import { UpdateFurnaceSplitterConfigDto } from './dto/update-furnacesplitter-config.dto';
|
||||
import { ImportFurnaceSplitterConfigDto } from './dto/import-furnacesplitter-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('furnacesplitter')
|
||||
@ApiBearerAuth()
|
||||
@Controller('furnacesplitter')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class FurnaceSplitterController {
|
||||
constructor(private readonly furnaceSplitterService: FurnaceSplitterService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('furnacesplitter.view')
|
||||
@ApiOperation({ summary: 'List furnace splitter configs (summaries)' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.furnaceSplitterService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('furnacesplitter.view')
|
||||
@ApiOperation({ summary: 'Get full furnace splitter config with data' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.furnaceSplitterService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('furnacesplitter.manage')
|
||||
@ApiOperation({ summary: 'Create furnace splitter config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateFurnaceSplitterConfigDto) {
|
||||
return this.furnaceSplitterService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('furnacesplitter.manage')
|
||||
@ApiOperation({ summary: 'Update furnace splitter config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateFurnaceSplitterConfigDto,
|
||||
) {
|
||||
return this.furnaceSplitterService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('furnacesplitter.manage')
|
||||
@ApiOperation({ summary: 'Delete furnace splitter config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.furnaceSplitterService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('furnacesplitter.manage')
|
||||
@ApiOperation({ summary: 'Deploy furnace splitter config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.furnaceSplitterService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('furnacesplitter.manage')
|
||||
@ApiOperation({ summary: 'Import FurnaceSplitter.json from server via NATS' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportFurnaceSplitterConfigDto) {
|
||||
return this.furnaceSplitterService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { FurnaceSplitterController } from './furnacesplitter.controller';
|
||||
import { FurnaceSplitterService } from './furnacesplitter.service';
|
||||
import { FurnaceSplitterConfig } from '../../entities/furnacesplitter-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([FurnaceSplitterConfig])],
|
||||
controllers: [FurnaceSplitterController],
|
||||
providers: [FurnaceSplitterService, NatsService],
|
||||
exports: [FurnaceSplitterService],
|
||||
})
|
||||
export class FurnaceSplitterModule {}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { FurnaceSplitterConfig } from '../../entities/furnacesplitter-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateFurnaceSplitterConfigDto } from './dto/create-furnacesplitter-config.dto';
|
||||
import { UpdateFurnaceSplitterConfigDto } from './dto/update-furnacesplitter-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class FurnaceSplitterService {
|
||||
private readonly logger = new Logger(FurnaceSplitterService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(FurnaceSplitterConfig)
|
||||
private readonly furnaceRepo: Repository<FurnaceSplitterConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.furnaceRepo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.furnaceRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('FurnaceSplitter config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateFurnaceSplitterConfigDto) {
|
||||
const config = this.furnaceRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.furnaceRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateFurnaceSplitterConfigDto) {
|
||||
const config = await this.furnaceRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('FurnaceSplitter config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.furnaceRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.furnaceRepo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('FurnaceSplitter config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.furnaceRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('FurnaceSplitter config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write FurnaceSplitter.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/FurnaceSplitter.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload FurnaceSplitter plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload FurnaceSplitter',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.furnaceRepo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.furnaceRepo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy furnace splitter config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy furnace splitter config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import FurnaceSplitter.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read FurnaceSplitter.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/FurnaceSplitter.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new furnace splitter config row
|
||||
const config = this.furnaceRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.furnaceRepo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import furnace splitter config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import furnace splitter config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateGatherConfigDto {
|
||||
@ApiProperty({ example: 'Default 2x Rates' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard 2x gather rates' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportGatherConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateGatherConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated Rates' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
80
backend-nest/src/modules/gather/gather.controller.ts
Normal file
80
backend-nest/src/modules/gather/gather.controller.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { GatherService } from './gather.service';
|
||||
import { CreateGatherConfigDto } from './dto/create-gather-config.dto';
|
||||
import { UpdateGatherConfigDto } from './dto/update-gather-config.dto';
|
||||
import { ImportGatherConfigDto } from './dto/import-gather-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('gather')
|
||||
@ApiBearerAuth()
|
||||
@Controller('gather')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class GatherController {
|
||||
constructor(private readonly gatherService: GatherService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('gather.view')
|
||||
@ApiOperation({ summary: 'List gather configs' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.gatherService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('gather.view')
|
||||
@ApiOperation({ summary: 'Get full gather config' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.gatherService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('gather.manage')
|
||||
@ApiOperation({ summary: 'Create gather config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateGatherConfigDto) {
|
||||
return this.gatherService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('gather.manage')
|
||||
@ApiOperation({ summary: 'Update gather config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateGatherConfigDto,
|
||||
) {
|
||||
return this.gatherService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('gather.manage')
|
||||
@ApiOperation({ summary: 'Delete gather config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.gatherService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('gather.manage')
|
||||
@ApiOperation({ summary: 'Deploy gather config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.gatherService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('gather.manage')
|
||||
@ApiOperation({ summary: 'Import GatherManager.json from server' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportGatherConfigDto) {
|
||||
return this.gatherService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
14
backend-nest/src/modules/gather/gather.module.ts
Normal file
14
backend-nest/src/modules/gather/gather.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { GatherController } from './gather.controller';
|
||||
import { GatherService } from './gather.service';
|
||||
import { GatherConfig } from '../../entities/gather-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([GatherConfig])],
|
||||
controllers: [GatherController],
|
||||
providers: [GatherService, NatsService],
|
||||
exports: [GatherService],
|
||||
})
|
||||
export class GatherModule {}
|
||||
180
backend-nest/src/modules/gather/gather.service.ts
Normal file
180
backend-nest/src/modules/gather/gather.service.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { GatherConfig } from '../../entities/gather-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateGatherConfigDto } from './dto/create-gather-config.dto';
|
||||
import { UpdateGatherConfigDto } from './dto/update-gather-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class GatherService {
|
||||
private readonly logger = new Logger(GatherService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(GatherConfig)
|
||||
private readonly gatherRepo: Repository<GatherConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.gatherRepo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.gatherRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Gather config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateGatherConfigDto) {
|
||||
const config = this.gatherRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.gatherRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateGatherConfigDto) {
|
||||
const config = await this.gatherRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Gather config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.gatherRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.gatherRepo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('Gather config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.gatherRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Gather config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write GatherManager.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/GatherManager.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload GatherManager plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload GatherManager',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.gatherRepo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.gatherRepo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy gather config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy gather config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import GatherManager.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read GatherManager.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/GatherManager.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new gather config row
|
||||
const config = this.gatherRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.gatherRepo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import gather config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import gather config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
19
backend-nest/src/modules/kits/dto/create-kits-config.dto.ts
Normal file
19
backend-nest/src/modules/kits/dto/create-kits-config.dto.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateKitsConfigDto {
|
||||
@ApiProperty({ example: 'Default Kits' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard kit configuration' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
14
backend-nest/src/modules/kits/dto/import-kits-config.dto.ts
Normal file
14
backend-nest/src/modules/kits/dto/import-kits-config.dto.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportKitsConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
25
backend-nest/src/modules/kits/dto/update-kits-config.dto.ts
Normal file
25
backend-nest/src/modules/kits/dto/update-kits-config.dto.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateKitsConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated Kits' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
80
backend-nest/src/modules/kits/kits.controller.ts
Normal file
80
backend-nest/src/modules/kits/kits.controller.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { KitsService } from './kits.service';
|
||||
import { CreateKitsConfigDto } from './dto/create-kits-config.dto';
|
||||
import { UpdateKitsConfigDto } from './dto/update-kits-config.dto';
|
||||
import { ImportKitsConfigDto } from './dto/import-kits-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('kits')
|
||||
@ApiBearerAuth()
|
||||
@Controller('kits')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class KitsController {
|
||||
constructor(private readonly kitsService: KitsService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('kits.view')
|
||||
@ApiOperation({ summary: 'List kits configs (summaries)' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.kitsService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('kits.view')
|
||||
@ApiOperation({ summary: 'Get full kits config with data' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.kitsService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('kits.manage')
|
||||
@ApiOperation({ summary: 'Create kits config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateKitsConfigDto) {
|
||||
return this.kitsService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('kits.manage')
|
||||
@ApiOperation({ summary: 'Update kits config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateKitsConfigDto,
|
||||
) {
|
||||
return this.kitsService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('kits.manage')
|
||||
@ApiOperation({ summary: 'Delete kits config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.kitsService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('kits.manage')
|
||||
@ApiOperation({ summary: 'Deploy kits config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.kitsService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('kits.manage')
|
||||
@ApiOperation({ summary: 'Import Kits.json from server via NATS' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportKitsConfigDto) {
|
||||
return this.kitsService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
14
backend-nest/src/modules/kits/kits.module.ts
Normal file
14
backend-nest/src/modules/kits/kits.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { KitsController } from './kits.controller';
|
||||
import { KitsService } from './kits.service';
|
||||
import { KitsConfig } from '../../entities/kits-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([KitsConfig])],
|
||||
controllers: [KitsController],
|
||||
providers: [KitsService, NatsService],
|
||||
exports: [KitsService],
|
||||
})
|
||||
export class KitsModule {}
|
||||
180
backend-nest/src/modules/kits/kits.service.ts
Normal file
180
backend-nest/src/modules/kits/kits.service.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { KitsConfig } from '../../entities/kits-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateKitsConfigDto } from './dto/create-kits-config.dto';
|
||||
import { UpdateKitsConfigDto } from './dto/update-kits-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class KitsService {
|
||||
private readonly logger = new Logger(KitsService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(KitsConfig)
|
||||
private readonly kitsRepo: Repository<KitsConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.kitsRepo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.kitsRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Kits config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateKitsConfigDto) {
|
||||
const config = this.kitsRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.kitsRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateKitsConfigDto) {
|
||||
const config = await this.kitsRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Kits config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.kitsRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.kitsRepo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('Kits config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.kitsRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Kits config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write Kits.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/Kits.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload Kits plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload Kits',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.kitsRepo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.kitsRepo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy kits config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy kits config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import Kits.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read Kits.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/Kits.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new kits config row
|
||||
const config = this.kitsRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.kitsRepo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import kits config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import kits config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
39
backend-nest/src/modules/loot/data/rust-containers.ts
Normal file
39
backend-nest/src/modules/loot/data/rust-containers.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
export interface RustContainerInfo {
|
||||
prefab: string;
|
||||
name: string;
|
||||
category: string;
|
||||
}
|
||||
|
||||
export const RUST_CONTAINERS: RustContainerInfo[] = [
|
||||
// Crates
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_normal.prefab', name: 'Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_normal_2.prefab', name: 'Crate (Small)', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_elite.prefab', name: 'Elite Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_tools.prefab', name: 'Tool Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_food_1.prefab', name: 'Food Crate (Small)', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_food_2.prefab', name: 'Food Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_medical.prefab', name: 'Medical Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_mine.prefab', name: 'Mine Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_basic.prefab', name: 'Basic Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_underwater_basic.prefab', name: 'Underwater Basic Crate', category: 'crates' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_underwater_advanced.prefab', name: 'Underwater Advanced Crate', category: 'crates' },
|
||||
// Barrels
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/loot_barrel_1.prefab', name: 'Barrel', category: 'barrels' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/loot_barrel_2.prefab', name: 'Barrel 2', category: 'barrels' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/oil_barrel.prefab', name: 'Oil Barrel', category: 'barrels' },
|
||||
// Military
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_helicopter.prefab', name: 'Helicopter Crate', category: 'military' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/bradley_crate.prefab', name: 'Bradley Crate', category: 'military' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/supply_drop.prefab', name: 'Supply Drop', category: 'military' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_locked.prefab', name: 'Locked Crate', category: 'military' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/crate_hackable.prefab', name: 'Hackable Crate', category: 'military' },
|
||||
// NPCs
|
||||
{ prefab: 'assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_full_any.prefab', name: 'Scientist', category: 'npcs' },
|
||||
{ prefab: 'assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_heavy.prefab', name: 'Heavy Scientist', category: 'npcs' },
|
||||
{ prefab: 'assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_oilrig.prefab', name: 'Oil Rig Scientist', category: 'npcs' },
|
||||
{ prefab: 'assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_cargo.prefab', name: 'Cargo Ship Scientist', category: 'npcs' },
|
||||
{ prefab: 'assets/rust.ai/agents/npcplayer/humannpc/tunneldweller/npc_tunneldweller.prefab', name: 'Tunnel Dweller', category: 'npcs' },
|
||||
// Other
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/minecart.prefab', name: 'Minecart', category: 'other' },
|
||||
{ prefab: 'assets/bundled/prefabs/radtown/vehicle_parts.prefab', name: 'Vehicle Parts', category: 'other' },
|
||||
];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { IsNumber, IsIn } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class ApplyLootProfileDto {
|
||||
@ApiProperty({ example: 1, description: 'Loot multiplier', enum: [1, 2, 5, 10] })
|
||||
@IsNumber()
|
||||
@IsIn([1, 2, 5, 10])
|
||||
multiplier: number;
|
||||
}
|
||||
24
backend-nest/src/modules/loot/dto/create-loot-profile.dto.ts
Normal file
24
backend-nest/src/modules/loot/dto/create-loot-profile.dto.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateLootProfileDto {
|
||||
@ApiProperty({ example: 'Vanilla 2x' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
profile_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard 2x loot table' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
loot_table?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
loot_groups?: Record<string, any>;
|
||||
}
|
||||
23
backend-nest/src/modules/loot/dto/import-loot-profile.dto.ts
Normal file
23
backend-nest/src/modules/loot/dto/import-loot-profile.dto.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { IsString, IsObject, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportLootProfileDto {
|
||||
@ApiProperty({ example: 'Imported from Looty' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
profile_name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty({ description: 'BetterLoot LootTables.json content' })
|
||||
@IsObject()
|
||||
loot_table: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional({ description: 'BetterLoot LootGroups.json content' })
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
loot_groups?: Record<string, any>;
|
||||
}
|
||||
30
backend-nest/src/modules/loot/dto/update-loot-profile.dto.ts
Normal file
30
backend-nest/src/modules/loot/dto/update-loot-profile.dto.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateLootProfileDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
profile_name?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
loot_table?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
loot_groups?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
112
backend-nest/src/modules/loot/loot.controller.ts
Normal file
112
backend-nest/src/modules/loot/loot.controller.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
|
||||
import { LootService } from './loot.service';
|
||||
import { CreateLootProfileDto } from './dto/create-loot-profile.dto';
|
||||
import { UpdateLootProfileDto } from './dto/update-loot-profile.dto';
|
||||
import { ApplyLootProfileDto } from './dto/apply-loot-profile.dto';
|
||||
import { ImportLootProfileDto } from './dto/import-loot-profile.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('loot')
|
||||
@ApiBearerAuth()
|
||||
@Controller('loot')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class LootController {
|
||||
constructor(private readonly lootService: LootService) {}
|
||||
|
||||
@Get('profiles')
|
||||
@RequirePermission('loot.view')
|
||||
@ApiOperation({ summary: 'List loot profiles (summaries)' })
|
||||
getProfiles(@CurrentTenant() licenseId: string) {
|
||||
return this.lootService.getProfiles(licenseId);
|
||||
}
|
||||
|
||||
@Get('profiles/:id')
|
||||
@RequirePermission('loot.view')
|
||||
@ApiOperation({ summary: 'Get full loot profile with data' })
|
||||
getProfile(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.lootService.getProfile(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('profiles')
|
||||
@RequirePermission('loot.manage')
|
||||
@ApiOperation({ summary: 'Create loot profile' })
|
||||
createProfile(@CurrentTenant() licenseId: string, @Body() dto: CreateLootProfileDto) {
|
||||
return this.lootService.createProfile(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('profiles/:id')
|
||||
@RequirePermission('loot.manage')
|
||||
@ApiOperation({ summary: 'Update loot profile' })
|
||||
updateProfile(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateLootProfileDto,
|
||||
) {
|
||||
return this.lootService.updateProfile(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('profiles/:id')
|
||||
@RequirePermission('loot.manage')
|
||||
@ApiOperation({ summary: 'Delete loot profile' })
|
||||
deleteProfile(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.lootService.deleteProfile(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('profiles/:id/duplicate')
|
||||
@RequirePermission('loot.manage')
|
||||
@ApiOperation({ summary: 'Duplicate loot profile' })
|
||||
duplicateProfile(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.lootService.duplicateProfile(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('profiles/:id/apply')
|
||||
@RequirePermission('loot.manage')
|
||||
@ApiOperation({ summary: 'Apply loot profile to server with multiplier' })
|
||||
applyToServer(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: ApplyLootProfileDto,
|
||||
) {
|
||||
return this.lootService.applyToServer(licenseId, id, dto.multiplier);
|
||||
}
|
||||
|
||||
@Post('import')
|
||||
@RequirePermission('loot.manage')
|
||||
@ApiOperation({ summary: 'Import BetterLoot/Looty JSON as new profile' })
|
||||
importProfile(@CurrentTenant() licenseId: string, @Body() dto: ImportLootProfileDto) {
|
||||
return this.lootService.importProfile(licenseId, dto);
|
||||
}
|
||||
|
||||
@Get('export/:id')
|
||||
@RequirePermission('loot.view')
|
||||
@ApiOperation({ summary: 'Export loot profile as BetterLoot JSON' })
|
||||
@ApiQuery({ name: 'multiplier', required: false, example: 1 })
|
||||
exportProfile(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Query('multiplier') multiplier: string,
|
||||
) {
|
||||
return this.lootService.exportProfile(licenseId, id, multiplier ? parseInt(multiplier, 10) : 1);
|
||||
}
|
||||
|
||||
@Get('containers')
|
||||
@RequirePermission('loot.view')
|
||||
@ApiOperation({ summary: 'Get list of Rust container prefabs' })
|
||||
getContainers() {
|
||||
return this.lootService.getContainers();
|
||||
}
|
||||
}
|
||||
14
backend-nest/src/modules/loot/loot.module.ts
Normal file
14
backend-nest/src/modules/loot/loot.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { LootController } from './loot.controller';
|
||||
import { LootService } from './loot.service';
|
||||
import { LootProfile } from '../../entities/loot-profile.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([LootProfile])],
|
||||
controllers: [LootController],
|
||||
providers: [LootService, NatsService],
|
||||
exports: [LootService],
|
||||
})
|
||||
export class LootModule {}
|
||||
258
backend-nest/src/modules/loot/loot.service.ts
Normal file
258
backend-nest/src/modules/loot/loot.service.ts
Normal file
@@ -0,0 +1,258 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { LootProfile } from '../../entities/loot-profile.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateLootProfileDto } from './dto/create-loot-profile.dto';
|
||||
import { UpdateLootProfileDto } from './dto/update-loot-profile.dto';
|
||||
import { ImportLootProfileDto } from './dto/import-loot-profile.dto';
|
||||
import { RUST_CONTAINERS } from './data/rust-containers';
|
||||
|
||||
@Injectable()
|
||||
export class LootService {
|
||||
private readonly logger = new Logger(LootService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(LootProfile)
|
||||
private readonly lootRepo: Repository<LootProfile>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List profiles for a license (summaries — no JSONB) */
|
||||
async getProfiles(licenseId: string) {
|
||||
const profiles = await this.lootRepo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'profile_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { profiles };
|
||||
}
|
||||
|
||||
/** Get full profile with JSONB data */
|
||||
async getProfile(licenseId: string, profileId: string) {
|
||||
const profile = await this.lootRepo.findOne({
|
||||
where: { id: profileId, license_id: licenseId },
|
||||
});
|
||||
if (!profile) throw new NotFoundException('Loot profile not found');
|
||||
return { profile };
|
||||
}
|
||||
|
||||
/** Create a new profile */
|
||||
async createProfile(licenseId: string, dto: CreateLootProfileDto) {
|
||||
const profile = this.lootRepo.create({
|
||||
license_id: licenseId,
|
||||
profile_name: dto.profile_name,
|
||||
description: dto.description || null,
|
||||
loot_table: dto.loot_table || {},
|
||||
loot_groups: dto.loot_groups || {},
|
||||
});
|
||||
const saved = await this.lootRepo.save(profile);
|
||||
return { profile: saved };
|
||||
}
|
||||
|
||||
/** Update an existing profile */
|
||||
async updateProfile(licenseId: string, profileId: string, dto: UpdateLootProfileDto) {
|
||||
const profile = await this.lootRepo.findOne({
|
||||
where: { id: profileId, license_id: licenseId },
|
||||
});
|
||||
if (!profile) throw new NotFoundException('Loot profile not found');
|
||||
|
||||
if (dto.profile_name !== undefined) profile.profile_name = dto.profile_name;
|
||||
if (dto.description !== undefined) profile.description = dto.description;
|
||||
if (dto.loot_table !== undefined) profile.loot_table = dto.loot_table;
|
||||
if (dto.loot_groups !== undefined) profile.loot_groups = dto.loot_groups;
|
||||
if (dto.is_active !== undefined) profile.is_active = dto.is_active;
|
||||
profile.updated_at = new Date();
|
||||
|
||||
const saved = await this.lootRepo.save(profile);
|
||||
return { profile: saved };
|
||||
}
|
||||
|
||||
/** Delete a profile */
|
||||
async deleteProfile(licenseId: string, profileId: string) {
|
||||
const result = await this.lootRepo.delete({ id: profileId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('Loot profile not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Duplicate a profile */
|
||||
async duplicateProfile(licenseId: string, profileId: string) {
|
||||
const source = await this.lootRepo.findOne({
|
||||
where: { id: profileId, license_id: licenseId },
|
||||
});
|
||||
if (!source) throw new NotFoundException('Loot profile not found');
|
||||
|
||||
const copy = this.lootRepo.create({
|
||||
license_id: licenseId,
|
||||
profile_name: `${source.profile_name} (Copy)`,
|
||||
description: source.description,
|
||||
loot_table: JSON.parse(JSON.stringify(source.loot_table)),
|
||||
loot_groups: JSON.parse(JSON.stringify(source.loot_groups)),
|
||||
is_active: false,
|
||||
});
|
||||
const saved = await this.lootRepo.save(copy);
|
||||
return { profile: saved };
|
||||
}
|
||||
|
||||
/** Apply profile to server with multiplier */
|
||||
async applyToServer(licenseId: string, profileId: string, multiplier: number) {
|
||||
const profile = await this.lootRepo.findOne({
|
||||
where: { id: profileId, license_id: licenseId },
|
||||
});
|
||||
if (!profile) throw new NotFoundException('Loot profile not found');
|
||||
|
||||
// Deep clone and apply multiplier
|
||||
const scaledTable = JSON.parse(JSON.stringify(profile.loot_table));
|
||||
const scaledGroups = JSON.parse(JSON.stringify(profile.loot_groups));
|
||||
|
||||
if (multiplier !== 1) {
|
||||
this.applyMultiplierToTable(scaledTable, multiplier);
|
||||
this.applyMultiplierToGroups(scaledGroups, multiplier);
|
||||
}
|
||||
|
||||
const lootTablesJson = JSON.stringify(scaledTable, null, 2);
|
||||
const lootGroupsJson = JSON.stringify(scaledGroups, null, 2);
|
||||
|
||||
try {
|
||||
// Write LootTables.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/data/BetterLoot/LootTables.json',
|
||||
content: lootTablesJson,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Write LootGroups.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/data/BetterLoot/LootGroups.json',
|
||||
content: lootGroupsJson,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload BetterLoot plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload BetterLoot',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this profile as active, deactivate others
|
||||
await this.lootRepo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.lootRepo.update(
|
||||
{ id: profileId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Profile "${profile.profile_name}" applied with ${multiplier}x multiplier`,
|
||||
profile_name: profile.profile_name,
|
||||
multiplier,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to apply loot profile: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to apply loot profile — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import BetterLoot/Looty JSON as a new profile */
|
||||
async importProfile(licenseId: string, dto: ImportLootProfileDto) {
|
||||
const profile = this.lootRepo.create({
|
||||
license_id: licenseId,
|
||||
profile_name: dto.profile_name,
|
||||
description: dto.description || 'Imported profile',
|
||||
loot_table: dto.loot_table,
|
||||
loot_groups: dto.loot_groups || {},
|
||||
});
|
||||
const saved = await this.lootRepo.save(profile);
|
||||
return { profile: saved };
|
||||
}
|
||||
|
||||
/** Export profile as BetterLoot-compatible JSON with optional multiplier */
|
||||
async exportProfile(licenseId: string, profileId: string, multiplier: number) {
|
||||
const profile = await this.lootRepo.findOne({
|
||||
where: { id: profileId, license_id: licenseId },
|
||||
});
|
||||
if (!profile) throw new NotFoundException('Loot profile not found');
|
||||
|
||||
const exportTable = JSON.parse(JSON.stringify(profile.loot_table));
|
||||
const exportGroups = JSON.parse(JSON.stringify(profile.loot_groups));
|
||||
|
||||
if (multiplier && multiplier !== 1) {
|
||||
this.applyMultiplierToTable(exportTable, multiplier);
|
||||
this.applyMultiplierToGroups(exportGroups, multiplier);
|
||||
}
|
||||
|
||||
return {
|
||||
profile_name: profile.profile_name,
|
||||
multiplier: multiplier || 1,
|
||||
loot_table: exportTable,
|
||||
loot_groups: exportGroups,
|
||||
};
|
||||
}
|
||||
|
||||
/** Get static list of Rust container prefabs */
|
||||
getContainers() {
|
||||
return { containers: RUST_CONTAINERS };
|
||||
}
|
||||
|
||||
// --- Multiplier helpers ---
|
||||
|
||||
private applyMultiplierToTable(table: Record<string, any>, multiplier: number) {
|
||||
for (const prefab of Object.values(table)) {
|
||||
if (prefab?.ItemSettings) {
|
||||
this.scaleField(prefab.ItemSettings, 'ItemsMin', multiplier);
|
||||
this.scaleField(prefab.ItemSettings, 'ItemsMax', multiplier);
|
||||
this.scaleField(prefab.ItemSettings, 'MinScrap', multiplier);
|
||||
this.scaleField(prefab.ItemSettings, 'MaxScrap', multiplier);
|
||||
}
|
||||
if (prefab?.GuaranteedItems) {
|
||||
this.scaleItems(prefab.GuaranteedItems, multiplier);
|
||||
}
|
||||
if (prefab?.UngroupedItems) {
|
||||
this.scaleItems(prefab.UngroupedItems, multiplier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private applyMultiplierToGroups(groups: Record<string, any>, multiplier: number) {
|
||||
for (const group of Object.values(groups)) {
|
||||
if (group?.GuaranteedItems) {
|
||||
this.scaleItems(group.GuaranteedItems, multiplier);
|
||||
}
|
||||
if (group?.ItemList) {
|
||||
this.scaleItems(group.ItemList, multiplier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private scaleItems(items: Record<string, any>, multiplier: number) {
|
||||
for (const item of Object.values(items)) {
|
||||
this.scaleField(item, 'Min', multiplier);
|
||||
this.scaleField(item, 'Max', multiplier);
|
||||
// Recursively scale bonus items
|
||||
if (item?.BonusItems) {
|
||||
this.scaleItems(item.BonusItems, multiplier);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private scaleField(obj: Record<string, any>, field: string, multiplier: number) {
|
||||
if (typeof obj[field] === 'number') {
|
||||
obj[field] = Math.round(obj[field] * multiplier);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateRaidableBasesConfigDto {
|
||||
@ApiProperty({ example: 'Default RaidableBases Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard RaidableBases settings' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportRaidableBasesConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateRaidableBasesConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { RaidableBasesService } from './raidablebases.service';
|
||||
import { CreateRaidableBasesConfigDto } from './dto/create-raidablebases-config.dto';
|
||||
import { UpdateRaidableBasesConfigDto } from './dto/update-raidablebases-config.dto';
|
||||
import { ImportRaidableBasesConfigDto } from './dto/import-raidablebases-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('raidablebases')
|
||||
@ApiBearerAuth()
|
||||
@Controller('raidablebases')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class RaidableBasesController {
|
||||
constructor(private readonly raidableBasesService: RaidableBasesService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('raidablebases.view')
|
||||
@ApiOperation({ summary: 'List RaidableBases configs (summaries)' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.raidableBasesService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('raidablebases.view')
|
||||
@ApiOperation({ summary: 'Get full RaidableBases config with data' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.raidableBasesService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('raidablebases.manage')
|
||||
@ApiOperation({ summary: 'Create RaidableBases config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateRaidableBasesConfigDto) {
|
||||
return this.raidableBasesService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('raidablebases.manage')
|
||||
@ApiOperation({ summary: 'Update RaidableBases config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateRaidableBasesConfigDto,
|
||||
) {
|
||||
return this.raidableBasesService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('raidablebases.manage')
|
||||
@ApiOperation({ summary: 'Delete RaidableBases config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.raidableBasesService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('raidablebases.manage')
|
||||
@ApiOperation({ summary: 'Deploy RaidableBases config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.raidableBasesService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('raidablebases.manage')
|
||||
@ApiOperation({ summary: 'Import RaidableBases.json from server via NATS' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportRaidableBasesConfigDto) {
|
||||
return this.raidableBasesService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { RaidableBasesController } from './raidablebases.controller';
|
||||
import { RaidableBasesService } from './raidablebases.service';
|
||||
import { RaidableBasesConfig } from '../../entities/raidablebases-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([RaidableBasesConfig])],
|
||||
controllers: [RaidableBasesController],
|
||||
providers: [RaidableBasesService, NatsService],
|
||||
exports: [RaidableBasesService],
|
||||
})
|
||||
export class RaidableBasesModule {}
|
||||
180
backend-nest/src/modules/raidablebases/raidablebases.service.ts
Normal file
180
backend-nest/src/modules/raidablebases/raidablebases.service.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { RaidableBasesConfig } from '../../entities/raidablebases-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateRaidableBasesConfigDto } from './dto/create-raidablebases-config.dto';
|
||||
import { UpdateRaidableBasesConfigDto } from './dto/update-raidablebases-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class RaidableBasesService {
|
||||
private readonly logger = new Logger(RaidableBasesService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(RaidableBasesConfig)
|
||||
private readonly raidableBasesRepo: Repository<RaidableBasesConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.raidableBasesRepo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.raidableBasesRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('RaidableBases config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateRaidableBasesConfigDto) {
|
||||
const config = this.raidableBasesRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.raidableBasesRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateRaidableBasesConfigDto) {
|
||||
const config = await this.raidableBasesRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('RaidableBases config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.raidableBasesRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.raidableBasesRepo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('RaidableBases config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.raidableBasesRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('RaidableBases config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write RaidableBases.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/RaidableBases.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload RaidableBases plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload RaidableBases',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.raidableBasesRepo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.raidableBasesRepo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy RaidableBases config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy RaidableBases config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import RaidableBases.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read RaidableBases.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/RaidableBases.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new RaidableBases config row
|
||||
const config = this.raidableBasesRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.raidableBasesRepo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import RaidableBases config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import RaidableBases config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,4 +73,11 @@ export class ServersController {
|
||||
) {
|
||||
return await this.serversService.deployServer(licenseId, dto);
|
||||
}
|
||||
|
||||
@Post('install-oxide')
|
||||
@RequirePermission('server.manage')
|
||||
@ApiOperation({ summary: 'Install Oxide/uMod via companion agent' })
|
||||
async installOxide(@CurrentTenant() licenseId: string) {
|
||||
return await this.serversService.installOxide(licenseId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,4 +103,12 @@ export class ServersService {
|
||||
await this.natsService.sendDeployCommand(licenseId, { ...dto });
|
||||
return { message: 'Deployment started' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Install Oxide/uMod via companion agent
|
||||
*/
|
||||
async installOxide(licenseId: string) {
|
||||
await this.natsService.sendOxideInstallCommand(licenseId);
|
||||
return { message: 'Oxide installation started' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateTeleportConfigDto {
|
||||
@ApiProperty({ example: 'Default Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard NTeleportation settings' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportTeleportConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateTeleportConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
80
backend-nest/src/modules/teleport/teleport.controller.ts
Normal file
80
backend-nest/src/modules/teleport/teleport.controller.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { TeleportService } from './teleport.service';
|
||||
import { CreateTeleportConfigDto } from './dto/create-teleport-config.dto';
|
||||
import { UpdateTeleportConfigDto } from './dto/update-teleport-config.dto';
|
||||
import { ImportTeleportConfigDto } from './dto/import-teleport-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('teleport')
|
||||
@ApiBearerAuth()
|
||||
@Controller('teleport')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class TeleportController {
|
||||
constructor(private readonly teleportService: TeleportService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('teleport.view')
|
||||
@ApiOperation({ summary: 'List teleport configs (summaries)' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.teleportService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('teleport.view')
|
||||
@ApiOperation({ summary: 'Get full teleport config with data' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.teleportService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('teleport.manage')
|
||||
@ApiOperation({ summary: 'Create teleport config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateTeleportConfigDto) {
|
||||
return this.teleportService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('teleport.manage')
|
||||
@ApiOperation({ summary: 'Update teleport config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateTeleportConfigDto,
|
||||
) {
|
||||
return this.teleportService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('teleport.manage')
|
||||
@ApiOperation({ summary: 'Delete teleport config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.teleportService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('teleport.manage')
|
||||
@ApiOperation({ summary: 'Deploy teleport config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.teleportService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('teleport.manage')
|
||||
@ApiOperation({ summary: 'Import NTeleportation.json from server via NATS' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportTeleportConfigDto) {
|
||||
return this.teleportService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
14
backend-nest/src/modules/teleport/teleport.module.ts
Normal file
14
backend-nest/src/modules/teleport/teleport.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { TeleportController } from './teleport.controller';
|
||||
import { TeleportService } from './teleport.service';
|
||||
import { TeleportConfig } from '../../entities/teleport-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([TeleportConfig])],
|
||||
controllers: [TeleportController],
|
||||
providers: [TeleportService, NatsService],
|
||||
exports: [TeleportService],
|
||||
})
|
||||
export class TeleportModule {}
|
||||
180
backend-nest/src/modules/teleport/teleport.service.ts
Normal file
180
backend-nest/src/modules/teleport/teleport.service.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { TeleportConfig } from '../../entities/teleport-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateTeleportConfigDto } from './dto/create-teleport-config.dto';
|
||||
import { UpdateTeleportConfigDto } from './dto/update-teleport-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TeleportService {
|
||||
private readonly logger = new Logger(TeleportService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(TeleportConfig)
|
||||
private readonly teleportRepo: Repository<TeleportConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.teleportRepo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.teleportRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Teleport config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateTeleportConfigDto) {
|
||||
const config = this.teleportRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.teleportRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateTeleportConfigDto) {
|
||||
const config = await this.teleportRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Teleport config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.teleportRepo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.teleportRepo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('Teleport config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.teleportRepo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('Teleport config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write NTeleportation.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/NTeleportation.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload NTeleportation plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload NTeleportation',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.teleportRepo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.teleportRepo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy teleport config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy teleport config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import NTeleportation.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read NTeleportation.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/NTeleportation.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new teleport config row
|
||||
const config = this.teleportRepo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.teleportRepo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import teleport config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import teleport config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsString, IsOptional, IsObject, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateTimedExecuteConfigDto {
|
||||
@ApiProperty({ example: 'Default Timer Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Standard TimedExecute settings' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { IsString, IsOptional, MaxLength } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class ImportTimedExecuteConfigDto {
|
||||
@ApiProperty({ example: 'Server Import' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
config_name: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Imported from live server' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { IsString, IsOptional, IsObject, IsBoolean, MaxLength } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class UpdateTimedExecuteConfigDto {
|
||||
@ApiPropertyOptional({ example: 'Updated Timer Config' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
@IsOptional()
|
||||
config_name?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: 'Updated description' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
config_data?: Record<string, any>;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
is_active?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { TimedExecuteService } from './timedexecute.service';
|
||||
import { CreateTimedExecuteConfigDto } from './dto/create-timedexecute-config.dto';
|
||||
import { UpdateTimedExecuteConfigDto } from './dto/update-timedexecute-config.dto';
|
||||
import { ImportTimedExecuteConfigDto } from './dto/import-timedexecute-config.dto';
|
||||
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { PermissionsGuard } from '../../common/guards/permissions.guard';
|
||||
|
||||
@ApiTags('timedexecute')
|
||||
@ApiBearerAuth()
|
||||
@Controller('timedexecute')
|
||||
@UseGuards(JwtAuthGuard, PermissionsGuard)
|
||||
export class TimedExecuteController {
|
||||
constructor(private readonly timedExecuteService: TimedExecuteService) {}
|
||||
|
||||
@Get('configs')
|
||||
@RequirePermission('timedexecute.view')
|
||||
@ApiOperation({ summary: 'List TimedExecute configs (summaries)' })
|
||||
getConfigs(@CurrentTenant() licenseId: string) {
|
||||
return this.timedExecuteService.getConfigs(licenseId);
|
||||
}
|
||||
|
||||
@Get('configs/:id')
|
||||
@RequirePermission('timedexecute.view')
|
||||
@ApiOperation({ summary: 'Get full TimedExecute config with data' })
|
||||
getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.timedExecuteService.getConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs')
|
||||
@RequirePermission('timedexecute.manage')
|
||||
@ApiOperation({ summary: 'Create TimedExecute config' })
|
||||
createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateTimedExecuteConfigDto) {
|
||||
return this.timedExecuteService.createConfig(licenseId, dto);
|
||||
}
|
||||
|
||||
@Put('configs/:id')
|
||||
@RequirePermission('timedexecute.manage')
|
||||
@ApiOperation({ summary: 'Update TimedExecute config' })
|
||||
updateConfig(
|
||||
@CurrentTenant() licenseId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateTimedExecuteConfigDto,
|
||||
) {
|
||||
return this.timedExecuteService.updateConfig(licenseId, id, dto);
|
||||
}
|
||||
|
||||
@Delete('configs/:id')
|
||||
@RequirePermission('timedexecute.manage')
|
||||
@ApiOperation({ summary: 'Delete TimedExecute config' })
|
||||
deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.timedExecuteService.deleteConfig(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('configs/:id/apply')
|
||||
@RequirePermission('timedexecute.manage')
|
||||
@ApiOperation({ summary: 'Deploy TimedExecute config to server' })
|
||||
applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
|
||||
return this.timedExecuteService.applyToServer(licenseId, id);
|
||||
}
|
||||
|
||||
@Post('import-from-server')
|
||||
@RequirePermission('timedexecute.manage')
|
||||
@ApiOperation({ summary: 'Import TimedExecute.json from server via NATS' })
|
||||
importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportTimedExecuteConfigDto) {
|
||||
return this.timedExecuteService.importFromServer(licenseId, dto.config_name, dto.description);
|
||||
}
|
||||
}
|
||||
14
backend-nest/src/modules/timedexecute/timedexecute.module.ts
Normal file
14
backend-nest/src/modules/timedexecute/timedexecute.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { TimedExecuteController } from './timedexecute.controller';
|
||||
import { TimedExecuteService } from './timedexecute.service';
|
||||
import { TimedExecuteConfig } from '../../entities/timedexecute-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([TimedExecuteConfig])],
|
||||
controllers: [TimedExecuteController],
|
||||
providers: [TimedExecuteService, NatsService],
|
||||
exports: [TimedExecuteService],
|
||||
})
|
||||
export class TimedExecuteModule {}
|
||||
180
backend-nest/src/modules/timedexecute/timedexecute.service.ts
Normal file
180
backend-nest/src/modules/timedexecute/timedexecute.service.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { Injectable, Logger, NotFoundException, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { TimedExecuteConfig } from '../../entities/timedexecute-config.entity';
|
||||
import { NatsService } from '../../services/nats.service';
|
||||
import { CreateTimedExecuteConfigDto } from './dto/create-timedexecute-config.dto';
|
||||
import { UpdateTimedExecuteConfigDto } from './dto/update-timedexecute-config.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TimedExecuteService {
|
||||
private readonly logger = new Logger(TimedExecuteService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(TimedExecuteConfig)
|
||||
private readonly repo: Repository<TimedExecuteConfig>,
|
||||
private readonly natsService: NatsService,
|
||||
) {}
|
||||
|
||||
/** List configs for a license (summaries — no JSONB) */
|
||||
async getConfigs(licenseId: string) {
|
||||
const configs = await this.repo.find({
|
||||
where: { license_id: licenseId },
|
||||
select: ['id', 'config_name', 'description', 'is_active', 'created_at', 'updated_at'],
|
||||
order: { created_at: 'DESC' },
|
||||
});
|
||||
return { configs };
|
||||
}
|
||||
|
||||
/** Get full config with JSONB data */
|
||||
async getConfig(licenseId: string, configId: string) {
|
||||
const config = await this.repo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('TimedExecute config not found');
|
||||
return { config };
|
||||
}
|
||||
|
||||
/** Create a new config */
|
||||
async createConfig(licenseId: string, dto: CreateTimedExecuteConfigDto) {
|
||||
const config = this.repo.create({
|
||||
license_id: licenseId,
|
||||
config_name: dto.config_name,
|
||||
description: dto.description || null,
|
||||
config_data: dto.config_data || {},
|
||||
});
|
||||
const saved = await this.repo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Update an existing config */
|
||||
async updateConfig(licenseId: string, configId: string, dto: UpdateTimedExecuteConfigDto) {
|
||||
const config = await this.repo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('TimedExecute config not found');
|
||||
|
||||
if (dto.config_name !== undefined) config.config_name = dto.config_name;
|
||||
if (dto.description !== undefined) config.description = dto.description;
|
||||
if (dto.config_data !== undefined) config.config_data = dto.config_data;
|
||||
if (dto.is_active !== undefined) config.is_active = dto.is_active;
|
||||
config.updated_at = new Date();
|
||||
|
||||
const saved = await this.repo.save(config);
|
||||
return { config: saved };
|
||||
}
|
||||
|
||||
/** Delete a config */
|
||||
async deleteConfig(licenseId: string, configId: string) {
|
||||
const result = await this.repo.delete({ id: configId, license_id: licenseId });
|
||||
if (result.affected === 0) throw new NotFoundException('TimedExecute config not found');
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Deploy config to game server via NATS */
|
||||
async applyToServer(licenseId: string, configId: string) {
|
||||
const config = await this.repo.findOne({
|
||||
where: { id: configId, license_id: licenseId },
|
||||
});
|
||||
if (!config) throw new NotFoundException('TimedExecute config not found');
|
||||
|
||||
const jsonString = JSON.stringify(config.config_data, null, 2);
|
||||
|
||||
try {
|
||||
// Write TimedExecute.json via file manager NATS
|
||||
await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_save',
|
||||
path: 'server://oxide/config/TimedExecute.json',
|
||||
content: jsonString,
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
// Reload TimedExecute plugin via RCON
|
||||
await this.natsService.publish(
|
||||
`corrosion.${licenseId}.cmd.server`,
|
||||
{
|
||||
action: 'command',
|
||||
command: 'oxide.reload TimedExecute',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
// Mark this config as active, deactivate others
|
||||
await this.repo.update({ license_id: licenseId }, { is_active: false });
|
||||
await this.repo.update(
|
||||
{ id: configId, license_id: licenseId },
|
||||
{ is_active: true, updated_at: new Date() },
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `Config "${config.config_name}" deployed to server`,
|
||||
config_name: config.config_name,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to deploy TimedExecute config: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to deploy TimedExecute config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Import TimedExecute.json from game server via NATS */
|
||||
async importFromServer(licenseId: string, configName: string, description?: string) {
|
||||
try {
|
||||
// Read TimedExecute.json from server via file manager NATS
|
||||
const response = await this.natsService.request(
|
||||
`corrosion.${licenseId}.files.cmd`,
|
||||
{
|
||||
func: 'fm_preview',
|
||||
path: 'server://oxide/config/TimedExecute.json',
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
throw new HttpException(
|
||||
'No response from agent — it may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
// Parse the response content as JSON
|
||||
const responseData = response as Record<string, any>;
|
||||
let configData: Record<string, any>;
|
||||
|
||||
if (typeof responseData.content === 'string') {
|
||||
configData = JSON.parse(responseData.content);
|
||||
} else if (typeof responseData.content === 'object') {
|
||||
configData = responseData.content;
|
||||
} else {
|
||||
throw new HttpException(
|
||||
'Unexpected response format from agent',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
// Create new config row
|
||||
const config = this.repo.create({
|
||||
license_id: licenseId,
|
||||
config_name: configName,
|
||||
description: description || 'Imported from server',
|
||||
config_data: configData,
|
||||
});
|
||||
const saved = await this.repo.save(config);
|
||||
|
||||
return { config: saved };
|
||||
} catch (error) {
|
||||
if (error instanceof HttpException) throw error;
|
||||
this.logger.error(`Failed to import TimedExecute config from server: ${(error as Error).message}`);
|
||||
throw new HttpException(
|
||||
'Failed to import TimedExecute config — agent may be offline',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,11 @@ export class NatsBridgeService implements OnModuleInit {
|
||||
this.emit(licenseId, 'deploy_status', data);
|
||||
});
|
||||
|
||||
this.nats.subscribe('corrosion.*.oxide.status', (data, subject) => {
|
||||
const licenseId = subject.split('.')[1];
|
||||
this.emit(licenseId, 'oxide_status', data);
|
||||
});
|
||||
|
||||
this.logger.log('NATS bridge subscriptions initialized');
|
||||
}
|
||||
|
||||
|
||||
@@ -79,4 +79,12 @@ export class NatsService implements OnModuleInit, OnModuleDestroy {
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
/** Publish an Oxide install command to a specific license's companion agent */
|
||||
async sendOxideInstallCommand(licenseId: string): Promise<void> {
|
||||
await this.publish(`corrosion.${licenseId}.cmd.oxide`, {
|
||||
action: 'install_oxide',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
13
backend/migrations/013_loot_profiles.sql
Normal file
13
backend/migrations/013_loot_profiles.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
-- Loot profiles for BetterLoot integration
|
||||
CREATE TABLE loot_profiles (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
profile_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
loot_table JSONB NOT NULL DEFAULT '{}',
|
||||
loot_groups JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_loot_profiles_license ON loot_profiles(license_id);
|
||||
12
backend/migrations/014_teleport_configs.sql
Normal file
12
backend/migrations/014_teleport_configs.sql
Normal file
@@ -0,0 +1,12 @@
|
||||
-- Teleport configuration profiles for NTeleportation integration
|
||||
CREATE TABLE teleport_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_teleport_configs_license ON teleport_configs(license_id);
|
||||
11
backend/migrations/015_gather_configs.sql
Normal file
11
backend/migrations/015_gather_configs.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS gather_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_gather_configs_license ON gather_configs(license_id);
|
||||
11
backend/migrations/016_kits_configs.sql
Normal file
11
backend/migrations/016_kits_configs.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS kits_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_kits_configs_license ON kits_configs(license_id);
|
||||
11
backend/migrations/017_betterchat_configs.sql
Normal file
11
backend/migrations/017_betterchat_configs.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS betterchat_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_betterchat_configs_license ON betterchat_configs(license_id);
|
||||
11
backend/migrations/018_autodoors_configs.sql
Normal file
11
backend/migrations/018_autodoors_configs.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS autodoors_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_autodoors_configs_license ON autodoors_configs(license_id);
|
||||
11
backend/migrations/019_furnacesplitter_configs.sql
Normal file
11
backend/migrations/019_furnacesplitter_configs.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS furnacesplitter_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_furnacesplitter_configs_license ON furnacesplitter_configs(license_id);
|
||||
11
backend/migrations/020_timedexecute_configs.sql
Normal file
11
backend/migrations/020_timedexecute_configs.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS timedexecute_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_timedexecute_configs_license ON timedexecute_configs(license_id);
|
||||
11
backend/migrations/021_raidablebases_configs.sql
Normal file
11
backend/migrations/021_raidablebases_configs.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
CREATE TABLE IF NOT EXISTS raidablebases_configs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
license_id UUID NOT NULL REFERENCES licenses(id) ON DELETE CASCADE,
|
||||
config_name VARCHAR(100) NOT NULL,
|
||||
description TEXT,
|
||||
config_data JSONB NOT NULL DEFAULT '{}',
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_raidablebases_configs_license ON raidablebases_configs(license_id);
|
||||
@@ -31,6 +31,10 @@ type Config struct {
|
||||
// Install directory for deployment
|
||||
InstallDir string `envconfig:"INSTALL_DIR" default:""`
|
||||
|
||||
// RCON configuration
|
||||
RconPort int `envconfig:"RCON_PORT" default:"28016"`
|
||||
RconPassword string `envconfig:"RCON_PASSWORD" default:""`
|
||||
|
||||
// Optional settings
|
||||
HeartbeatInterval int `envconfig:"HEARTBEAT_INTERVAL" default:"60"`
|
||||
LogLevel string `envconfig:"LOG_LEVEL" default:"info"`
|
||||
@@ -63,6 +67,7 @@ func main() {
|
||||
log.Printf(" Game Server Path: %s", cfg.GameServerPath)
|
||||
log.Printf(" SteamCMD Path: %s", cfg.SteamCMDPath)
|
||||
log.Printf(" Install Dir: %s", cfg.InstallDir)
|
||||
log.Printf(" RCON Port: %d", cfg.RconPort)
|
||||
log.Printf(" Heartbeat Interval: %ds", cfg.HeartbeatInterval)
|
||||
|
||||
// Create context with signal handling for graceful shutdown
|
||||
@@ -88,6 +93,8 @@ func main() {
|
||||
GameServerArgs: cfg.GameServerArgs,
|
||||
Version: version,
|
||||
InstallDir: cfg.InstallDir,
|
||||
RconPort: cfg.RconPort,
|
||||
RconPassword: cfg.RconPassword,
|
||||
}
|
||||
|
||||
// Start daemon
|
||||
|
||||
@@ -8,6 +8,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/klauspost/compress v1.17.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.5 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
|
||||
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
|
||||
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
|
||||
|
||||
@@ -11,8 +11,10 @@ import (
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/vigilcyber/corrosion-companion/internal/deploy"
|
||||
"github.com/vigilcyber/corrosion-companion/internal/filemanager"
|
||||
"github.com/vigilcyber/corrosion-companion/internal/oxide"
|
||||
"github.com/vigilcyber/corrosion-companion/internal/files"
|
||||
"github.com/vigilcyber/corrosion-companion/internal/process"
|
||||
"github.com/vigilcyber/corrosion-companion/internal/rcon"
|
||||
"github.com/vigilcyber/corrosion-companion/internal/update"
|
||||
)
|
||||
|
||||
@@ -25,18 +27,21 @@ type DaemonConfig struct {
|
||||
GameServerArgs string
|
||||
Version string
|
||||
InstallDir string
|
||||
RconPort int
|
||||
RconPassword string
|
||||
}
|
||||
|
||||
// Daemon manages the companion agent's main operations
|
||||
type Daemon struct {
|
||||
nc *nats.Conn
|
||||
cfg *DaemonConfig
|
||||
gameServer *process.GameServer
|
||||
fileOps *files.Operations
|
||||
fm *filemanager.FileManager
|
||||
updater *update.Updater
|
||||
deployer *deploy.Deployer
|
||||
subscriptions []*nats.Subscription
|
||||
nc *nats.Conn
|
||||
cfg *DaemonConfig
|
||||
gameServer *process.GameServer
|
||||
fileOps *files.Operations
|
||||
fm *filemanager.FileManager
|
||||
updater *update.Updater
|
||||
deployer *deploy.Deployer
|
||||
oxideInstaller *oxide.OxideInstaller
|
||||
subscriptions []*nats.Subscription
|
||||
}
|
||||
|
||||
// HeartbeatPayload represents the data sent in heartbeat messages
|
||||
@@ -53,6 +58,7 @@ type HeartbeatPayload struct {
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
ServerInstalled bool `json:"server_installed"`
|
||||
OxideInstalled bool `json:"oxide_installed"`
|
||||
}
|
||||
|
||||
// gameServerAdapter wraps process.GameServer to satisfy deploy.GameServerStarter
|
||||
@@ -71,6 +77,15 @@ func (a *gameServerAdapter) UpdatePath(path string) {
|
||||
*a.gs = *process.NewGameServer(path, a.cfg.GameServerArgs)
|
||||
}
|
||||
|
||||
// restartAdapter wraps process.GameServer to satisfy oxide.GameServerRestarter
|
||||
type restartAdapter struct {
|
||||
gs *process.GameServer
|
||||
}
|
||||
|
||||
func (a *restartAdapter) Restart() error {
|
||||
return a.gs.Restart()
|
||||
}
|
||||
|
||||
// NewDaemon creates a new daemon instance
|
||||
func NewDaemon(nc *nats.Conn, cfg *DaemonConfig) (*Daemon, error) {
|
||||
gameServer := process.NewGameServer(cfg.GameServerPath, cfg.GameServerArgs)
|
||||
@@ -79,15 +94,18 @@ func NewDaemon(nc *nats.Conn, cfg *DaemonConfig) (*Daemon, error) {
|
||||
updater := update.NewUpdater(cfg.Version)
|
||||
adapter := &gameServerAdapter{gs: gameServer, cfg: cfg}
|
||||
deployer := deploy.NewDeployer(nc, cfg.LicenseID, cfg.InstallDir, adapter)
|
||||
restarter := &restartAdapter{gs: gameServer}
|
||||
oxideInst := oxide.NewOxideInstaller(nc, cfg.LicenseID, cfg.InstallDir, restarter)
|
||||
|
||||
d := &Daemon{
|
||||
nc: nc,
|
||||
cfg: cfg,
|
||||
gameServer: gameServer,
|
||||
fileOps: fileOps,
|
||||
fm: fm,
|
||||
updater: updater,
|
||||
deployer: deployer,
|
||||
nc: nc,
|
||||
cfg: cfg,
|
||||
gameServer: gameServer,
|
||||
fileOps: fileOps,
|
||||
fm: fm,
|
||||
updater: updater,
|
||||
deployer: deployer,
|
||||
oxideInstaller: oxideInst,
|
||||
}
|
||||
|
||||
return d, nil
|
||||
@@ -122,6 +140,11 @@ func (d *Daemon) Run(ctx context.Context) error {
|
||||
return fmt.Errorf("failed to subscribe to deploy commands: %w", err)
|
||||
}
|
||||
|
||||
// Subscribe to Oxide install commands
|
||||
if err := d.subscribeOxideInstall(); err != nil {
|
||||
return fmt.Errorf("failed to subscribe to oxide install commands: %w", err)
|
||||
}
|
||||
|
||||
// Subscribe to file manager commands (VueFinder-compatible request-reply)
|
||||
if err := d.subscribeFileManager(); err != nil {
|
||||
return fmt.Errorf("failed to subscribe to file manager commands: %w", err)
|
||||
@@ -155,7 +178,8 @@ func (d *Daemon) subscribeServerCommands() error {
|
||||
|
||||
sub, err := d.nc.Subscribe(subject, func(msg *nats.Msg) {
|
||||
var cmd struct {
|
||||
Action string `json:"action"`
|
||||
Action string `json:"action"`
|
||||
Command string `json:"command"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(msg.Data, &cmd); err != nil {
|
||||
@@ -174,6 +198,24 @@ func (d *Daemon) subscribeServerCommands() error {
|
||||
err = d.gameServer.Stop()
|
||||
case "restart":
|
||||
err = d.gameServer.Restart()
|
||||
case "command":
|
||||
if cmd.Command == "" {
|
||||
d.respondError(msg, "invalid_command", "command field is required")
|
||||
return
|
||||
}
|
||||
result, rconErr := rcon.SendCommand(d.cfg.RconPort, d.cfg.RconPassword, cmd.Command)
|
||||
if rconErr != nil {
|
||||
log.Printf("RCON command failed: %v", rconErr)
|
||||
d.respondError(msg, "rcon_failed", rconErr.Error())
|
||||
} else {
|
||||
d.respondSuccess(msg, map[string]interface{}{
|
||||
"action": "command",
|
||||
"command": cmd.Command,
|
||||
"response": result,
|
||||
"status": "success",
|
||||
})
|
||||
}
|
||||
return
|
||||
default:
|
||||
err = fmt.Errorf("unknown action: %s", cmd.Action)
|
||||
}
|
||||
@@ -367,6 +409,38 @@ func (d *Daemon) subscribeFileManager() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// subscribeOxideInstall subscribes to Oxide installation commands
|
||||
func (d *Daemon) subscribeOxideInstall() error {
|
||||
subject := fmt.Sprintf("corrosion.%s.cmd.oxide", d.cfg.LicenseID)
|
||||
|
||||
sub, err := d.nc.Subscribe(subject, func(msg *nats.Msg) {
|
||||
log.Println("Received Oxide install command")
|
||||
|
||||
// Run installation in goroutine (it's long-running)
|
||||
go func() {
|
||||
if err := d.oxideInstaller.Install(); err != nil {
|
||||
log.Printf("Oxide installation failed: %v", err)
|
||||
} else {
|
||||
log.Println("Oxide installation completed successfully")
|
||||
}
|
||||
}()
|
||||
|
||||
// Immediately acknowledge the command
|
||||
d.respondSuccess(msg, map[string]interface{}{
|
||||
"status": "accepted",
|
||||
"message": "Oxide installation started, progress will be published to oxide.status",
|
||||
})
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d.subscriptions = append(d.subscriptions, sub)
|
||||
log.Printf("Subscribed to: %s", subject)
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleFileOperation processes file operation requests
|
||||
func (d *Daemon) handleFileOperation(msg *nats.Msg) {
|
||||
// Parse common fields
|
||||
@@ -437,6 +511,7 @@ func (d *Daemon) publishHeartbeat() {
|
||||
OS: runtime.GOOS,
|
||||
Arch: runtime.GOARCH,
|
||||
ServerInstalled: deploy.CheckServerInstalled(d.cfg.InstallDir),
|
||||
OxideInstalled: oxide.CheckOxideInstalled(d.cfg.InstallDir),
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
|
||||
250
companion-agent/internal/oxide/installer.go
Normal file
250
companion-agent/internal/oxide/installer.go
Normal file
@@ -0,0 +1,250 @@
|
||||
package oxide
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
// GameServerRestarter abstracts the game server process manager so the installer
|
||||
// can restart the server after extracting Oxide files.
|
||||
type GameServerRestarter interface {
|
||||
Restart() error
|
||||
}
|
||||
|
||||
// OxideInstaller handles downloading and extracting Oxide/uMod over a Rust server installation.
|
||||
type OxideInstaller struct {
|
||||
nc *nats.Conn
|
||||
licenseID string
|
||||
installDir string
|
||||
gameServer GameServerRestarter
|
||||
}
|
||||
|
||||
// NewOxideInstaller creates a new OxideInstaller instance.
|
||||
func NewOxideInstaller(nc *nats.Conn, licenseID, installDir string, gs GameServerRestarter) *OxideInstaller {
|
||||
return &OxideInstaller{
|
||||
nc: nc,
|
||||
licenseID: licenseID,
|
||||
installDir: installDir,
|
||||
gameServer: gs,
|
||||
}
|
||||
}
|
||||
|
||||
// githubRelease represents the relevant fields from the GitHub Releases API response.
|
||||
type githubRelease struct {
|
||||
TagName string `json:"tag_name"`
|
||||
Assets []githubAsset `json:"assets"`
|
||||
}
|
||||
|
||||
type githubAsset struct {
|
||||
Name string `json:"name"`
|
||||
BrowserDownloadURL string `json:"browser_download_url"`
|
||||
}
|
||||
|
||||
// Install performs the full Oxide installation pipeline:
|
||||
// 1. Fetch latest release info from GitHub
|
||||
// 2. Download the zip
|
||||
// 3. Extract over {installDir}/server/
|
||||
// 4. Restart the game server
|
||||
func (o *OxideInstaller) Install() error {
|
||||
// Stage 1: Fetch latest release
|
||||
log.Printf("Oxide: fetching latest release for license %s", o.licenseID)
|
||||
o.publishStatus("fetching_release", 0, "Checking latest Oxide release...")
|
||||
|
||||
release, err := o.fetchLatestRelease()
|
||||
if err != nil {
|
||||
o.publishStatus("failed", 0, "Failed to fetch Oxide release info", err.Error())
|
||||
return fmt.Errorf("fetch release failed: %w", err)
|
||||
}
|
||||
|
||||
if len(release.Assets) == 0 {
|
||||
err := fmt.Errorf("no assets found in release %s", release.TagName)
|
||||
o.publishStatus("failed", 0, "No download assets in release", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
downloadURL := release.Assets[0].BrowserDownloadURL
|
||||
version := release.TagName
|
||||
log.Printf("Oxide: latest version is %s, download URL: %s", version, downloadURL)
|
||||
o.publishStatus("fetching_release", 100, fmt.Sprintf("Found Oxide %s", version))
|
||||
|
||||
// Stage 2: Download zip
|
||||
log.Printf("Oxide: downloading %s", downloadURL)
|
||||
o.publishStatus("downloading", 0, fmt.Sprintf("Downloading Oxide %s...", version))
|
||||
|
||||
tmpPath := filepath.Join(os.TempDir(), "oxide-latest.zip")
|
||||
if err := o.downloadFile(downloadURL, tmpPath); err != nil {
|
||||
o.publishStatus("failed", 0, "Failed to download Oxide", err.Error())
|
||||
return fmt.Errorf("download failed: %w", err)
|
||||
}
|
||||
defer os.Remove(tmpPath)
|
||||
|
||||
log.Printf("Oxide: download complete")
|
||||
o.publishStatus("downloading", 100, "Download complete")
|
||||
|
||||
// Stage 3: Extract over server directory
|
||||
serverDir := filepath.Join(o.installDir, "server")
|
||||
log.Printf("Oxide: extracting to %s", serverDir)
|
||||
o.publishStatus("installing", 0, "Extracting Oxide over server directory...")
|
||||
|
||||
if err := o.extractZip(tmpPath, serverDir); err != nil {
|
||||
o.publishStatus("failed", 0, "Failed to extract Oxide", err.Error())
|
||||
return fmt.Errorf("extract failed: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Oxide: extraction complete")
|
||||
o.publishStatus("installing", 100, "Oxide files extracted")
|
||||
|
||||
// Stage 4: Restart server
|
||||
log.Printf("Oxide: restarting server")
|
||||
o.publishStatus("restarting", 0, "Restarting server to load Oxide...")
|
||||
|
||||
if err := o.gameServer.Restart(); err != nil {
|
||||
o.publishStatus("failed", 0, "Server restart failed", err.Error())
|
||||
return fmt.Errorf("server restart failed: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("Oxide: server restarted, installation complete")
|
||||
o.publishStatus("complete", 100, fmt.Sprintf("Oxide %s installed successfully", version))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchLatestRelease queries the GitHub API for the latest Oxide.Rust release.
|
||||
func (o *OxideInstaller) fetchLatestRelease() (*githubRelease, error) {
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
|
||||
resp, err := client.Get("https://api.github.com/repos/OxideMod/Oxide.Rust/releases/latest")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GitHub API request failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("GitHub API returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var release githubRelease
|
||||
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse GitHub API response: %w", err)
|
||||
}
|
||||
|
||||
return &release, nil
|
||||
}
|
||||
|
||||
// downloadFile downloads a URL to a local file path.
|
||||
func (o *OxideInstaller) downloadFile(url, destPath string) error {
|
||||
client := &http.Client{Timeout: 5 * time.Minute}
|
||||
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("HTTP GET failed: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("download returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
out, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file %s: %w", destPath, err)
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := io.Copy(out, resp.Body); err != nil {
|
||||
return fmt.Errorf("failed to write download: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractZip extracts a zip file to a destination directory, overwriting existing files.
|
||||
// This is used to overlay Oxide's DLLs over the Rust server's Managed directory
|
||||
// and create the oxide/ folder structure.
|
||||
func (o *OxideInstaller) extractZip(zipPath, destDir string) error {
|
||||
r, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open zip: %w", err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
for _, f := range r.File {
|
||||
targetPath := filepath.Join(destDir, f.Name)
|
||||
|
||||
// Security: prevent path traversal
|
||||
if !strings.HasPrefix(targetPath, filepath.Clean(destDir)+string(os.PathSeparator)) && targetPath != filepath.Clean(destDir) {
|
||||
log.Printf("Oxide: skipping potentially unsafe path: %s", f.Name)
|
||||
continue
|
||||
}
|
||||
|
||||
if f.FileInfo().IsDir() {
|
||||
if err := os.MkdirAll(targetPath, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create directory %s: %w", targetPath, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
|
||||
return fmt.Errorf("failed to create parent directory for %s: %w", targetPath, err)
|
||||
}
|
||||
|
||||
outFile, err := os.OpenFile(targetPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file %s: %w", targetPath, err)
|
||||
}
|
||||
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
outFile.Close()
|
||||
return fmt.Errorf("failed to open zip entry %s: %w", f.Name, err)
|
||||
}
|
||||
|
||||
_, err = io.Copy(outFile, rc)
|
||||
rc.Close()
|
||||
outFile.Close()
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to extract %s: %w", f.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// publishStatus publishes an OxideStatus message to NATS. Publish errors are logged
|
||||
// but do not fail the installation — losing a progress update is not fatal.
|
||||
func (o *OxideInstaller) publishStatus(stage string, progress int, message string, errDetail ...string) {
|
||||
subject := fmt.Sprintf("corrosion.%s.oxide.status", o.licenseID)
|
||||
|
||||
status := OxideStatus{
|
||||
Stage: stage,
|
||||
Progress: progress,
|
||||
Message: message,
|
||||
Timestamp: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if len(errDetail) > 0 && errDetail[0] != "" {
|
||||
status.Error = errDetail[0]
|
||||
}
|
||||
|
||||
data, err := json.Marshal(status)
|
||||
if err != nil {
|
||||
log.Printf("Failed to marshal oxide status: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := o.nc.Publish(subject, data); err != nil {
|
||||
log.Printf("Failed to publish oxide status to %s: %v", subject, err)
|
||||
}
|
||||
}
|
||||
31
companion-agent/internal/oxide/status.go
Normal file
31
companion-agent/internal/oxide/status.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package oxide
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// OxideStatus represents a progress update published to NATS during Oxide installation.
|
||||
// The frontend listens on corrosion.{license_id}.oxide.status for these messages.
|
||||
type OxideStatus struct {
|
||||
Stage string `json:"stage"`
|
||||
Progress int `json:"progress"`
|
||||
Message string `json:"message"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
}
|
||||
|
||||
// Valid installation stages:
|
||||
// fetching_release - Querying GitHub API for latest Oxide.Rust release
|
||||
// downloading - Downloading the Oxide zip file
|
||||
// installing - Extracting zip over server directory
|
||||
// restarting - Restarting the game server to load Oxide
|
||||
// complete - Oxide installation finished successfully
|
||||
// failed - Installation failed at some stage
|
||||
|
||||
// CheckOxideInstalled returns true if the oxide/ directory exists in the
|
||||
// server installation directory, indicating that Oxide/uMod has been installed.
|
||||
func CheckOxideInstalled(installDir string) bool {
|
||||
_, err := os.Stat(filepath.Join(installDir, "server", "oxide"))
|
||||
return err == nil
|
||||
}
|
||||
80
companion-agent/internal/rcon/client.go
Normal file
80
companion-agent/internal/rcon/client.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package rcon
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// RconRequest is the JSON payload sent to Rust's WebRCON.
|
||||
type RconRequest struct {
|
||||
Identifier int `json:"Identifier"`
|
||||
Message string `json:"Message"`
|
||||
Name string `json:"Name"`
|
||||
}
|
||||
|
||||
// RconResponse is the JSON payload received from Rust's WebRCON.
|
||||
type RconResponse struct {
|
||||
Identifier int `json:"Identifier"`
|
||||
Message string `json:"Message"`
|
||||
Type string `json:"Type"`
|
||||
}
|
||||
|
||||
// SendCommand opens a WebSocket to the Rust server's RCON port, sends
|
||||
// a single command, reads the response, and closes the connection.
|
||||
func SendCommand(port int, password string, command string) (string, error) {
|
||||
u := url.URL{
|
||||
Scheme: "ws",
|
||||
Host: fmt.Sprintf("127.0.0.1:%d", port),
|
||||
Path: fmt.Sprintf("/%s", password),
|
||||
}
|
||||
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
conn, _, err := dialer.Dial(u.String(), nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("rcon dial failed: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Set read deadline
|
||||
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
|
||||
req := RconRequest{
|
||||
Identifier: 1,
|
||||
Message: command,
|
||||
Name: "Corrosion",
|
||||
}
|
||||
|
||||
data, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("rcon marshal failed: %w", err)
|
||||
}
|
||||
|
||||
if err := conn.WriteMessage(websocket.TextMessage, data); err != nil {
|
||||
return "", fmt.Errorf("rcon write failed: %w", err)
|
||||
}
|
||||
|
||||
// Read response — may get multiple messages (Generic, Warning, etc.)
|
||||
// We want the first response with our Identifier.
|
||||
for {
|
||||
_, message, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("rcon read failed: %w", err)
|
||||
}
|
||||
|
||||
var resp RconResponse
|
||||
if err := json.Unmarshal(message, &resp); err != nil {
|
||||
continue // skip unparseable messages
|
||||
}
|
||||
|
||||
if resp.Identifier == req.Identifier {
|
||||
return resp.Message, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="en" class="dark">
|
||||
<html lang="en" class="dark" data-theme="dark" data-game="rust">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="any" />
|
||||
@@ -9,8 +9,24 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#0a0a0a" />
|
||||
<title>Corrosion Management</title>
|
||||
<script>
|
||||
/* FOUC guard — apply persisted theme/game to <html> before the app mounts,
|
||||
so the design-system tokens paint with the right skin from frame one. */
|
||||
(function () {
|
||||
try {
|
||||
var el = document.documentElement;
|
||||
var t = localStorage.getItem('cc-theme');
|
||||
var g = localStorage.getItem('cc-game');
|
||||
if (t === 'dark' || t === 'light') {
|
||||
el.setAttribute('data-theme', t);
|
||||
el.classList.toggle('dark', t === 'dark');
|
||||
}
|
||||
if (g) el.setAttribute('data-game', g);
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body class="bg-neutral-950">
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
|
||||
8
frontend/src/assets/corrosion-mark.svg
Normal file
8
frontend/src/assets/corrosion-mark.svg
Normal file
@@ -0,0 +1,8 @@
|
||||
<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Corrosion">
|
||||
<path d="M40.2 9.45 A24 24 0 0 1 54.6 23.8" stroke="currentColor" stroke-width="6.4" stroke-linecap="round"></path>
|
||||
<path d="M54.6 40.2 A24 24 0 0 1 40.2 54.6" stroke="currentColor" stroke-width="6.4" stroke-linecap="round"></path>
|
||||
<path d="M23.8 54.6 A24 24 0 0 1 9.45 40.2" stroke="currentColor" stroke-width="6.4" stroke-linecap="round"></path>
|
||||
<path d="M9.45 23.8 A24 24 0 0 1 23.8 9.45" stroke="currentColor" stroke-width="6.4" stroke-linecap="round"></path>
|
||||
<path d="M32 16V24M32 40V48M16 32H24M40 32H48" stroke="currentColor" stroke-width="3.6" stroke-linecap="round"></path>
|
||||
<circle cx="32" cy="32" r="4.4" fill="currentColor"></circle>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 770 B |
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onErrorCaptured } from 'vue'
|
||||
import { AlertTriangle } from 'lucide-vue-next'
|
||||
import Icon from '@/components/ds/core/Icon.vue'
|
||||
import Button from '@/components/ds/core/Button.vue'
|
||||
|
||||
const hasError = ref(false)
|
||||
const errorMessage = ref('')
|
||||
@@ -20,18 +21,67 @@ function retry() {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="hasError" class="min-h-screen bg-neutral-950 flex items-center justify-center p-6">
|
||||
<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-8 max-w-md w-full text-center">
|
||||
<AlertTriangle class="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<h1 class="text-xl font-bold text-neutral-100 mb-2">Something went wrong</h1>
|
||||
<p class="text-sm text-neutral-400 mb-6">{{ errorMessage }}</p>
|
||||
<button
|
||||
@click="retry"
|
||||
class="px-4 py-2 bg-oxide-500 hover:bg-oxide-600 text-white font-medium rounded-lg transition-colors"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
<div v-if="hasError" class="eb-screen">
|
||||
<div class="eb-card">
|
||||
<div class="eb-icon-wrap">
|
||||
<Icon name="triangle-alert" :size="24" :stroke-width="1.75" />
|
||||
</div>
|
||||
<h1 class="eb-title">Something went wrong</h1>
|
||||
<p class="eb-msg">{{ errorMessage }}</p>
|
||||
<Button icon="refresh-cw" @click="retry">Retry</Button>
|
||||
</div>
|
||||
</div>
|
||||
<slot v-else />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.eb-screen {
|
||||
min-height: 100vh;
|
||||
background: var(--surface-canvas);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--space-6);
|
||||
}
|
||||
|
||||
.eb-card {
|
||||
background: var(--surface-base);
|
||||
box-shadow: var(--ring-default), var(--shadow-md);
|
||||
border-radius: var(--radius-xl);
|
||||
padding: var(--space-8);
|
||||
max-width: 380px;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.eb-icon-wrap {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: var(--radius-lg);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--status-offline-soft);
|
||||
box-shadow: inset 0 0 0 1px var(--status-offline-border);
|
||||
color: var(--status-offline);
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.eb-title {
|
||||
font-size: var(--text-xl);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.eb-msg {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--text-tertiary);
|
||||
line-height: 1.55;
|
||||
max-width: 300px;
|
||||
}
|
||||
</style>
|
||||
|
||||
29
frontend/src/components/brand/CorrosionMark.vue
Normal file
29
frontend/src/components/brand/CorrosionMark.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Corrosion brand mark — segmented "C-core" reticle.
|
||||
* A bold ring split into four arc segments around a centered control node,
|
||||
* with N/E/S/W targeting ticks. Drawn in `currentColor` so it themes to the
|
||||
* active accent (set `color: var(--accent)` on a parent) and stays crisp to ~12px.
|
||||
* Source: design-system assets/mark.svg (64×64 viewBox).
|
||||
*/
|
||||
withDefaults(defineProps<{ size?: number | string }>(), { size: 24 })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg
|
||||
:width="size"
|
||||
:height="size"
|
||||
viewBox="0 0 64 64"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
role="img"
|
||||
aria-label="Corrosion"
|
||||
>
|
||||
<path d="M40.2 9.45 A24 24 0 0 1 54.6 23.8" stroke="currentColor" stroke-width="6.4" stroke-linecap="round" />
|
||||
<path d="M54.6 40.2 A24 24 0 0 1 40.2 54.6" stroke="currentColor" stroke-width="6.4" stroke-linecap="round" />
|
||||
<path d="M23.8 54.6 A24 24 0 0 1 9.45 40.2" stroke="currentColor" stroke-width="6.4" stroke-linecap="round" />
|
||||
<path d="M9.45 23.8 A24 24 0 0 1 23.8 9.45" stroke="currentColor" stroke-width="6.4" stroke-linecap="round" />
|
||||
<path d="M32 16V24M32 40V48M16 32H24M40 32H48" stroke="currentColor" stroke-width="3.6" stroke-linecap="round" />
|
||||
<circle cx="32" cy="32" r="4.4" fill="currentColor" />
|
||||
</svg>
|
||||
</template>
|
||||
92
frontend/src/components/ds/brand/Logo.vue
Normal file
92
frontend/src/components/ds/brand/Logo.vue
Normal file
@@ -0,0 +1,92 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Logo — Corrosion brand lockup.
|
||||
* Composes the CorrosionMark SVG + Oxanium wordmark + optional tagline.
|
||||
*
|
||||
* The mark renders in `currentColor`, so set `color: var(--accent)` on a
|
||||
* parent (or pass `markColor`) to theme it per active game.
|
||||
*
|
||||
* Props mirror Logo.jsx exactly:
|
||||
* size — base px size; drives mark em-size + wordmark scaling
|
||||
* wordmark — show the "Corrosion" text (default true)
|
||||
* tagline — false | true (→ "Management Panel") | custom string
|
||||
* glow — accent drop-shadow for marketing / login hero use
|
||||
* markColor — force a fixed color on the mark (bypasses currentColor theming)
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import CorrosionMark from '@/components/brand/CorrosionMark.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
size?: number
|
||||
wordmark?: boolean
|
||||
tagline?: boolean | string
|
||||
glow?: boolean
|
||||
markColor?: string
|
||||
}>(),
|
||||
{ size: 26, wordmark: true, tagline: false, glow: false },
|
||||
)
|
||||
|
||||
const gap = computed(() => Math.round(props.size * 0.4) + 'px')
|
||||
const wordmarkGap = computed(() => Math.round(props.size * 0.14) + 'px')
|
||||
const wordmarkFontSize = computed(() => (props.size * 0.62) + 'px')
|
||||
const taglineFontSize = computed(() => Math.max(8, props.size * 0.26) + 'px')
|
||||
const glowFilter = computed(() =>
|
||||
props.glow ? `drop-shadow(0 0 ${props.size * 0.5}px var(--accent-glow))` : 'none'
|
||||
)
|
||||
const tagText = computed(() =>
|
||||
typeof props.tagline === 'string' ? props.tagline : 'Management Panel'
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="cc-logo"
|
||||
:style="{ display: 'inline-flex', alignItems: 'center', gap, lineHeight: 1 }"
|
||||
>
|
||||
<!-- Mark wrapper: sets font-size so CorrosionMark's 1em sizing works; applies glow -->
|
||||
<span
|
||||
:style="{
|
||||
fontSize: size + 'px',
|
||||
display: 'inline-flex',
|
||||
filter: glowFilter,
|
||||
color: markColor ?? undefined,
|
||||
}"
|
||||
>
|
||||
<CorrosionMark :size="size" />
|
||||
</span>
|
||||
|
||||
<!-- Wordmark + optional tagline -->
|
||||
<span
|
||||
v-if="wordmark"
|
||||
:style="{ display: 'inline-flex', flexDirection: 'column', gap: wordmarkGap }"
|
||||
>
|
||||
<span
|
||||
:style="{
|
||||
fontFamily: 'var(--font-brand)',
|
||||
fontWeight: 800,
|
||||
fontSize: wordmarkFontSize,
|
||||
letterSpacing: '0.005em',
|
||||
color: 'var(--text-primary)',
|
||||
lineHeight: 1,
|
||||
}"
|
||||
>Corrosion</span>
|
||||
<span
|
||||
v-if="tagline"
|
||||
:style="{
|
||||
fontFamily: 'var(--font-brand)',
|
||||
fontWeight: 600,
|
||||
fontSize: taglineFontSize,
|
||||
letterSpacing: '0.26em',
|
||||
textTransform: 'uppercase',
|
||||
color: 'var(--accent-text)',
|
||||
lineHeight: 1,
|
||||
}"
|
||||
>{{ tagText }}</span>
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-logo { user-select: none; }
|
||||
</style>
|
||||
62
frontend/src/components/ds/core/Badge.vue
Normal file
62
frontend/src/components/ds/core/Badge.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
/** Badge — compact status/label chip. Tone drives fg/soft-bg/border; `solid` fills. */
|
||||
import { computed } from 'vue'
|
||||
import Icon from './Icon.vue'
|
||||
import StatusDot from './StatusDot.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
tone?: 'neutral' | 'accent' | 'online' | 'offline' | 'warn' | 'info' | 'starting' | 'wiping'
|
||||
solid?: boolean
|
||||
dot?: boolean
|
||||
pulse?: boolean
|
||||
icon?: string
|
||||
size?: 'md' | 'lg'
|
||||
mono?: boolean
|
||||
uppercase?: boolean
|
||||
}>(),
|
||||
{ tone: 'neutral', solid: false, dot: false, pulse: false, size: 'md', mono: false, uppercase: false },
|
||||
)
|
||||
|
||||
const NEUTRAL: [string, string, string] = ['var(--text-secondary)', 'var(--surface-raised-2)', 'var(--border-default)']
|
||||
const TONES: Record<string, [string, string, string]> = {
|
||||
neutral: NEUTRAL,
|
||||
accent: ['var(--accent-text)', 'var(--accent-soft)', 'var(--accent-border)'],
|
||||
online: ['var(--status-online)', 'var(--status-online-soft)', 'var(--status-online-border)'],
|
||||
offline: ['var(--status-offline)', 'var(--status-offline-soft)', 'var(--status-offline-border)'],
|
||||
warn: ['var(--status-warn)', 'var(--status-warn-soft)', 'var(--status-warn-border)'],
|
||||
info: ['var(--status-info)', 'var(--status-info-soft)', 'var(--status-info-border)'],
|
||||
starting: ['var(--status-starting)', 'var(--status-starting-soft)', 'var(--status-starting-border)'],
|
||||
wiping: ['var(--status-wiping)', 'var(--status-wiping-soft)', 'var(--status-wiping-border)'],
|
||||
}
|
||||
|
||||
const styleObj = computed(() => {
|
||||
const [fg, soft, border] = TONES[props.tone] ?? NEUTRAL
|
||||
return props.solid
|
||||
? { background: fg, color: 'var(--surface-canvas)', boxShadow: 'none' }
|
||||
: { background: soft, color: fg, boxShadow: `inset 0 0 0 1px ${border}` }
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="cc-badge"
|
||||
:class="[size === 'lg' && 'cc-badge--lg', mono && 'cc-badge--mono', uppercase && 'cc-badge--uppercase']"
|
||||
:style="styleObj"
|
||||
>
|
||||
<StatusDot v-if="dot" :tone="tone" :size="6" :pulse="pulse" />
|
||||
<Icon v-if="icon" :name="icon" :size="size === 'lg' ? 13 : 12" :stroke-width="2.5" />
|
||||
<slot />
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-badge {
|
||||
display: inline-flex; align-items: center; gap: 5px; height: 20px; padding: 0 8px;
|
||||
font-family: var(--font-sans); font-weight: 600; font-size: var(--text-xs); line-height: 1;
|
||||
border-radius: var(--radius-sm); white-space: nowrap; letter-spacing: 0.005em;
|
||||
}
|
||||
.cc-badge--lg { height: 24px; padding: 0 10px; font-size: var(--text-sm); }
|
||||
.cc-badge--mono { font-family: var(--font-mono); font-weight: 500; letter-spacing: 0; font-variant-numeric: tabular-nums; }
|
||||
.cc-badge--uppercase { text-transform: uppercase; letter-spacing: var(--tracking-wider); font-size: var(--text-2xs); }
|
||||
</style>
|
||||
82
frontend/src/components/ds/core/Button.vue
Normal file
82
frontend/src/components/ds/core/Button.vue
Normal file
@@ -0,0 +1,82 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Button — primary action control; `variant="primary"` carries the live game accent.
|
||||
* Variants: primary | secondary | ghost | outline | danger | danger-soft.
|
||||
* Sizes: sm | md | lg. Pass Lucide names via `icon` / `iconRight`.
|
||||
* Native click bubbles via attribute fall-through (root is the <button>).
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import Icon from './Icon.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
variant?: 'primary' | 'secondary' | 'ghost' | 'outline' | 'danger' | 'danger-soft'
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
icon?: string
|
||||
iconRight?: string
|
||||
loading?: boolean
|
||||
block?: boolean
|
||||
disabled?: boolean
|
||||
type?: 'button' | 'submit' | 'reset'
|
||||
}>(),
|
||||
{ variant: 'primary', size: 'md', loading: false, block: false, disabled: false, type: 'button' },
|
||||
)
|
||||
|
||||
const iconSize = computed(() => (props.size === 'lg' ? 17 : props.size === 'sm' ? 14 : 15))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
:type="type"
|
||||
:disabled="disabled || loading"
|
||||
:class="[
|
||||
'cc-btn',
|
||||
`cc-btn--${variant}`,
|
||||
size !== 'md' && `cc-btn--${size}`,
|
||||
block && 'cc-btn--block',
|
||||
]"
|
||||
>
|
||||
<span v-if="loading" class="cc-btn__spin" />
|
||||
<Icon v-else-if="icon" :name="icon" :size="iconSize" :stroke-width="2.25" />
|
||||
<span v-if="$slots.default"><slot /></span>
|
||||
<Icon v-if="iconRight && !loading" :name="iconRight" :size="iconSize" :stroke-width="2.25" />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 7px;
|
||||
font-family: var(--font-sans); font-weight: 600; font-size: var(--text-sm); line-height: 1;
|
||||
white-space: nowrap; height: var(--control-h-md); padding: 0 14px;
|
||||
border-radius: var(--radius-md); border: 1px solid transparent; cursor: pointer; user-select: none;
|
||||
transition: var(--transition-colors), transform var(--dur-fast) var(--ease-standard);
|
||||
}
|
||||
.cc-btn:focus-visible { outline: none; box-shadow: var(--focus-ring); }
|
||||
.cc-btn:active { transform: translateY(0.5px); }
|
||||
.cc-btn[disabled], .cc-btn[aria-disabled="true"] { opacity: 0.45; pointer-events: none; }
|
||||
.cc-btn--block { width: 100%; }
|
||||
.cc-btn--sm { height: var(--control-h-sm); padding: 0 10px; font-size: var(--text-xs); border-radius: var(--radius-sm); gap: 6px; }
|
||||
.cc-btn--lg { height: var(--control-h-lg); padding: 0 18px; font-size: var(--text-base); gap: 9px; }
|
||||
|
||||
.cc-btn--primary { background: var(--accent); color: var(--accent-contrast); }
|
||||
.cc-btn--primary:hover { background: var(--accent-hover); }
|
||||
.cc-btn--primary:active { background: var(--accent-press); }
|
||||
|
||||
.cc-btn--secondary { background: var(--surface-raised-2); color: var(--text-primary); box-shadow: var(--ring-default); }
|
||||
.cc-btn--secondary:hover { background: var(--surface-active); }
|
||||
|
||||
.cc-btn--ghost { background: transparent; color: var(--text-secondary); }
|
||||
.cc-btn--ghost:hover { background: var(--surface-hover); color: var(--text-primary); }
|
||||
|
||||
.cc-btn--outline { background: transparent; color: var(--accent-text); box-shadow: inset 0 0 0 1px var(--accent-border); }
|
||||
.cc-btn--outline:hover { background: var(--accent-soft); }
|
||||
|
||||
.cc-btn--danger { background: var(--danger); color: #fff; }
|
||||
.cc-btn--danger:hover { filter: brightness(1.1); }
|
||||
|
||||
.cc-btn--danger-soft { background: var(--status-offline-soft); color: var(--danger); box-shadow: inset 0 0 0 1px var(--status-offline-border); }
|
||||
.cc-btn--danger-soft:hover { background: var(--danger); color: #fff; }
|
||||
|
||||
.cc-btn__spin { width: 14px; height: 14px; border-radius: 50%; border: 2px solid currentColor; border-top-color: transparent; animation: cc-btn-spin 0.6s linear infinite; }
|
||||
@keyframes cc-btn-spin { to { transform: rotate(360deg); } }
|
||||
</style>
|
||||
81
frontend/src/components/ds/core/Icon.vue
Normal file
81
frontend/src/components/ds/core/Icon.vue
Normal file
@@ -0,0 +1,81 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Icon — renders a Lucide icon by kebab-case name (matches the design system's
|
||||
* string `icon` prop API, e.g. <Icon name="refresh-cw" />). Maps to
|
||||
* `lucide-vue-next` via a registry so the bundle only ships icons we use.
|
||||
* Lucide icons render with `currentColor`, so they theme to the parent's color.
|
||||
* Add new icons to `registry` as the port grows.
|
||||
*/
|
||||
import type { Component } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
Play, Pause, RefreshCw, Trash2, Settings, Terminal, Power, Box, Sun, Moon,
|
||||
Loader, LoaderCircle, TrendingUp, TrendingDown, Minus, Plus, Server, Users,
|
||||
Puzzle, FolderOpen, Cpu, BarChart3, Rocket, TriangleAlert, Bell, Search,
|
||||
ChevronDown, ChevronRight, ChevronLeft, ChevronUp, Check, X, Calendar, Clock,
|
||||
ShoppingCart, CreditCard, HardDrive, Activity, Shield, Download, Upload,
|
||||
Wifi, WifiOff, Map, Gauge, Gift, Flame, DoorOpen, Pickaxe, Swords, Crosshair,
|
||||
Navigation, MessageSquare, FileText, Bookmark, ExternalLink, Copy, LogOut,
|
||||
Eye, EyeOff, Globe, Key, Layers, List, MoreVertical, Zap,
|
||||
Info, OctagonAlert, CircleCheck, Sparkles, Inbox,
|
||||
LayoutDashboard, CalendarClock, Drama, ChevronsUpDown, ServerCog,
|
||||
LayoutGrid, SquareDashed, MemoryStick, CornerDownLeft,
|
||||
Ban, Flag,
|
||||
CircleAlert, ArrowDown, Award, DollarSign, FlaskConical, Mail, Package,
|
||||
Pencil, Save, ShoppingBag, Target, User,
|
||||
} from 'lucide-vue-next'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{ name: string; size?: number; strokeWidth?: number }>(),
|
||||
{ size: 16, strokeWidth: 2 },
|
||||
)
|
||||
|
||||
const registry: Record<string, Component> = {
|
||||
play: Play, pause: Pause, 'refresh-cw': RefreshCw, 'trash-2': Trash2,
|
||||
settings: Settings, terminal: Terminal, power: Power, box: Box, sun: Sun,
|
||||
moon: Moon, loader: LoaderCircle, 'loader-2': Loader, 'trending-up': TrendingUp,
|
||||
'trending-down': TrendingDown, minus: Minus, plus: Plus, server: Server,
|
||||
users: Users, puzzle: Puzzle, 'folder-open': FolderOpen, cpu: Cpu,
|
||||
'bar-chart-3': BarChart3, rocket: Rocket, 'triangle-alert': TriangleAlert,
|
||||
bell: Bell, search: Search, 'chevron-down': ChevronDown,
|
||||
'chevron-right': ChevronRight, 'chevron-left': ChevronLeft, 'chevron-up': ChevronUp,
|
||||
check: Check, x: X, calendar: Calendar, clock: Clock,
|
||||
'shopping-cart': ShoppingCart, 'credit-card': CreditCard, 'hard-drive': HardDrive,
|
||||
activity: Activity, shield: Shield, download: Download, upload: Upload,
|
||||
wifi: Wifi, 'wifi-off': WifiOff, map: Map, gauge: Gauge, gift: Gift,
|
||||
flame: Flame, 'door-open': DoorOpen, pickaxe: Pickaxe, swords: Swords,
|
||||
crosshair: Crosshair, navigation: Navigation, 'message-square': MessageSquare,
|
||||
'file-text': FileText, bookmark: Bookmark, 'external-link': ExternalLink,
|
||||
copy: Copy, 'log-out': LogOut, eye: Eye, 'eye-off': EyeOff, globe: Globe,
|
||||
key: Key, layers: Layers, list: List, 'more-vertical': MoreVertical, zap: Zap,
|
||||
info: Info, 'octagon-alert': OctagonAlert, 'circle-check': CircleCheck,
|
||||
sparkles: Sparkles, inbox: Inbox,
|
||||
'layout-dashboard': LayoutDashboard, 'calendar-clock': CalendarClock, drama: Drama,
|
||||
'chevrons-up-down': ChevronsUpDown, 'server-cog': ServerCog, 'layout-grid': LayoutGrid,
|
||||
'square-dashed': SquareDashed, 'memory-stick': MemoryStick, 'corner-down-left': CornerDownLeft,
|
||||
ban: Ban, flag: Flag,
|
||||
'alert-circle': CircleAlert, 'arrow-down': ArrowDown, award: Award,
|
||||
'dollar-sign': DollarSign, 'flask-conical': FlaskConical, mail: Mail,
|
||||
package: Package, pencil: Pencil, save: Save, 'shopping-bag': ShoppingBag,
|
||||
target: Target, user: User,
|
||||
}
|
||||
|
||||
const cmp = computed<Component | null>(() => registry[props.name] ?? null)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<component
|
||||
:is="cmp"
|
||||
v-if="cmp"
|
||||
class="cc-icon"
|
||||
:size="size"
|
||||
:width="size"
|
||||
:height="size"
|
||||
:stroke-width="strokeWidth"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-icon { display: inline-block; flex: none; vertical-align: middle; }
|
||||
</style>
|
||||
62
frontend/src/components/ds/core/IconButton.vue
Normal file
62
frontend/src/components/ds/core/IconButton.vue
Normal file
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* IconButton — square icon-only action button.
|
||||
* Variants: ghost | solid | accent | danger.
|
||||
* Sizes: sm | md | lg.
|
||||
* Native click bubbles via attribute fall-through (root is <button>).
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
import Icon from './Icon.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
icon: string
|
||||
variant?: 'ghost' | 'solid' | 'accent' | 'danger'
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
active?: boolean
|
||||
label?: string
|
||||
disabled?: boolean
|
||||
}>(),
|
||||
{ variant: 'ghost', size: 'md', active: false, disabled: false },
|
||||
)
|
||||
|
||||
const iconPx = computed(() => (props.size === 'lg' ? 19 : props.size === 'sm' ? 15 : 17))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
:aria-label="label"
|
||||
:title="label"
|
||||
:disabled="disabled"
|
||||
:class="[
|
||||
'cc-iconbtn',
|
||||
variant !== 'ghost' && `cc-iconbtn--${variant}`,
|
||||
size !== 'md' && `cc-iconbtn--${size}`,
|
||||
active && 'cc-iconbtn--active',
|
||||
]"
|
||||
>
|
||||
<Icon :name="icon" :size="iconPx" :stroke-width="2" />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-iconbtn {
|
||||
display:inline-flex; align-items:center; justify-content:center; flex:none;
|
||||
width:var(--control-h-md); height:var(--control-h-md); border-radius:var(--radius-md);
|
||||
border:1px solid transparent; background:transparent; color:var(--text-secondary);
|
||||
cursor:pointer; transition:var(--transition-colors), transform var(--dur-fast) var(--ease-standard);
|
||||
}
|
||||
.cc-iconbtn:hover { background:var(--surface-hover); color:var(--text-primary); }
|
||||
.cc-iconbtn:active { transform: translateY(0.5px); }
|
||||
.cc-iconbtn:focus-visible { outline:none; box-shadow:var(--focus-ring); }
|
||||
.cc-iconbtn[disabled] { opacity:.4; pointer-events:none; }
|
||||
.cc-iconbtn--sm { width:var(--control-h-sm); height:var(--control-h-sm); border-radius:var(--radius-sm); }
|
||||
.cc-iconbtn--lg { width:var(--control-h-lg); height:var(--control-h-lg); }
|
||||
.cc-iconbtn--solid { background:var(--surface-raised-2); box-shadow:var(--ring-default); }
|
||||
.cc-iconbtn--solid:hover { background:var(--surface-active); }
|
||||
.cc-iconbtn--accent { background:var(--accent); color:var(--accent-contrast); }
|
||||
.cc-iconbtn--accent:hover { background:var(--accent-hover); }
|
||||
.cc-iconbtn--danger:hover { background:var(--status-offline-soft); color:var(--danger); }
|
||||
.cc-iconbtn--active { background:var(--accent-soft); color:var(--accent-text); box-shadow: inset 0 0 0 1px var(--accent-border); }
|
||||
</style>
|
||||
20
frontend/src/components/ds/core/Kbd.vue
Normal file
20
frontend/src/components/ds/core/Kbd.vue
Normal file
@@ -0,0 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Kbd — keyboard shortcut key chip, rendered as <kbd>.
|
||||
* Uses mono font and inset border + bottom shadow to mimic a physical key.
|
||||
* No props — purely a presentational slot wrapper; native attrs fall through.
|
||||
*/
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<kbd class="cc-kbd"><slot /></kbd>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-kbd {
|
||||
display:inline-flex; align-items:center; justify-content:center; min-width:20px; height:20px; padding:0 5px;
|
||||
font-family:var(--font-mono); font-size:11px; font-weight:500; line-height:1; color:var(--text-secondary);
|
||||
background:var(--surface-raised-2); border-radius:var(--radius-sm);
|
||||
box-shadow: inset 0 0 0 1px var(--border-default), 0 1px 0 var(--border-default);
|
||||
}
|
||||
</style>
|
||||
48
frontend/src/components/ds/core/StatusDot.vue
Normal file
48
frontend/src/components/ds/core/StatusDot.vue
Normal file
@@ -0,0 +1,48 @@
|
||||
<script setup lang="ts">
|
||||
/** StatusDot — small live-status dot; pulses when live. Tone maps to status tokens. */
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
tone?: 'online' | 'offline' | 'warn' | 'info' | 'starting' | 'wiping' | 'neutral' | 'accent'
|
||||
size?: number
|
||||
pulse?: boolean
|
||||
}>(),
|
||||
{ tone: 'online', size: 8, pulse: false },
|
||||
)
|
||||
|
||||
const TONE: Record<string, string> = {
|
||||
online: 'var(--status-online)',
|
||||
offline: 'var(--status-offline)',
|
||||
warn: 'var(--status-warn)',
|
||||
info: 'var(--status-info)',
|
||||
starting: 'var(--status-starting)',
|
||||
wiping: 'var(--status-wiping)',
|
||||
neutral: 'var(--text-muted)',
|
||||
accent: 'var(--accent)',
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="cc-dot"
|
||||
:class="pulse && 'cc-dot--pulse'"
|
||||
:style="{
|
||||
width: size + 'px',
|
||||
height: size + 'px',
|
||||
background: TONE[tone] || TONE.neutral,
|
||||
boxShadow: pulse ? '0 0 8px -1px ' + (TONE[tone] || TONE.neutral) : 'none',
|
||||
}"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-dot { display: inline-block; flex: none; border-radius: 50%; position: relative; }
|
||||
.cc-dot--pulse::after {
|
||||
content: ''; position: absolute; inset: 0; border-radius: 50%; background: inherit;
|
||||
animation: cc-dot-pulse 1.8s var(--ease-out) infinite;
|
||||
}
|
||||
@keyframes cc-dot-pulse {
|
||||
0% { transform: scale(1); opacity: 0.6; }
|
||||
70%, 100% { transform: scale(2.6); opacity: 0; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .cc-dot--pulse::after { animation: none; } }
|
||||
</style>
|
||||
52
frontend/src/components/ds/core/Tag.vue
Normal file
52
frontend/src/components/ds/core/Tag.vue
Normal file
@@ -0,0 +1,52 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Tag — removable or static label chip.
|
||||
* Set `removable` to show the dismiss ×; emit `remove` is fired when clicked.
|
||||
* Optional `icon` prefix via Icon registry.
|
||||
*/
|
||||
import Icon from './Icon.vue'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
icon?: string
|
||||
removable?: boolean
|
||||
}>(),
|
||||
{ removable: false },
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
remove: []
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span :class="['cc-tag', !removable && 'cc-tag--static']">
|
||||
<Icon v-if="icon" :name="icon" :size="12" :stroke-width="2.25" />
|
||||
<span><slot /></span>
|
||||
<button
|
||||
v-if="removable"
|
||||
type="button"
|
||||
class="cc-tag__x"
|
||||
aria-label="Remove"
|
||||
@click="emit('remove')"
|
||||
>
|
||||
<Icon name="x" :size="11" :stroke-width="2.5" />
|
||||
</button>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-tag {
|
||||
display:inline-flex; align-items:center; gap:6px; height:24px; padding:0 4px 0 9px;
|
||||
font-family:var(--font-sans); font-size:var(--text-xs); font-weight:500; line-height:1;
|
||||
color:var(--text-secondary); background:var(--surface-raised-2);
|
||||
border-radius:var(--radius-sm); box-shadow:var(--ring-default);
|
||||
}
|
||||
.cc-tag--static { padding:0 9px; }
|
||||
.cc-tag__x {
|
||||
display:inline-flex; align-items:center; justify-content:center; width:16px; height:16px;
|
||||
border-radius:var(--radius-xs); color:var(--text-tertiary); cursor:pointer; border:0; background:transparent;
|
||||
transition:var(--transition-colors);
|
||||
}
|
||||
.cc-tag__x:hover { background:var(--surface-active); color:var(--text-primary); }
|
||||
</style>
|
||||
72
frontend/src/components/ds/data/Avatar.vue
Normal file
72
frontend/src/components/ds/data/Avatar.vue
Normal file
@@ -0,0 +1,72 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Avatar — player / operator avatar. Renders an image, or falls back to initials.
|
||||
* Optional status dot (online / offline / warn / idle) sits bottom-right.
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
name?: string
|
||||
src?: string
|
||||
size?: number
|
||||
shape?: 'rounded' | 'circle'
|
||||
status?: 'online' | 'offline' | 'warn' | 'idle'
|
||||
}>(),
|
||||
{ name: '', size: 32, shape: 'rounded' },
|
||||
)
|
||||
|
||||
const TONE: Record<string, string> = {
|
||||
online: 'var(--status-online)',
|
||||
offline: 'var(--status-offline)',
|
||||
warn: 'var(--status-warn)',
|
||||
idle: 'var(--text-muted)',
|
||||
}
|
||||
|
||||
const initials = computed(() =>
|
||||
props.name
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.map(w => w[0] ?? '')
|
||||
.join('')
|
||||
.toUpperCase() || '?',
|
||||
)
|
||||
|
||||
const dotSize = computed(() => Math.max(7, Math.round(props.size * 0.28)))
|
||||
const dotColor = computed(() => (props.status ? (TONE[props.status] ?? TONE.idle) : ''))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="cc-avatar"
|
||||
:class="shape === 'circle' && 'cc-avatar--circle'"
|
||||
:style="{
|
||||
width: size + 'px',
|
||||
height: size + 'px',
|
||||
fontSize: Math.round(size * 0.4) + 'px',
|
||||
}"
|
||||
>
|
||||
<img v-if="src" :src="src" :alt="name" />
|
||||
<template v-else>{{ initials }}</template>
|
||||
<span
|
||||
v-if="status"
|
||||
class="cc-avatar__status"
|
||||
:style="{ width: dotSize + 'px', height: dotSize + 'px', background: dotColor }"
|
||||
/>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.cc-avatar {
|
||||
position: relative; display: inline-flex; align-items: center; justify-content: center; flex: none;
|
||||
border-radius: var(--radius-md); background: var(--surface-active); color: var(--text-secondary);
|
||||
font-family: var(--font-mono); font-weight: 600; overflow: visible; box-shadow: var(--ring-default);
|
||||
}
|
||||
.cc-avatar--circle { border-radius: 50%; }
|
||||
.cc-avatar img { width: 100%; height: 100%; object-fit: cover; border-radius: inherit; }
|
||||
.cc-avatar__status {
|
||||
position: absolute; right: -2px; bottom: -2px; border-radius: 50%;
|
||||
box-shadow: 0 0 0 2px var(--surface-base);
|
||||
}
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user