1 | const common = require('./common')
|
2 |
|
3 | function parseWebSocketRequest (socket, opts, params) {
|
4 | if (!opts) opts = {}
|
5 | params = JSON.parse(params)
|
6 |
|
7 | params.socket = socket
|
8 | if (params.action === 'announce') {
|
9 | params.action = common.ACTIONS.ANNOUNCE
|
10 |
|
11 | if (typeof params.info_hash !== 'string' || params.info_hash.length !== 20) {
|
12 | throw new Error('invalid info_hash')
|
13 | }
|
14 | params.info_hash = common.binaryToHex(params.info_hash)
|
15 |
|
16 | if (typeof params.peer_id !== 'string' || params.peer_id.length !== 20) {
|
17 | throw new Error('invalid peer_id')
|
18 | }
|
19 | params.peer_id = common.binaryToHex(params.peer_id)
|
20 |
|
21 | if (params.answer) {
|
22 | if (typeof params.to_peer_id !== 'string' || params.to_peer_id.length !== 20) {
|
23 | throw new Error('invalid `to_peer_id` (required with `answer`)')
|
24 | }
|
25 | params.to_peer_id = common.binaryToHex(params.to_peer_id)
|
26 | }
|
27 |
|
28 | params.left = Number(params.left)
|
29 | if (Number.isNaN(params.left)) params.left = Infinity
|
30 |
|
31 | params.numwant = Math.min(
|
32 | Number(params.offers && params.offers.length) || 0,
|
33 | common.MAX_ANNOUNCE_PEERS
|
34 | )
|
35 | params.compact = -1
|
36 | } else if (params.action === 'scrape') {
|
37 | params.action = common.ACTIONS.SCRAPE
|
38 |
|
39 | if (typeof params.info_hash === 'string') params.info_hash = [ params.info_hash ]
|
40 | if (Array.isArray(params.info_hash)) {
|
41 | params.info_hash = params.info_hash.map(binaryInfoHash => {
|
42 | if (typeof binaryInfoHash !== 'string' || binaryInfoHash.length !== 20) {
|
43 | throw new Error('invalid info_hash')
|
44 | }
|
45 | return common.binaryToHex(binaryInfoHash)
|
46 | })
|
47 | }
|
48 | } else {
|
49 | throw new Error('invalid action in WS request: ' + params.action)
|
50 | }
|
51 |
|
52 | params.ip = socket.realIPAddress
|
53 | params.port = socket.port
|
54 |
|
55 | if (params.port) {
|
56 | params.addr = (common.IPV6_RE.test(params.ip) ? '[' + params.ip + ']' : params.ip) + ':' + params.port
|
57 | }
|
58 |
|
59 | params.headers = socket.headers
|
60 |
|
61 | return params
|
62 | }
|
63 |
|
64 | module.exports = parseWebSocketRequest
|