-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtracker.ts
More file actions
72 lines (65 loc) · 1.99 KB
/
tracker.ts
File metadata and controls
72 lines (65 loc) · 1.99 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
/// <reference path="../typings/index.d.ts" />
import * as http from 'http';
import * as url from 'url';
import * as errors from './tracker-errors';
import AnnounceGetRequestParams from './announce-get-request-params'
import TrackerService from './tracker-service';
import * as bencode from 'bencode';
import * as _ from 'lodash';
interface TrackerOptions {
verbose?: boolean;
}
export default class Tracker {
private DEFAULTS: TrackerOptions = {
verbose: false,
};
private options: TrackerOptions;
private service: TrackerService;
private server: http.Server;
constructor(options: TrackerOptions) {
this.options = _.defaults({}, options, this.DEFAULTS);
this.service = new TrackerService();
this.server = http.createServer();
this.server.on('request', this.onRequest.bind(this));
}
start (port: number) {
port = port || 8080;
this.server.listen(port);
}
close () {
this.server.close();
}
private onRequest(request: http.IncomingMessage, response: http.ServerResponse) {
var u = url.parse(request.url),
data;
if (this.options.verbose) {
console.log('request', request.method, request.url, request.socket.remoteAddress);
}
try {
if (request.method !== 'GET') {
throw new errors.NotFoundError();
}
if (u.pathname === '/announce') {
let params = new AnnounceGetRequestParams(u.query, request.socket.remoteAddress);
if (this.options.verbose) {
console.log('/announce', params);
}
data = this.service.announce(params);
} else {
throw new errors.NotFoundError();
}
} catch (err) {
if (err instanceof errors.TrackerError) {
response.statusCode = err.statusCode;
} else {
response.statusCode = 500;
}
data = err.message;
}
if (this.options.verbose) {
console.log('response', response.statusCode, data);
}
response.setHeader('Content-Type', 'text/plain');
response.end(bencode.encode(data));
}
}