-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathmain.ts
More file actions
338 lines (289 loc) · 8.74 KB
/
main.ts
File metadata and controls
338 lines (289 loc) · 8.74 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// @ts-strict-ignore
import './polyfills';
import * as asyncStorage from '#platform/server/asyncStorage';
import * as connection from '#platform/server/connection';
import * as fs from '#platform/server/fs';
import { logger, setVerboseMode } from '#platform/server/log';
import * as sqlite from '#platform/server/sqlite';
import { q } from '#shared/query';
import { amountToInteger, integerToAmount } from '#shared/util';
import type { Handlers } from '#types/handlers';
import { app as accountsApp } from './accounts/app';
import { app as adminApp } from './admin/app';
import { installAPI } from './api';
import { aqlQuery } from './aql';
import { app as authApp } from './auth/app';
import { app as budgetApp } from './budget/app';
import { app as budgetFilesApp } from './budgetfiles/app';
import { app as dashboardApp } from './dashboard/app';
import * as db from './db';
import * as encryption from './encryption';
import { app as encryptionApp } from './encryption/app';
import { app as filtersApp } from './filters/app';
import { app } from './main-app';
import { mutator, runHandler } from './mutators';
import { app as notesApp } from './notes/app';
import { app as payeesApp } from './payees/app';
import { get } from './post';
import { app as preferencesApp } from './preferences/app';
import * as prefs from './prefs';
import { app as reportsApp } from './reports/app';
import { app as rulesApp } from './rules/app';
import { app as schedulesApp } from './schedules/app';
import { getServer, setServer } from './server-config';
import { app as spreadsheetApp } from './spreadsheet/app';
import { fullSync, setSyncingMode } from './sync';
import { app as syncApp } from './sync/app';
import { app as tagsApp } from './tags/app';
import { app as toolsApp } from './tools/app';
import { app as transactionsApp } from './transactions/app';
import * as rules from './transactions/transaction-rules';
import { redo, undo } from './undo';
// handlers
// need to work around the type system here because the object
// is /currently/ empty but we promise to fill it in later
export let handlers = {} as unknown as Handlers;
handlers['undo'] = mutator(async function () {
return undo();
});
handlers['redo'] = mutator(function () {
return redo();
});
handlers['make-filters-from-conditions'] = async function ({
conditions,
applySpecialCases,
}) {
return rules.conditionsToAQL(conditions, { applySpecialCases });
};
handlers['query'] = async function (query) {
if (query['table'] == null) {
throw new Error('query has no table, did you forgot to call `.serialize`?');
}
return aqlQuery(query);
};
handlers['get-server-version'] = async function () {
if (!getServer()) {
return { error: 'no-server' };
}
let version;
try {
const res = await get(getServer().BASE_SERVER + '/info');
const info = JSON.parse(res);
version = info.build.version;
} catch {
return { error: 'network-failure' };
}
return { version };
};
handlers['get-server-url'] = async function () {
return getServer() && getServer().BASE_SERVER;
};
handlers['set-server-url'] = async function ({ url, validate = true }) {
if (url == null) {
await asyncStorage.removeItem('user-token');
} else {
url = url.replace(/\/+$/, '');
if (validate) {
// Validate the server is running
const result = await runHandler(handlers['subscribe-needs-bootstrap'], {
url,
});
if ('error' in result) {
return { error: result.error };
}
}
}
await asyncStorage.setItem('server-url', url);
await asyncStorage.setItem('did-bootstrap', true);
setServer(url);
return {};
};
handlers['app-focused'] = async function () {
if (prefs.getPrefs() && prefs.getPrefs().id) {
// First we sync
void fullSync();
}
};
handlers = installAPI(handlers) as Handlers;
// A hack for now until we clean up everything
app.handlers = handlers;
app.combine(
authApp,
schedulesApp,
budgetApp,
dashboardApp,
notesApp,
preferencesApp,
toolsApp,
filtersApp,
reportsApp,
rulesApp,
adminApp,
transactionsApp,
accountsApp,
payeesApp,
spreadsheetApp,
syncApp,
budgetFilesApp,
encryptionApp,
tagsApp,
);
export function getDefaultDocumentDir() {
return fs.join(process.env.ACTUAL_DOCUMENT_DIR, 'Actual');
}
async function setupDocumentsDir() {
async function ensureExists(dir) {
// Make sure the document folder exists
if (!(await fs.exists(dir))) {
await fs.mkdir(dir);
}
}
let documentDir = await asyncStorage.getItem('document-dir');
// Test the existing documents directory to make sure it's a valid
// path that exists, and if it errors fallback to the default one
if (documentDir) {
try {
await ensureExists(documentDir);
} catch {
documentDir = null;
}
}
if (!documentDir) {
documentDir = getDefaultDocumentDir();
}
await ensureExists(documentDir);
fs._setDocumentDir(documentDir);
}
export async function initApp(isDev, socketName) {
await sqlite.init();
asyncStorage.init();
await fs.init();
await setupDocumentsDir();
const keysStr = await asyncStorage.getItem('encrypt-keys');
if (keysStr) {
try {
const keys = JSON.parse(keysStr);
// Load all the keys
await Promise.all(
Object.keys(keys).map(fileId => {
return encryption.loadKey(keys[fileId]);
}),
);
} catch (e) {
logger.log('Error loading key', e);
throw new Error('load-key-error');
}
}
const url = await asyncStorage.getItem('server-url');
if (!url) {
await asyncStorage.removeItem('user-token');
}
setServer(url);
connection.init(socketName, app.handlers);
// Allow running DB queries locally
global.$query = aqlQuery;
global.$q = q;
if (isDev) {
global.$send = (name, args) => runHandler(app.handlers[name], args);
global.$db = db;
global.$setSyncingMode = setSyncingMode;
}
}
type BaseInitConfig = {
dataDir?: string;
verbose?: boolean;
};
type ServerInitConfig = BaseInitConfig & {
serverURL: string;
};
type PasswordAuthConfig = ServerInitConfig & {
password: string;
sessionToken?: never;
};
type SessionTokenAuthConfig = ServerInitConfig & {
sessionToken: string;
password?: never;
};
type NoServerConfig = BaseInitConfig & {
serverURL?: undefined;
password?: never;
sessionToken?: never;
};
export type InitConfig =
| PasswordAuthConfig
| SessionTokenAuthConfig
| NoServerConfig;
export async function init(config: InitConfig) {
// Get from build
let dataDir, serverURL;
if (config) {
dataDir = config.dataDir;
serverURL = config.serverURL;
// Set verbose mode if specified
if (config.verbose !== undefined) {
setVerboseMode(config.verbose);
}
} else {
dataDir = process.env.ACTUAL_DATA_DIR;
serverURL = process.env.ACTUAL_SERVER_URL;
}
await sqlite.init();
asyncStorage.init({ persist: false });
await fs.init();
fs._setDocumentDir(dataDir || process.cwd());
if (serverURL) {
setServer(serverURL);
if ('sessionToken' in config && config.sessionToken) {
// Session token authentication
await runHandler(handlers['subscribe-set-token'], {
token: config.sessionToken,
});
// Validate the token
const user = await runHandler(handlers['subscribe-get-user'], undefined);
if (!user || user.tokenExpired === true) {
// Clear invalid token
await runHandler(handlers['subscribe-set-token'], { token: '' });
throw new Error(
'Authentication failed: invalid or expired session token',
);
}
if (user.offline === true) {
// Clear token since we can't validate
await runHandler(handlers['subscribe-set-token'], { token: '' });
throw new Error('Authentication failed: server offline or unreachable');
}
} else if ('password' in config && config.password) {
const result = await runHandler(handlers['subscribe-sign-in'], {
password: config.password,
});
if (result?.error) {
throw new Error(`Authentication failed: ${result.error}`);
}
}
} else {
// This turns off all server URLs. In this mode we don't want any
// access to the server, we are doing things locally
setServer(null);
app.events.on('load-budget', () => {
setSyncingMode('offline');
});
}
return lib;
}
// Export a few things required for the platform
export const lib = {
getDataDir: fs.getDataDir,
sendMessage: (msg, args) => connection.send(msg, args),
send: async <K extends keyof Handlers, T extends Handlers[K]>(
name: K,
args?: Parameters<T>[0],
): Promise<Awaited<ReturnType<T>>> => {
const res = await runHandler(app.handlers[name], args);
return res;
},
on: (name, func) => app.events.on(name, func),
q,
db,
amountToInteger,
integerToAmount,
};