File size: 5,465 Bytes
f55c62a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import app from './app.js';

import {
  Env,
  config as appConfig,
  createLogger,
  initDb,
  initialiseConfig,
  closeDb,
  UserRepository,
  logStartupInfo,
  Cache,
  RegexAccess,
  SelAccess,
  AnimeDatabase,
  ConfigStartupError,
  ProwlarrAddon,
  TemplateManager,
  maskSensitiveInfo,
  constants,
  SeaDexDataset,
  ensureConfigAccessKey,
  startAnalytics,
  stopAnalytics,
  TaskManager,
} from '@aiostreams/core';
import { randomBytes } from 'crypto';

const logger = createLogger('server');

async function initialiseDatabase() {
  try {
    await initDb(appConfig.bootstrap.databaseUri);
    await initialiseConfig();
  } catch (error) {
    if (error instanceof ConfigStartupError) throw error;
    logger.error('Failed to initialise database:', error);
    throw error;
  }
}

function registerPruneTask() {
  const maxDays = appConfig.tasks.pruning.maxDays;
  TaskManager.register({
    id: 'prune-users',
    label: 'Prune inactive users',
    description:
      'Deletes user configs that have not been accessed within the configured window.',
    category: 'users',
    kind: 'scheduled',
    intervalMs: appConfig.tasks.pruning.interval * 1000,
    enabled: maxDays >= 0,
    destructive: true,
    multiReplica: 'single',
    run: async () => {
      if (appConfig.tasks.pruning.maxDays < 0)
        return { ok: true, message: 'pruning disabled' };
      const n = await UserRepository.pruneUsers(
        appConfig.tasks.pruning.maxDays
      );
      return { ok: true, message: `pruned ${n} users` };
    },
  });
}

function registerCacheTasks() {
  TaskManager.register({
    id: 'clear-all-cache',
    label: 'Clear all cache',
    description: 'Wipes every registered cache backend. Destructive.',
    category: 'cache',
    kind: 'manual',
    enabled: true,
    destructive: true,
    multiReplica: 'all',
    run: async () => {
      await Cache.clearAll();
      return { ok: true, message: 'cache cleared' };
    },
  });
  TaskManager.register({
    id: 'clear-expired-cache',
    label: 'Clear expired cache keys',
    description: 'Deletes expired SQL cache rows (memory/redis self-expire).',
    category: 'cache',
    kind: 'manual',
    enabled: true,
    destructive: false,
    multiReplica: 'single',
    run: async () => {
      const n = await Cache.clearExpired();
      return { ok: true, message: `removed ${n} expired rows` };
    },
  });
}

async function initialiseRedis() {
  if (appConfig.bootstrap.redisUri) {
    await Cache.testRedisConnection();
  }
}

async function initialiseAnimeDatabase() {
  try {
    await AnimeDatabase.getInstance().initialise();
  } catch (error) {
    logger.error('Failed to initialise AnimeDatabase:', error);
  }
}

async function initialiseSeaDexDataset() {
  try {
    await SeaDexDataset.getInstance().initialise();
  } catch {}
}

async function initialiseProwlarr() {
  try {
    await ProwlarrAddon.fetchpreconfiguredIndexers();
  } catch (error) {
    logger.error('Failed to initialise Prowlarr:', error);
  }
}

async function initialiseTemplates() {
  try {
    await TemplateManager.loadTemplates();
  } catch (error) {
    logger.error('Failed to initialise templates:', error);
  }
}

async function initialiseAuth() {
  await ensureConfigAccessKey();
  if (appConfig.nzbProxy.publicEnabled) {
    appConfig.bootstrap.auth.set(
      constants.PUBLIC_NZB_PROXY_USERNAME,
      appConfig.bootstrap.auth.get(constants.PUBLIC_NZB_PROXY_USERNAME) ||
        randomBytes(32).toString('hex')
    );
    logger.info('AIOStreams Public NZB Proxy is enabled.', {
      username: constants.PUBLIC_NZB_PROXY_USERNAME,
      password: maskSensitiveInfo(
        appConfig.bootstrap.auth.get(constants.PUBLIC_NZB_PROXY_USERNAME) || ''
      ),
    });
  }
}

async function start() {
  try {
    await initialiseDatabase();
    await initialiseTemplates();
    logStartupInfo();
    await initialiseRedis();
    initialiseAnimeDatabase();
    initialiseSeaDexDataset();
    RegexAccess.initialise();
    SelAccess.initialise();
    await initialiseProwlarr();
    registerPruneTask();
    registerCacheTasks();
    await initialiseAuth();
    startAnalytics();
    const server = app.listen(appConfig.bootstrap.port, (error) => {
      if (error) {
        logger.error('Failed to start server:', error);
        process.exit(1);
      }
      logger.info(
        `Server running on port ${appConfig.bootstrap.port}: ${JSON.stringify(server.address())}`
      );
    });
  } catch (error) {
    if (error instanceof ConfigStartupError) throw error;
    logger.error('Failed to start server:', error);
    process.exit(1);
  }
}

async function shutdown() {
  TaskManager.stopAll();
  await stopAnalytics().catch(() => undefined);
  await Cache.close();
  RegexAccess.cleanup();
  SelAccess.cleanup();
  await closeDb();
}

process.on('SIGTERM', async () => {
  logger.info('SIGTERM received. Shutting down gracefully...');
  await shutdown();
  process.exit(0);
});

process.on('SIGINT', async () => {
  logger.info('SIGINT received. Shutting down gracefully...');
  await shutdown();
  process.exit(0);
});

start().catch((error) => {
  if (error instanceof ConfigStartupError) {
    // The message is already a pre-formatted human-friendly banner — print
    // it verbatim and exit 1 without dumping a node stack trace.
    process.stderr.write(`${error.message}\n`);
    process.exit(1);
  }
  logger.error('Failed to start server:', error);
  process.exit(1);
});