SystemService.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { AppDataSource, SystemConfig, User, PlatformAccount, PublishTask } from '../models/index.js';
  2. import type { SystemConfig as SystemConfigType } from '@media-manager/shared';
  3. import { PLATFORM_TYPES } from '@media-manager/shared';
  4. import { wsManager } from '../websocket/index.js';
  5. interface UpdateConfigParams {
  6. allowRegistration?: boolean;
  7. defaultUserRole?: string;
  8. }
  9. interface SystemStatus {
  10. database: 'connected' | 'disconnected';
  11. redis: 'connected' | 'disconnected';
  12. onlineUsers: number;
  13. totalUsers: number;
  14. totalAccounts: number;
  15. totalTasks: number;
  16. uptime: number;
  17. }
  18. export class SystemService {
  19. private configRepository = AppDataSource.getRepository(SystemConfig);
  20. private userRepository = AppDataSource.getRepository(User);
  21. private accountRepository = AppDataSource.getRepository(PlatformAccount);
  22. private taskRepository = AppDataSource.getRepository(PublishTask);
  23. async getPublicConfig(): Promise<SystemConfigType> {
  24. const configs = await this.configRepository.find();
  25. const configMap = new Map(configs.map(c => [c.configKey, c.configValue]));
  26. return {
  27. allowRegistration: configMap.get('allow_registration') === 'true',
  28. defaultUserRole: configMap.get('default_user_role') || 'operator',
  29. maxUploadSize: 4096 * 1024 * 1024, // 4GB
  30. supportedPlatforms: PLATFORM_TYPES,
  31. };
  32. }
  33. async updateConfig(params: UpdateConfigParams): Promise<void> {
  34. if (params.allowRegistration !== undefined) {
  35. await this.setConfig('allow_registration', String(params.allowRegistration));
  36. }
  37. if (params.defaultUserRole) {
  38. await this.setConfig('default_user_role', params.defaultUserRole);
  39. }
  40. }
  41. async getSystemStatus(): Promise<SystemStatus> {
  42. const [totalUsers, totalAccounts, totalTasks] = await Promise.all([
  43. this.userRepository.count(),
  44. this.accountRepository.count(),
  45. this.taskRepository.count(),
  46. ]);
  47. return {
  48. database: AppDataSource.isInitialized ? 'connected' : 'disconnected',
  49. redis: 'connected', // TODO: 实际检查 Redis 连接状态
  50. onlineUsers: wsManager.getOnlineUserCount(),
  51. totalUsers,
  52. totalAccounts,
  53. totalTasks,
  54. uptime: process.uptime(),
  55. };
  56. }
  57. private async setConfig(key: string, value: string): Promise<void> {
  58. const existing = await this.configRepository.findOne({ where: { configKey: key } });
  59. if (existing) {
  60. await this.configRepository.update(existing.id, { configValue: value });
  61. } else {
  62. await this.configRepository.save({ configKey: key, configValue: value });
  63. }
  64. }
  65. }