UNPKG

2.02 kBJavaScriptView Raw
1const Buffer = require('safe-buffer').Buffer
2const querystring = require('querystring')
3
4exports.DEFAULT_ANNOUNCE_PEERS = 50
5exports.MAX_ANNOUNCE_PEERS = 82
6
7exports.binaryToHex = str => {
8 if (typeof str !== 'string') {
9 str = String(str)
10 }
11 return Buffer.from(str, 'binary').toString('hex')
12}
13
14exports.hexToBinary = str => {
15 if (typeof str !== 'string') {
16 str = String(str)
17 }
18 return Buffer.from(str, 'hex').toString('binary')
19}
20
21exports.IPV4_RE = /^[\d.]+$/
22exports.IPV6_RE = /^[\da-fA-F:]+$/
23exports.REMOVE_IPV4_MAPPED_IPV6_RE = /^::ffff:/
24
25exports.CONNECTION_ID = Buffer.concat([ toUInt32(0x417), toUInt32(0x27101980) ])
26exports.ACTIONS = { CONNECT: 0, ANNOUNCE: 1, SCRAPE: 2, ERROR: 3 }
27exports.EVENTS = { update: 0, completed: 1, started: 2, stopped: 3 }
28exports.EVENT_IDS = {
29 0: 'update',
30 1: 'completed',
31 2: 'started',
32 3: 'stopped'
33}
34exports.EVENT_NAMES = {
35 update: 'update',
36 completed: 'complete',
37 started: 'start',
38 stopped: 'stop'
39}
40
41function toUInt32 (n) {
42 const buf = Buffer.allocUnsafe(4)
43 buf.writeUInt32BE(n, 0)
44 return buf
45}
46exports.toUInt32 = toUInt32
47
48/**
49 * `querystring.parse` using `unescape` instead of decodeURIComponent, since bittorrent
50 * clients send non-UTF8 querystrings
51 * @param {string} q
52 * @return {Object}
53 */
54exports.querystringParse = q => {
55 const saved = querystring.unescape
56 querystring.unescape = unescape // global
57 const ret = querystring.parse(q)
58 querystring.unescape = saved
59 return ret
60}
61
62/**
63 * `querystring.stringify` using `escape` instead of encodeURIComponent, since bittorrent
64 * clients send non-UTF8 querystrings
65 * @param {Object} obj
66 * @return {string}
67 */
68exports.querystringStringify = obj => {
69 const saved = querystring.escape
70 querystring.escape = escape // global
71 let ret = querystring.stringify(obj)
72 ret = ret.replace(/[@*/+]/g, char => // `escape` doesn't encode the characters @*/+ so we do it manually
73 '%' + char.charCodeAt(0).toString(16).toUpperCase())
74 querystring.escape = saved
75 return ret
76}