-
Notifications
You must be signed in to change notification settings - Fork 135
/
torrents.ts
1008 lines (907 loc) · 31.6 KB
/
torrents.ts
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import childProcess from 'child_process';
import contentDisposition from 'content-disposition';
import createTorrent from 'create-torrent';
import express, {Response} from 'express';
import fs from 'fs';
import path from 'path';
import rateLimit from 'express-rate-limit';
import sanitize from 'sanitize-filename';
import tar, {Pack} from 'tar-fs';
import type {
AddTorrentByFileOptions,
AddTorrentByURLOptions,
ContentToken,
ReannounceTorrentsOptions,
SetTorrentsTagsOptions,
} from '@shared/schema/api/torrents';
import type {
CheckTorrentsOptions,
CreateTorrentOptions,
DeleteTorrentsOptions,
MoveTorrentsOptions,
SetTorrentContentsPropertiesOptions,
SetTorrentsInitialSeedingOptions,
SetTorrentsPriorityOptions,
SetTorrentsSequentialOptions,
SetTorrentsTrackersOptions,
StartTorrentsOptions,
StopTorrentsOptions,
} from '@shared/types/api/torrents';
import {
addTorrentByFileSchema,
addTorrentByURLSchema,
reannounceTorrentsSchema,
setTorrentsTagsSchema,
} from '../../../shared/schema/api/torrents';
import {accessDeniedError, fileNotFoundError, isAllowedPath, sanitizePath} from '../../util/fileUtil';
import {getTempPath} from '../../models/TemporaryStorage';
import {getToken} from '../../util/authUtil';
const getDestination = async (
services: Express.Request['services'],
{destination, tags}: {destination?: string; tags?: Array<string>},
): Promise<string | undefined> => {
let autoDestination = destination === '' ? undefined : destination;
// Use preferred destination of the first tag
if (autoDestination == null) {
await services.settingService.get('torrentDestinations').then(
({torrentDestinations}) => {
autoDestination = torrentDestinations?.[tags?.[0] ?? ''];
},
() => undefined,
);
}
// Use default destination of torrent client
if (autoDestination == null) {
const {directoryDefault} = (await services.clientGatewayService.getClientSettings().catch(() => undefined)) ?? {};
autoDestination = directoryDefault;
}
// Use temporary directory of Flood
if (autoDestination == null || typeof autoDestination !== 'string') {
autoDestination = getTempPath('download/');
}
let sanitizedPath: string | null = null;
try {
sanitizedPath = sanitizePath(autoDestination);
if (!isAllowedPath(sanitizedPath)) {
return undefined;
}
} catch (e) {
return undefined;
}
return sanitizedPath;
};
const router = express.Router();
/**
* GET /api/torrents
* @summary Gets the list of torrents
* @tags Torrents
* @security User
* @return {TorrentListSummary} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.get(
'/',
async (req, res): Promise<Response> =>
req.services.torrentService
.fetchTorrentList()
.then((data) => {
if (data == null) {
throw new Error();
}
return res.status(200).json(data);
})
.catch(({code, message}) => res.status(500).json({code, message})),
);
/**
* POST /api/torrents/add-urls
* @summary Adds torrents by URLs.
* @tags Torrents
* @security User
* @param {AddTorrentByURLOptions} request.body.required - options - application/json
* @return {object} 200 - all torrents added - application/json
* @return {object} 202 - requests sent to torrent client - application/json
* @return {object} 207 - some succeed, some failed - application/json
* @return {Error} 403 - illegal destination - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, AddTorrentByURLOptions>(
'/add-urls',
async (req, res): Promise<Response> => {
const parsedResult = addTorrentByURLSchema.safeParse(req.body);
if (!parsedResult.success) {
return res.status(422).json({message: 'Validation error.'});
}
const {
urls,
cookies,
destination,
tags,
isBasePath,
isCompleted,
isSequential,
isInitialSeeding,
start,
} = parsedResult.data;
const finalDestination = await getDestination(req.services, {
destination,
tags,
});
if (finalDestination == null) {
const {code, message} = accessDeniedError();
return res.status(403).json({code, message});
}
return req.services.clientGatewayService
.addTorrentsByURL({
urls,
cookies: cookies != null ? cookies : {},
destination: finalDestination,
tags: tags ?? [],
isBasePath: isBasePath ?? false,
isCompleted: isCompleted ?? false,
isSequential: isSequential ?? false,
isInitialSeeding: isInitialSeeding ?? false,
start: start ?? false,
})
.then(
(response) => {
req.services.torrentService.fetchTorrentList();
if (response.length === 0) {
return res.status(202).json(response);
} else if (response.length < urls.length) {
return res.status(207).json(response);
} else {
return res.status(200).json(response);
}
},
({code, message}) => res.status(500).json({code, message}),
);
},
);
/**
* POST /api/torrents/add-files
* @summary Adds torrents by files.
* @tags Torrents
* @security User
* @param {AddTorrentByFileOptions} request.body.required - options - application/json
* @return {object} 200 - all torrents added - application/json
* @return {object} 202 - requests sent to torrent client - application/json
* @return {object} 207 - some succeed, some failed - application/json
* @return {Error} 403 - illegal destination - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, AddTorrentByFileOptions>(
'/add-files',
async (req, res): Promise<Response> => {
const parsedResult = addTorrentByFileSchema.safeParse(req.body);
if (!parsedResult.success) {
return res.status(422).json({message: 'Validation error.'});
}
const {
files,
destination,
tags,
isBasePath,
isCompleted,
isSequential,
isInitialSeeding,
start,
} = parsedResult.data;
const finalDestination = await getDestination(req.services, {
destination,
tags,
});
if (finalDestination == null) {
const {code, message} = accessDeniedError();
return res.status(403).json({code, message});
}
return req.services.clientGatewayService
.addTorrentsByFile({
files,
destination: finalDestination,
tags: tags ?? [],
isBasePath: isBasePath ?? false,
isCompleted: isCompleted ?? false,
isSequential: isSequential ?? false,
isInitialSeeding: isInitialSeeding ?? false,
start: start ?? false,
})
.then(
(response) => {
req.services.torrentService.fetchTorrentList();
if (response.length === 0) {
return res.status(202).json(response);
} else if (response.length < files.length) {
return res.status(207).json(response);
} else {
return res.status(200).json(response);
}
},
({code, message}) => res.status(500).json({code, message}),
);
},
);
/**
* POST /api/torrents/create
* @summary Creates a torrent
* @tags Torrents
* @security User
* @param {CreateTorrentOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/x-bittorrent
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, CreateTorrentOptions>(
'/create',
async (req, res): Promise<Response> => {
const {name, sourcePath, trackers, comment, infoSource, isPrivate, isInitialSeeding, tags, start} = req.body;
if (typeof sourcePath !== 'string') {
return res.status(422).json({message: 'Validation error.'});
}
const sanitizedPath = sanitizePath(sourcePath);
if (!isAllowedPath(sanitizedPath)) {
const {code, message} = accessDeniedError();
return res.status(403).json({code, message});
}
const torrentFileName = sanitize(name ?? sanitizedPath.split(path.sep).pop() ?? `${Date.now()}`).concat('.torrent');
const torrentPath = getTempPath(torrentFileName);
return new Promise<Response>((resolve) => {
createTorrent(
sanitizedPath,
{
name,
comment,
createdBy: 'Flood - flood.js.org',
private: isPrivate,
announceList: [trackers],
info: infoSource
? {
source: infoSource,
}
: undefined,
},
(err, torrent) => {
if (err) {
const {message} = err;
return resolve(res.status(500).json({message}));
}
fs.promises.writeFile(torrentPath, torrent).then(
() => {
res.attachment(torrentFileName);
res.download(torrentPath);
req.services.clientGatewayService
.addTorrentsByFile({
files: [torrent.toString('base64')],
destination: fs.lstatSync(sanitizedPath).isDirectory() ? sanitizedPath : path.dirname(sanitizedPath),
tags: tags ?? [],
isBasePath: true,
isCompleted: true,
isSequential: false,
isInitialSeeding: isInitialSeeding ?? false,
start: start ?? false,
})
.catch(() => {
// do nothing.
});
resolve(res);
},
({code, message}) => resolve(res.status(500).json({code, message})),
);
},
);
});
},
);
/**
* POST /api/torrents/start
* @summary Starts torrents.
* @tags Torrents
* @security User
* @param {StartTorrentsOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, StartTorrentsOptions>(
'/start',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.startTorrents(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* POST /api/torrents/stop
* @summary Stops torrents.
* @tags Torrents
* @security User
* @param {StopTorrentsOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, StopTorrentsOptions>(
'/stop',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.stopTorrents(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* POST /api/torrents/check-hash
* @summary Hash checks torrents.
* @tags Torrents
* @security User
* @param {CheckTorrentsOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, CheckTorrentsOptions>(
'/check-hash',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.checkTorrents(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* POST /api/torrents/move
* @summary Moves torrents to specified destination path.
* @tags Torrents
* @security User
* @param {MoveTorrentsOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, MoveTorrentsOptions>(
'/move',
async (req, res): Promise<Response> => {
let sanitizedPath: string | null = null;
try {
sanitizedPath = sanitizePath(req.body.destination);
if (!isAllowedPath(sanitizedPath)) {
const {code, message} = accessDeniedError();
return res.status(403).json({code, message});
}
} catch ({code, message}) {
return res.status(403).json({code, message});
}
return req.services.clientGatewayService.moveTorrents({...req.body, destination: sanitizedPath}).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
);
},
);
/**
* POST /api/torrents/delete
* @summary Removes torrents from Flood. Optionally deletes data of torrents.
* @tags Torrents
* @security User
* @param {DeleteTorrentsOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, DeleteTorrentsOptions>(
'/delete',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.removeTorrents(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* POST /api/torrents/reannounce
* @summary Reannounces torrents to trackers
* @tags Torrents
* @security User
* @param {ReannounceTorrentsOptions} - request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.post<unknown, unknown, ReannounceTorrentsOptions>(
'/reannounce',
async (req, res): Promise<Response> => {
const parsedResult = reannounceTorrentsSchema.safeParse(req.body);
if (!parsedResult.success) {
return res.status(422).json({message: 'Validation error.'});
}
return req.services.clientGatewayService.reannounceTorrents(parsedResult.data).then(
(response) => {
req.services.clientGatewayService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
);
},
);
/**
* PATCH /api/torrents/initial-seeding
* @summary Sets initial seeding mode of torrents.
* @tags Torrents
* @security User
* @param {SetTorrentsInitialSeedingOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.patch<unknown, unknown, SetTorrentsInitialSeedingOptions>(
'/initial-seeding',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.setTorrentsInitialSeeding(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* PATCH /api/torrents/priority
* @summary Sets priority of torrents.
* @tags Torrents
* @security User
* @param {SetTorrentsPriorityOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.patch<unknown, unknown, SetTorrentsPriorityOptions>(
'/priority',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.setTorrentsPriority(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* PATCH /api/torrents/sequential
* @summary Sets sequential mode of torrents.
* @tags Torrents
* @security User
* @param {SetTorrentsSequentialOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.patch<unknown, unknown, SetTorrentsSequentialOptions>(
'/sequential',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.setTorrentsSequential(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* PATCH /api/torrents/tags
* @summary Sets tags of torrents.
* @tags Torrents
* @security User
* @param {SetTorrentsTagsOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.patch<unknown, unknown, SetTorrentsTagsOptions>(
'/tags',
async (req, res): Promise<Response> => {
const parsedResult = setTorrentsTagsSchema.safeParse(req.body);
if (!parsedResult.success) {
return res.status(422).json({message: 'Validation error.'});
}
return req.services.clientGatewayService.setTorrentsTags(parsedResult.data).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
);
},
);
/**
* PATCH /api/torrents/trackers
* @summary Sets trackers of torrents.
* @tags Torrents
* @security User
* @param {SetTorrentsTrackersOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.patch<unknown, unknown, SetTorrentsTrackersOptions>(
'/trackers',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.setTorrentsTrackers(req.body).then(
(response) => {
req.services.torrentService.fetchTorrentList();
return res.status(200).json(response);
},
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* GET /api/torrents/{hash(, hash2, ...)}/metainfo
* @summary Gets meta-info (.torrent) files of torrents
* @tags Torrents
* @security User
* @param {string} hashes.path - Hash of a torrent, or hashes of torrents (split by ,)
* @return {object} 200 - single torrent - application/x-bittorrent
* @return {object} 200 - torrents archived in .tar - application/x-tar
* @return {Error} 422 - hash not provided - application/json
* @return {Error} 500 - other failure responses - application/json
*/
router.get<{hashes: string}>(
'/:hashes/metainfo',
// This operation is resource-intensive
// Limit each IP to 60 requests every 5 minutes
rateLimit({
windowMs: 5 * 60 * 1000,
max: 60,
}),
async (req, res): Promise<Response> => {
const hashes: Array<string> = req.params.hashes?.split(',').map((hash) => sanitize(hash));
if (!Array.isArray(hashes) || hashes?.length < 1) {
return res.status(422).json(new Error('Hash not provided.'));
}
const {path: sessionDirectory, case: torrentCase} =
(await req.services.clientGatewayService.getClientSessionDirectory().catch(() => undefined)) || {};
if (sessionDirectory == null || !fs.existsSync(sessionDirectory)) {
return res.status(500).json(new Error('Failed to get session directory.'));
}
const torrentFileNames = hashes.map(
(hash) => `${torrentCase === 'lower' ? hash.toLowerCase() : hash.toUpperCase()}.torrent`,
);
if (hashes.length < 2) {
res.attachment(torrentFileNames[0]);
res.download(path.join(sessionDirectory, torrentFileNames[0]));
return res;
}
try {
torrentFileNames.forEach((torrentFileName) =>
fs.accessSync(path.join(sessionDirectory, torrentFileName), fs.constants.R_OK),
);
} catch {
return res.status(404).json('Failed to access torrent files.');
}
res.attachment(`torrents-${Date.now()}.tar`);
return tar
.pack(sessionDirectory, {
entries: torrentFileNames,
strict: true,
dereference: false,
})
.pipe(res);
},
);
/**
*
* APIs below operate on a single torrent.
*
*/
/**
* TODO: API not yet implemented
* GET /api/torrents/{hash}
* @summary Gets information of a torrent.
* @tags Torrent
* @security User
* @param {string} hash.path - Hash of a torrent
*/
/**
* GET /api/torrents/{hash}/contents
* @summary Gets the list of contents of a torrent and their properties.
* @tags Torrent
* @security User
* @param {string} hash.path
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.get(
'/:hash/contents',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.getTorrentContents(req.params.hash).then(
(contents) => res.status(200).json(contents),
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* PATCH /api/torrents/{hash}/contents
* @summary Sets properties of contents of a torrent. Only priority can be set for now.
* @tags Torrent
* @security User
* @param {string} hash.path
* @param {SetTorrentContentsPropertiesOptions} request.body.required - options - application/json
* @return {object} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.patch<{hash: string}, unknown, SetTorrentContentsPropertiesOptions>(
'/:hash/contents',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.setTorrentContentsPriority(req.params.hash, req.body).then(
(response) => res.status(200).json(response),
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* GET /api/torrents/{hash}/contents/{indices}/token
* @summary Gets retrieval token of contents of a torrent.
* @tags Torrent
* @security User
* @param {string} hash.path
* @param {string} indices.path - 'all' or indices of selected contents separated by ','
* @return {string} 200 - token - text/plain
*/
router.get<{hash: string; indices: string}, unknown, unknown, {token: string}>(
'/:hash/contents/:indices/token',
// This operation performs authentication operations.
rateLimit({
windowMs: 5 * 60 * 1000,
max: 200,
}),
async (req, res): Promise<Response> => {
if (!req.user) {
return res.status(500).json({message: 'User is not attached.'});
}
const {hash, indices} = req.params;
return res.status(200).send(
getToken<ContentToken>({
username: req.user.username,
hash,
indices,
}),
);
},
);
/**
* GET /api/torrents/{hash}/contents/{indices}/data
* @summary Gets downloaded data of contents of a torrent.
* @tags Torrent
* @security User
* @param {string} hash.path
* @param {string} indices.path - 'all' or indices of selected contents separated by ','
* @return {object} 200 - contents archived in .tar - application/x-tar
*/
router.get<{hash: string; indices: string}, unknown, unknown, {token: string}>(
'/:hash/contents/:indices/data',
// This operation is resource-intensive
// Limit each IP to 200 requests every 5 minutes
rateLimit({
windowMs: 5 * 60 * 1000,
max: 200,
}),
async (req, res): Promise<Response> => {
const {hash, indices: stringIndices} = req.params;
if (req.user != null && req.query.token == null) {
// https://bugzilla.mozilla.org/show_bug.cgi?id=1689018
if (req.headers?.['user-agent']?.includes('Firefox/') !== true) {
res.redirect(
`?token=${getToken<ContentToken>({
username: req.user.username,
hash,
indices: stringIndices,
})}`,
);
return res;
}
}
const selectedTorrent = req.services.torrentService.getTorrent(hash);
if (!selectedTorrent) {
return res.status(404).json({error: 'Torrent not found.'});
}
return req.services.clientGatewayService
.getTorrentContents(hash)
.then((contents) => {
if (!contents || contents.length < 1) {
return res.status(404).json({error: 'Torrent contents not found'});
}
let indices: Array<number>;
if (!stringIndices || stringIndices === 'all') {
indices = contents.map((x) => x.index);
} else {
indices = stringIndices.split(',').map((value) => Number(value));
}
let filePathsToDownload = contents
.filter((content) => indices.includes(content.index))
.map((content) => sanitizePath(path.join(selectedTorrent.directory, content.path)));
filePathsToDownload = filePathsToDownload.filter((filePath) => isAllowedPath(filePath));
if (filePathsToDownload.length !== indices.length) {
const {code, message} = accessDeniedError();
return res.status(403).json({code, message});
}
filePathsToDownload = filePathsToDownload.filter((filePath) => fs.existsSync(filePath));
if (filePathsToDownload.length < 1 || filePathsToDownload.length !== indices.length) {
const {code, message} = fileNotFoundError();
return res.status(404).json({code, message});
}
if (filePathsToDownload.length === 1) {
const file = filePathsToDownload[0];
const fileName = path.basename(file);
const fileExt = path.extname(file);
let processedType: string = fileExt;
switch (fileExt) {
// Browsers don't support MKV streaming. However, browsers do support WebM which is a
// subset of MKV. Chromium supports MKV when encoded in selected codecs.
case '.mkv':
processedType = 'video/webm';
break;
// MIME database uses x-flac which is not recognized by browsers as streamable audio.
case '.flac':
processedType = 'audio/flac';
break;
default:
break;
}
res.type(processedType);
// Allow browsers to display the content inline when only a single content is requested.
// This is useful for texts, videos and audios. Users can still download them if needed.
res.setHeader('content-disposition', contentDisposition(fileName, {type: 'inline'}));
res.sendFile(file);
return res;
}
const archiveRootFolder = sanitizePath(selectedTorrent.directory);
const relativeFilePaths = filePathsToDownload.map((filePath) =>
filePath.replace(`${archiveRootFolder}${path.sep}`, ''),
);
res.attachment(`${selectedTorrent.name}.tar`);
const tarOptions: tar.PackOptions = {
strict: true,
dereference: false,
};
// Append file one by one to avoid OOM
const appendEntry = (prevPack: Pack) => {
const entry = relativeFilePaths.shift();
if (entry == null) {
prevPack.finalize();
} else {
tar.pack(archiveRootFolder, {
pack: prevPack,
entries: [entry],
...tarOptions,
finalize: false,
finish: appendEntry,
});
}
};
const tarStream = tar.pack(archiveRootFolder, {
entries: [relativeFilePaths.shift() as string],
...tarOptions,
finalize: false,
finish: appendEntry,
});
tarStream.pipe(res).once('close', () => {
tarStream.unpipe(res);
res.destroy();
});
return res;
})
.catch(({code, message}) => res.status(500).json({code, message}));
},
);
/**
* GET /api/torrents/{hash}/details
* @summary Gets details of a torrent.
* @tags Torrent
* @security User
* @param {string} hash.path
*/
router.get(
'/:hash/details',
async (req, res): Promise<Response> => {
try {
const contents = req.services.clientGatewayService.getTorrentContents(req.params.hash);
const peers = req.services.clientGatewayService.getTorrentPeers(req.params.hash);
const trackers = req.services.clientGatewayService.getTorrentTrackers(req.params.hash);
await Promise.all([contents, peers, trackers]);
return res.status(200).json({
contents: await contents,
peers: await peers,
trackers: await trackers,
});
} catch ({code, message}) {
return res.status(500).json({code, message});
}
},
);
/**
* GET /api/torrents/{hash}/mediainfo
* @summary Gets mediainfo output of a torrent.
* @tags Torrent
* @security User
* @param {string} hash.path
* @return {{output: string}} - 200 - success response - application/json
*/
router.get<{hash: string}>(
'/:hash/mediainfo',
// This operation is resource-intensive
// Limit each IP to 30 requests every 5 minutes
rateLimit({
windowMs: 5 * 60 * 1000,
max: 30,
}),
async (req, res): Promise<Response> => {
const torrentDirectory = req.services.torrentService.getTorrent(req.params.hash)?.directory;
const torrentContents = await req.services.clientGatewayService
.getTorrentContents(req.params.hash)
.catch(() => undefined);
if (torrentDirectory == null || torrentContents == null || torrentContents.length < 1) {
return res.status(404).json({message: 'Failed to fetch info of torrent.'});
}
try {
let torrentContentPaths = torrentContents?.map((content) =>
sanitizePath(path.join(torrentDirectory, content.path)),
);
torrentContentPaths = torrentContentPaths.filter((contentPath) => isAllowedPath(contentPath));
if (torrentContentPaths.length < 1) {
const {code, message} = accessDeniedError();
return res.status(403).json({code, message});
}
torrentContentPaths = torrentContentPaths.filter((contentPath) => fs.existsSync(contentPath));
if (torrentContentPaths.length < 1) {
const {code, message} = fileNotFoundError();
return res.status(404).json({code, message});
}
const mediainfoProcess = childProcess.execFile(
'mediainfo',
torrentContentPaths,
{maxBuffer: 1024 * 2000, timeout: 1000 * 10},
(error, stdout, stderr) => {
if (error) {
return res.status(500).json({message: error.message});
}
if (stderr) {
return res.status(500).json({message: stderr});
}
return res.status(200).json({output: stdout});
},
);
req.on('close', () => mediainfoProcess.kill('SIGTERM'));
return res;
} catch ({code, message}) {
return res.status(500).json({code, message});
}
},
);
/**
* GET /api/torrents/{hash}/peers
* @summary Gets the list of peers of a torrent.
* @tags Torrent
* @security User
* @param {string} hash.path
*/
router.get(
'/:hash/peers',
async (req, res): Promise<Response> =>
req.services.clientGatewayService.getTorrentPeers(req.params.hash).then(
(peers) => res.status(200).json(peers),
({code, message}) => res.status(500).json({code, message}),
),
);
/**
* GET /api/torrents/{hash}/trackers
* @summary Gets the list of trackers of a torrent.
* @tags Torrent
* @security User
* @param {string} hash.path
* @return {Array<TorrentTracker>} 200 - success response - application/json
* @return {Error} 500 - failure response - application/json
*/
router.get(
'/:hash/trackers',