-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
525 lines (468 loc) · 14.7 KB
/
app.ts
File metadata and controls
525 lines (468 loc) · 14.7 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// app.ts
import { noise } from '@chainsafe/libp2p-noise';
import { yamux } from '@chainsafe/libp2p-yamux';
import { circuitRelayTransport } from '@libp2p/circuit-relay-v2';
import { identify, identifyPush } from '@libp2p/identify';
import { ping } from '@libp2p/ping';
import { webRTC } from '@libp2p/webrtc';
import { webSockets } from '@libp2p/websockets';
import { createLibp2p, type Libp2p, type Libp2pOptions } from 'libp2p';
import { multiaddr } from '@multiformats/multiaddr';
import { keychain } from '@libp2p/keychain';
import { dcutr } from '@libp2p/dcutr';
import { kadDHT } from '@libp2p/kad-dht';
import { bootstrap } from '@libp2p/bootstrap';
import { WebRTC } from '@multiformats/multiaddr-matcher';
import * as filters from '@libp2p/websockets/filters';
import type { ConnectionGater } from '@libp2p/interface';
import type { Multiaddr } from '@multiformats/multiaddr';
import { AppState } from '@/core/AppState';
import { ConnectionManager } from '@/core/ConnectionManager';
import { FileTransferManager } from '@/core/FileTransferManager';
import { StunService } from '@/services/StunService';
import { PhraseService } from '@/services/PhraseService';
import { UIManager } from '@/ui/UIManager';
import { ProgressTracker } from '@/ui/ProgressTracker';
import { ErrorHandler } from '@/utils/ErrorHandler';
import { ConfigManager } from '@/utils/ConfigManager';
const TURN_SERVER: string = import.meta.env.VITE_TURN_SERVER;
const TURN_USERNAME: string = import.meta.env.VITE_TURN_USERNAME;
const TURN_CREDENTIAL: string = import.meta.env.VITE_TURN_CREDENTIAL;
/**
* Interface for the services container.
* @internal
*/
interface Services {
stun: StunService;
phrase: PhraseService;
}
/**
* Interface for the managers container.
* @internal
*/
interface Managers {
ui: UIManager;
error: ErrorHandler;
progress: ProgressTracker;
fileTransfer: FileTransferManager;
connection: ConnectionManager;
}
// Extend the Window interface for global app access
declare global {
interface Window {
fileFerryApp: FileFerryApp;
}
}
/**
* The main application class that manages all modules.
*/
class FileFerryApp {
private config: ConfigManager;
private appState: AppState;
private node: Libp2p | null;
private services: Partial<Services>;
private managers: Partial<Managers>;
/**
* Initializes the FileFerryApp.
*/
public constructor() {
this.config = new ConfigManager();
this.appState = new AppState();
this.node = null;
this.services = {};
this.managers = {};
}
/**
* Initializes all services, managers, and the libp2p node.
* @returns A promise that resolves when initialization is complete.
*/
public async initialize(): Promise<void> {
try {
this.config.validateConfig();
await this.setupServices();
await this.setupLibp2pNode();
await this.setupManagers();
await this.setupUI();
console.log('FileFerry app initialized successfully');
} catch (error) {
console.error('Failed to initialize app:', error);
throw error;
}
}
/**
* Sets up application services.
* @returns A promise that resolves when services are set up.
* @internal
*/
private async setupServices(): Promise<void> {
this.services.stun = new StunService();
this.services.phrase = new PhraseService(this.config.getApiUrl());
}
/**
* Creates and configures the libp2p node.
* @returns A promise that resolves when the node is started.
* @internal
*/
private async setupLibp2pNode(): Promise<void> {
const stunServer = await this.getStunConfiguration();
const relayAddress = this.config.getRelayAddress();
console.log(stunServer);
const iceConfig = {
rtcConfiguration: {
iceServers: [
{
urls: stunServer,
},
{
urls: TURN_SERVER,
username: TURN_USERNAME,
credential: TURN_CREDENTIAL,
},
],
},
};
const options: Libp2pOptions = {
addresses: {
listen: ['/webrtc', '/p2p-circuit'],
},
transports: [
circuitRelayTransport(),
webRTC(iceConfig),
webSockets({
filter: filters.all,
}),
],
connectionEncrypters: [noise()],
streamMuxers: [yamux()],
services: {
dht: kadDHT(),
peerDiscovery: bootstrap({
list: [relayAddress],
timeout: 2000,
}),
dcutr: dcutr(),
identify: identify(),
identifyPush: identifyPush(),
keychain: keychain(),
ping: ping(),
},
};
this.node = await createLibp2p(options);
await this.node.start();
console.log(`Node started with Peer ID: ${this.node.peerId.toString()}`);
}
/**
* Sets up all application managers.
* @returns A promise that resolves when managers are set up.
* @internal
*/
private async setupManagers(): Promise<void> {
if (!this.node) {
throw new Error('Libp2p node is not initialized.');
}
// Create UI manager first
this.managers.ui = new UIManager(this.appState);
// Create error handler with UI manager
this.managers.error = new ErrorHandler(this.managers.ui);
// Create progress tracker
this.managers.progress = new ProgressTracker(this.managers.ui);
// Create core managers
this.managers.fileTransfer = new FileTransferManager(
this.node,
this.appState,
this.managers.progress,
this.managers.ui,
);
this.managers.connection = new ConnectionManager(
this.node,
this.appState,
this.managers.error,
this.config,
this.managers.fileTransfer,
);
// Setup event listeners
this.setupEventListeners();
// Setup file transfer protocol
this.managers.fileTransfer.setupFileTransferProtocol();
// Handle SPA routing - check for redirect parameter from 404.html
this.handleSpaRouting();
}
/**
* Sets up the UI manager and its callbacks.
* @returns A promise that resolves when the UI is set up.
* @internal
*/
private async setupUI(): Promise<void> {
if (!this.managers.ui) {
throw new Error('UIManager not initialized');
}
this.managers.ui.setupEventListeners();
// Override UI callbacks
this.managers.ui.onFileSelected = this.handleFileSelected.bind(this);
this.managers.ui.onPhraseEntered = this.handlePhraseEntered.bind(this);
this.managers.ui.onReceiveModeRequested =
this.handleReceiveModeRequested.bind(this);
}
/**
* Sets up global libp2p event listeners.
* @internal
*/
private setupEventListeners(): void {
if (!this.node || !this.managers.connection) {
return;
}
this.node.addEventListener(
'connection:open',
this.managers.connection.onConnectionEstablished.bind(
this.managers.connection,
),
);
this.node.addEventListener(
'connection:close',
this.managers.connection.onConnectionClosed.bind(
this.managers.connection,
),
);
}
/**
* Gets the best STUN server configuration.
* @returns A promise that resolves to the STUN server URL string.
* @internal
*/
private async getStunConfiguration(): Promise<string[]> {
if (!this.services.stun) {
return this.config.getStunServers();
}
try {
const closestStuns = await this.services.stun.getClosestStunServers();
return closestStuns ? closestStuns : this.config.getStunServers();
} catch (error) {
console.warn('Could not fetch closest STUN server:', error);
return this.config.getStunServers();
}
}
/**
* Handles the file selection event from the UI.
* @param file - The selected file.
* @internal
*/
private async handleFileSelected(file: File): Promise<void> {
if (!this.managers.ui || !this.managers.error) {
return;
}
try {
this.managers.ui.showSenderMode();
await this.startSenderMode(file);
} catch (error) {
this.managers.error.handleTransferError(error as Error, {
operation: 'fileSelected',
direction: 'send',
});
}
}
/**
* Handles the phrase submission event from the UI.
* @param phrase - The entered phrase.
* @internal
*/
private async handlePhraseEntered(phrase: string): Promise<void> {
if (!this.managers.error) {
return;
}
try {
await this.startReceiverMode(phrase);
} catch (error) {
this.managers.error.handleApiError(error as Error, {
operation: 'phraseEntered',
});
}
}
/**
* Handles the request to switch to receiver mode.
* @internal
*/
private async handleReceiveModeRequested(): Promise<void> {
if (!this.managers.ui) {
return;
}
this.managers.ui.showReceiverMode();
}
/**
* Starts the sender workflow.
* @param file - The file to be sent.
* @internal
*/
private async startSenderMode(file: File): Promise<void> {
if (!this.services.phrase || !this.managers.error) {
return;
}
try {
this.appState.setSelectedFile(file);
this.appState.setMode('sender');
console.log('Starting sender mode...');
// Generate phrase first
const phrase = await this.services.phrase.generatePhrase();
console.log(`Generated phrase: ${phrase}`);
// Update UI with phrase
this.managers.ui?.showPhrase(phrase);
// Get address
let webRTCMultiAddr;
while (!webRTCMultiAddr) {
webRTCMultiAddr = this.node
?.getMultiaddrs()
.find((ma) => WebRTC.matches(ma));
await new Promise((resolve) => setTimeout(resolve, 1000));
}
console.log('WebRTC Circuit Address:', webRTCMultiAddr?.toString());
// Register phrase
console.log('Registering phrase...');
await this.services.phrase.registerPhrase(phrase, webRTCMultiAddr);
console.log('Sender mode setup complete. Waiting for receiver...');
} catch (error) {
console.error('Failed to start sender mode:', error);
this.managers.error.handleTransferError(error as Error, {
operation: 'startSenderMode',
direction: 'send',
});
this.appState.setMode('idle');
throw error;
}
}
/**
* Starts the receiver workflow.
* @param phrase - The phrase to look up the sender.
* @internal
*/
private async startReceiverMode(phrase: string): Promise<void> {
if (
!this.appState ||
!this.services.phrase ||
!this.managers.connection ||
!this.node
) {
return;
}
this.appState.setMode('receiver');
// Lookup phrase
let addressData;
try {
addressData = await this.services.phrase.lookupPhrase(phrase);
} catch (error) {
this.managers.ui?.showErrorPopup(
'No address found for the provided phrase.',
);
}
if (addressData == undefined || !addressData.maddr) {
this.managers.ui?.showErrorPopup(
'No address found for the provided phrase.',
);
return;
}
const peerMultiaddr = multiaddr(addressData.maddr);
console.log(`Connecting to peer: ${addressData.maddr}`);
const connection = await this.managers.connection.dialPeer(peerMultiaddr, {
signal: AbortSignal.timeout(60000),
});
console.log(`Connected to sender via phrase: ${phrase}`);
this.appState.setActivePeer(connection.remotePeer.toString());
}
/**
* Handles SPA routing by checking for redirect parameter from 404.html
* and processing the current pathname for client-side routing.
* @internal
*/
private handleSpaRouting(): void {
// Check if we have a redirect parameter from 404.html
const urlParams = new URLSearchParams(window.location.search);
const redirectPath = urlParams.get('redirect');
if (redirectPath) {
// Remove the redirect parameter from URL and update history
const cleanUrl = window.location.origin + redirectPath;
window.history.replaceState({}, '', cleanUrl);
// Parse the redirected path for routing
const url = new URL(cleanUrl);
this.actionPathname(url.pathname + url.search);
} else {
// Handle normal pathname routing
const pathname = window.location.pathname;
const search = window.location.search;
if (pathname && pathname !== '/') {
this.actionPathname(pathname + search);
}
}
}
/**
* Conditionally handles the provided pathname of the current URL.
* If the pathname starts with `/send`, it shows the send window.
* If it starts with `/receive`, it checks for a phrase in the URL parameters,
* if the phrase is valid, it starts the receiver mode and shows the receiver window.
*
* @param pathWithQuery - The pathname and query string from the current URL.
* @internal
*/
private actionPathname(pathWithQuery: string): void {
// Parse pathname and query parameters from the input
const [pathname, queryString] = pathWithQuery.split('?');
const urlParams = queryString
? new URLSearchParams(queryString)
: new URLSearchParams();
if (pathname.startsWith('/send')) {
this.managers.ui?.showSendWindow();
} else if (pathname.startsWith('/receive')) {
this.managers.ui?.showReceiveWindow();
const phrase = this.services.phrase?.sanitizePhrase(
urlParams.get('phrase') || '',
);
if (phrase && this.services.phrase?.validatePhrase(phrase)) {
this.startReceiverMode(phrase);
this.managers.ui?.showReceiverMode();
this.managers.ui?.onPhraseEntered(phrase);
} else if (urlParams.get('phrase')) {
// Only show error if phrase was provided but invalid
this.managers.ui?.showErrorPopup('Invalid phrase provided.');
}
} else if (
pathname !== '/' &&
pathname !== '' &&
!pathname.startsWith('/staging')
) {
this.managers.ui?.showErrorPopup('404 Page Not Found');
}
}
/**
* Starts the application.
* @returns A promise that resolves when the app has started.
*/
public async start(): Promise<void> {
await this.initialize();
}
/**
* Stops the application and the libp2p node.
* @returns A promise that resolves when the app has stopped.
*/
public async stop(): Promise<void> {
if (this.node) {
await this.node.stop();
}
this.appState.reset();
console.log('FileFerry app stopped');
}
}
const app = new FileFerryApp();
document.addEventListener('DOMContentLoaded', async () => {
try {
await app.start();
} catch (error) {
console.error('Failed to start FileFerry app:', error);
}
});
window.addEventListener(
'unhandledrejection',
(event: PromiseRejectionEvent) => {
console.error('Unhandled promise rejection:', event.reason);
},
);
window.addEventListener('error', (event: ErrorEvent) => {
console.error('Global error:', event.error);
});
window.fileFerryApp = app;