2016-03-23 16:23:10 +01:00
|
|
|
'use strict'
|
|
|
|
|
2016-08-11 14:50:44 +02:00
|
|
|
const connect = require('pull-ws/client')
|
2016-03-14 21:19:42 +00:00
|
|
|
const mafmt = require('mafmt')
|
2016-12-15 21:06:54 -08:00
|
|
|
const includes = require('lodash.includes')
|
2016-06-19 06:35:31 +01:00
|
|
|
const Connection = require('interface-connection').Connection
|
2017-03-23 16:19:36 -07:00
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
const maToUrl = require('./ma-to-url')
|
2016-08-11 14:50:44 +02:00
|
|
|
const debug = require('debug')
|
|
|
|
const log = debug('libp2p:websockets:dialer')
|
2016-06-19 06:35:31 +01:00
|
|
|
|
2016-08-11 14:50:44 +02:00
|
|
|
const createListener = require('./listener')
|
2016-03-14 20:25:00 +00:00
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
class WebSockets {
|
2016-08-11 14:50:44 +02:00
|
|
|
dial (ma, options, callback) {
|
2016-06-19 06:35:31 +01:00
|
|
|
if (typeof options === 'function') {
|
|
|
|
callback = options
|
2016-03-14 20:25:00 +00:00
|
|
|
options = {}
|
|
|
|
}
|
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
callback = callback || function () {}
|
2016-06-19 06:35:31 +01:00
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
const url = maToUrl(ma)
|
2016-08-11 14:50:44 +02:00
|
|
|
log('dialing %s', url)
|
|
|
|
const socket = connect(url, {
|
|
|
|
binary: true,
|
2017-03-27 16:10:20 +01:00
|
|
|
onConnect: (err) => callback(err)
|
2016-06-19 06:35:31 +01:00
|
|
|
})
|
|
|
|
|
2016-08-11 14:50:44 +02:00
|
|
|
const conn = new Connection(socket)
|
2017-03-23 15:09:06 +00:00
|
|
|
conn.getObservedAddrs = (callback) => callback(null, [ma])
|
|
|
|
conn.close = (callback) => socket.close(callback)
|
2016-06-19 06:35:31 +01:00
|
|
|
|
2016-03-14 20:25:00 +00:00
|
|
|
return conn
|
|
|
|
}
|
|
|
|
|
2016-08-11 14:50:44 +02:00
|
|
|
createListener (options, handler) {
|
2016-03-14 20:25:00 +00:00
|
|
|
if (typeof options === 'function') {
|
|
|
|
handler = options
|
|
|
|
options = {}
|
|
|
|
}
|
|
|
|
|
2016-08-11 14:50:44 +02:00
|
|
|
return createListener(options, handler)
|
2016-03-14 20:25:00 +00:00
|
|
|
}
|
|
|
|
|
2016-08-11 14:50:44 +02:00
|
|
|
filter (multiaddrs) {
|
2016-05-29 09:00:26 +01:00
|
|
|
if (!Array.isArray(multiaddrs)) {
|
|
|
|
multiaddrs = [multiaddrs]
|
|
|
|
}
|
2016-08-11 14:50:44 +02:00
|
|
|
|
2016-03-14 20:25:00 +00:00
|
|
|
return multiaddrs.filter((ma) => {
|
2016-12-15 21:06:54 -08:00
|
|
|
if (includes(ma.protoNames(), 'ipfs')) {
|
2016-05-29 09:00:26 +01:00
|
|
|
ma = ma.decapsulate('ipfs')
|
|
|
|
}
|
2017-03-23 15:09:06 +00:00
|
|
|
return mafmt.WebSockets.matches(ma) || mafmt.WebSocketsSecure.matches(ma)
|
2016-03-14 20:25:00 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2017-03-23 15:09:06 +00:00
|
|
|
|
|
|
|
module.exports = WebSockets
|