-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.js
More file actions
266 lines (231 loc) · 8.88 KB
/
tracker.js
File metadata and controls
266 lines (231 loc) · 8.88 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
#!/usr/bin/env node
import { Server } from 'bittorrent-tracker'
import { readFileSync, existsSync } from 'fs'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { createServer } from 'net'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const indexFile = 'nostr-file-sync.html'
class GenericWebTorrentServer {
constructor(options = {}) {
this.config = {
port: options.port || process.env.PORT || 8080,
// Address to bind/listen on inside the container/host
bindAddress: options.bindAddress || process.env.BIND || '0.0.0.0',
// Public hostname used for logs/links/announce display
publicHostname: options.publicHostname || options.hostname || process.env.HOST || 'localhost',
interval: options.interval || 600000, // 10min - standard BitTorrent interval
...options
}
this.stats = {
announces: 0,
scrapes: 0,
torrents: 0,
peers: 0
}
this.initTracker()
}
initTracker() {
// Generic tracker - no filtering, embrace the network effect!
this.tracker = new Server({
udp: true, // Support traditional clients
http: true, // Support web and traditional clients
ws: true, // Primary for PWAs
stats: false, // We'll handle our own stats
interval: this.config.interval,
trustProxy: false
})
this.setupEventHandlers()
this.setupHTTPServer()
}
setupEventHandlers() {
this.tracker.on('error', (err) => {
console.error('❌ Tracker error:', err.message)
})
this.tracker.on('warning', (err) => {
console.warn('⚠️ Warning:', err.message)
})
this.tracker.on('listening', () => {
const wsAddr = this.tracker.ws?.address()
const udpAddr = this.tracker.udp?.address()
const httpAddr = this.tracker.http?.address()
console.log('🚀 Generic WebTorrent Server running!')
console.log(`🔒 Bound on: ${this.config.bindAddress} (internal) | Public: ${this.config.publicHostname}`)
if (wsAddr) console.log(`📡 WebSocket: ws://${wsAddr.address}:${wsAddr.port}`)
if (udpAddr) console.log(`📡 UDP: udp://${udpAddr.address}:${udpAddr.port}`)
if (httpAddr) console.log(`📡 HTTP: http://${httpAddr.address}:${httpAddr.port}/announce`)
console.log(`🌐 Web Interface: http://${this.config.publicHostname}:${this.config.port}`)
})
// Track activity for stats
this.tracker.on('start', () => { this.stats.announces++; this.updateStats() })
this.tracker.on('update', () => { this.stats.announces++; this.updateStats() })
this.tracker.on('complete', () => { this.stats.announces++; this.updateStats() })
this.tracker.on('stop', () => { this.stats.announces++; this.updateStats() })
}
updateStats() {
this.stats.torrents = Object.keys(this.tracker.torrents).length
this.stats.peers = Object.values(this.tracker.torrents)
.reduce((total, torrent) => total + torrent.peers.length, 0)
}
setupHTTPServer() {
// Store original request handlers before modifying
const originalListeners = this.tracker.http.listeners('request')
this.tracker.http.removeAllListeners('request')
this.tracker.http.on('request', (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`)
const pathname = url.pathname
if (pathname === '/') {
this.serveStaticFile(req, res, indexFile, 'text/html')
} else if (pathname === '/torrent.html') {
this.serveStaticFile(req, res, 'torrent.html', 'text/html')
} else if (pathname === '/torrent_plain.html') {
this.serveStaticFile(req, res, 'torrent_plain.html', 'text/html')
} else if (pathname === '/nostr-file-sync.html') {
this.serveStaticFile(req, res, 'nostr-file-sync.html', 'text/html')
} else if (pathname === '/api/stats') {
this.serveStats(req, res)
} else {
// Delegate to original tracker handlers
let handled = false
for (const listener of originalListeners) {
try {
listener.call(this.tracker.http, req, res)
handled = true
break
} catch (err) {
console.warn('Handler error:', err.message)
}
}
if (!handled) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Not Found')
}
}
})
}
serveStaticFile(req, res, filename, contentType) {
const filePath = join(__dirname, filename)
if (!existsSync(filePath)) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end(`File not found: ${filename}\nPlace ${filename} next to tracker.js`)
return
}
try {
const content = readFileSync(filePath, 'utf8')
res.writeHead(200, { 'Content-Type': contentType })
res.end(content)
} catch (error) {
res.writeHead(500, { 'Content-Type': 'text/plain' })
res.end(`Error serving file: ${error.message}`)
}
}
serveStats(req, res) {
this.updateStats()
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(this.stats))
}
async start() {
return new Promise((resolve, reject) => {
// Handle potential binding errors
this.tracker.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`❌ Port ${this.config.port} is already in use`)
console.log('💡 Try a different port: node tracker.js --port 8081')
process.exit(1)
} else if (err.code === 'EADDRNOTAVAIL') {
console.error(`❌ Address not available: ${err.address || ''}:${err.port || this.config.port}`)
console.log('💡 Inside Docker/containers, bind to all interfaces: --bind 0.0.0.0')
console.log(' And use --host <public-hostname> for external access (e.g. sslip.io).')
process.exit(1)
} else if (err.code === 'EINVAL') {
console.error('❌ Invalid address/port combination')
console.log('💡 Try: node tracker.js --bind 0.0.0.0 --port 8080')
process.exit(1)
} else if (err.code === 'EACCES') {
console.error(`❌ Permission denied for port ${this.config.port}`)
console.log('💡 Try a port above 1024: node tracker.js --port 8080')
process.exit(1)
} else {
console.error(`❌ Server error: ${err.message}`)
reject(err)
}
})
const listenHost = (this.config.bindAddress === '0.0.0.0' || this.config.bindAddress === '::' || !this.config.bindAddress)
? undefined
: this.config.bindAddress
this.tracker.listen(this.config.port, listenHost, (err) => {
if (err) {
console.error(`❌ Failed to start server: ${err.message}`)
if (err.code === 'EADDRINUSE') {
console.log('💡 Port is busy. Try: node tracker.js --port 8081')
}
reject(err)
} else {
resolve(this.tracker)
}
})
})
// Graceful shutdown
process.on('SIGINT', () => this.shutdown())
process.on('SIGTERM', () => this.shutdown())
}
async shutdown() {
console.log('\n🛑 Shutting down server...')
try {
if (this.tracker?.http) this.tracker.http.close()
if (this.tracker?.udp) this.tracker.udp.close()
if (this.tracker?.ws) this.tracker.ws.close()
console.log('✅ Server shutdown complete')
process.exit(0)
} catch (error) {
console.error('❌ Shutdown error:', error)
process.exit(1)
}
}
}
// CLI support
if (import.meta.url === `file://${process.argv[1]}`) {
const config = {}
const args = process.argv.slice(2)
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case '--port':
case '-p':
config.port = parseInt(args[++i])
break
case '--host':
// Public hostname (e.g., sslip.io) shown in logs/links
config.publicHostname = args[++i]
break
case '--bind':
// Bind/listen address (inside container/host)
config.bindAddress = args[++i]
break
case '--help':
case '-h':
console.log(`
WebTorrent P2P Server
Usage: node tracker.js [options]
Files needed:
tracker.js - This server file
index.html - Web interface (place in same directory)
Options:
-p, --port <number> Server port (default: 8080)
--bind <string> Bind address (default: 0.0.0.0)
--host <string> Public hostname for links (default: localhost)
-h, --help Show this help
Examples:
node tracker.js # Start on localhost:8080
node tracker.js --port 8081 # Use different port
node tracker.js --bind 0.0.0.0 # Bind to all interfaces
node tracker.js --host my.sslip.io # Public hostname for links
Web Interface: http://localhost:8080
`)
process.exit(0)
}
}
const server = new GenericWebTorrentServer(config)
server.start().catch(console.error)
}
export default GenericWebTorrentServer