-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
executable file
·103 lines (92 loc) · 2.46 KB
/
index.js
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
#!/usr/bin/env node
const fs = require('fs')
const torrentStream = require('torrent-stream')
const readTorrent = require('read-torrent')
const drive = require('./drive.js')
const dbFind = require('./db.js').dbFind
const db = require('./db.js').db
var argv = require('yargs')
.usage('Usage: $0 <command> [options]')
.command('add <torrentFile> [category]', 'Add torrent file to the DB', (yargs) => {
yargs
.positional('torrentFile', {
describe: 'torrent file',
type: 'string',
default: null
})
})
.command('list', 'List torrents in the DB')
.command('mount <path>', 'Mount torrents under specific path', (yargs) => {
yargs
.positional('path', {
describe: 'Path to mount the torrents',
type: 'string',
default: null
})
.demand('path')
})
.option('c', {
alias: 'cache-path',
description: 'Path for caching',
default: '/tmp'
})
.demandCommand()
.help('help')
.alias('h', 'help')
.argv
const command = argv._[0]
if (command === 'list') {
listTorrents()
}
if (command === 'add') {
addTorrent(argv.torrentFile, argv.category)
}
if (command === 'mount') {
mountTorrents()
}
async function listTorrents () {
dbFind({}, (items) => {
items.forEach(item => {
const line = [item.infoHash, item.name, item.category].filter(x => x).join('\t')
console.log(line)
})
})
}
async function addTorrent (torrentFile, category) {
console.log('Fetching torrent')
readTorrent(torrentFile, function (err, torrent, raw) {
if (err) {
console.error(err.message)
process.exit(2)
}
const ts = torrentStream(raw)
ts.on('ready', async function () {
const files = ts.files.map((file) => {
return { path: file.path, length: file.length }
})
console.log('Files:')
files.forEach(file => console.log(file))
const metadata = JSON.stringify({ files: files })
const doc = {
torrentFile: ts.metadata.toString('base64'),
name: ts.torrent.name,
infoHash: torrent.infoHash,
metadata: metadata,
category: category
}
db.insert(doc, function (err, newDoc) {
if (err) console.log(err)
process.exit()
})
})
})
}
function mountTorrents () {
let mount = argv.path
let cache = argv.cachePath
if (!mount) mount = '/tmp/data'
if (!cache) cache = '/tmp'
mount = fs.realpathSync(mount)
cache = fs.realpathSync(cache)
drive(mount, cache)
}