heyujie
2021-05-24 4885600ecc369aa2e30a65de8dd7a410f13c34df
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
'use strict'
 
var Transform = require('readable-stream').Transform
var duplexify = require('duplexify')
 
/* global wx */
var socketTask
var proxy
var stream
 
function buildProxy () {
  var proxy = new Transform()
  proxy._write = function (chunk, encoding, next) {
    socketTask.send({
      data: chunk.buffer,
      success: function () {
        next()
      },
      fail: function (errMsg) {
        next(new Error(errMsg))
      }
    })
  }
  proxy._flush = function socketEnd (done) {
    socketTask.close({
      success: function () {
        done()
      }
    })
  }
 
  return proxy
}
 
function setDefaultOpts (opts) {
  if (!opts.hostname) {
    opts.hostname = 'localhost'
  }
  if (!opts.path) {
    opts.path = '/'
  }
 
  if (!opts.wsOptions) {
    opts.wsOptions = {}
  }
}
 
function buildUrl (opts, client) {
  var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  var url = protocol + '://' + opts.hostname + opts.path
  if (opts.port && opts.port !== 80 && opts.port !== 443) {
    url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  }
  if (typeof (opts.transformWsUrl) === 'function') {
    url = opts.transformWsUrl(url, opts, client)
  }
  return url
}
 
function bindEventHandler () {
  socketTask.onOpen(function () {
    stream.setReadable(proxy)
    stream.setWritable(proxy)
    stream.emit('connect')
  })
 
  socketTask.onMessage(function (res) {
    var data = res.data
 
    if (data instanceof ArrayBuffer) data = Buffer.from(data)
    else data = Buffer.from(data, 'utf8')
    proxy.push(data)
  })
 
  socketTask.onClose(function () {
    stream.end()
    stream.destroy()
  })
 
  socketTask.onError(function (res) {
    stream.destroy(new Error(res.errMsg))
  })
}
 
function buildStream (client, opts) {
  opts.hostname = opts.hostname || opts.host
 
  if (!opts.hostname) {
    throw new Error('Could not determine host. Specify host manually.')
  }
 
  var websocketSubProtocol =
    (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
      ? 'mqttv3.1'
      : 'mqtt'
 
  setDefaultOpts(opts)
 
  var url = buildUrl(opts, client)
  socketTask = wx.connectSocket({
    url: url,
    protocols: websocketSubProtocol
  })
 
  proxy = buildProxy()
  stream = duplexify.obj()
  stream._destroy = function (err, cb) {
    socketTask.close({
      success: function () {
        cb && cb(err)
      }
    })
  }
 
  var destroyRef = stream.destroy
  stream.destroy = function () {
    stream.destroy = destroyRef
 
    var self = this
    process.nextTick(function () {
      socketTask.close({
        fail: function () {
          self._destroy(new Error())
        }
      })
    })
  }.bind(stream)
 
  bindEventHandler()
 
  return stream
}
 
module.exports = buildStream