-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreviewClient.js
258 lines (223 loc) · 7.43 KB
/
previewClient.js
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
'use babel'
'use strict'
const request = require('request')
const WebSocketClient = require('websocket').client
const WsBridge = require('./wsBridge')
const configurationManager = require('./configurationManager')
const THERA_CONFIG_URL = 'http://127.0.0.1:PORT/theraConfig'
const MOCK_CONFIG_URL = 'http://localhost:PORT/mockConfig'
const wsAddress = 'http://127.0.0.1:PORT'
const pageQRCode = 'http://127.0.0.1:PORT/ipAddressPort'
const WS_SEND_MSG = 'weex-run:ws-send-msg'
const HTTP_SEND_MSG = 'weex-run:http-send-msg'
const WS_CONNECTED = 'weex-run:ws-connected'
const SERVER_STATUS_STARTING = "starting"
const SERVER_STATUS_RUNNING = "running"
const SERVER_STATUS_SHUTDOWN = "shutdown"
const fsp = require('fs-promise')
const path = require('path')
const fs = require('fs')
module.exports = class PreviewClient {
constructor () {
atom.commands.add(atom.commands.rootNode, WS_SEND_MSG, (content) => this.wsSend(content))
atom.commands.add(atom.commands.rootNode, HTTP_SEND_MSG, (content) => this.httpSend(content.detail))
let projectPath = atom.project.getDirectories()[0].path
this.mockConfigPath = path.join(projectPath, 'mock', 'config.json')
this.launchConfigPath = path.join(projectPath, '.thera', 'launch.json')
}
start (fileToRun, protocol) {
return new Promise((resolve, reject) => {
this.sendLaunchConfig()
this.sendMockConfig()
})
}
requestQRCode () {
return new Promise((resolve, reject) => {
const imgURL = pageQRCode.replace('PORT', atom.config.get('weex-run.dumplingPort'))
request(imgURL, (err, response, body) => {
if (err || response.statusCode !== 200) {
console.error(`request qr image ${imgURL} error`, err)
resolve(undefined)
} else {
resolve(body)
}
})
})
}
httpSend (content) {
let {url, method, headers, body} = content
let payload = {
url: url,
method: method,
headers: headers,
body: JSON.stringify(body)
}
console.log(`send request ${url}`)
if (payload.method === 'POST') console.log(`send request body ${JSON.stringify(body)}`)
request(payload, (err, response, body) => {
if (err || response.statusCode !== 200) {
if (err) console.error(err)
} else {
console.log(body)
}
})
}
wsSend (content) {
this.wsClient = this.wsClient || new WebSocketClient()
if (this.wsClient.connection) {
console.log(`ws send msg ${JSON.stringify(content.detail)}`)
this.wsClient.connection.sendUTF(JSON.stringify(content.detail))
} else {
console.error('not connected yet')
}
}
wsConnect () {
var self = this
return new Promise((resolve, reject) => {
// If connection is valid, needn't do any thing.
if (this.wsClient && this.wsClient.connection && this.wsClient.connection.state === 'open') {
console.log('Thera connection to dumpling is alive. Needn\'t reconnection.');
resolve();
return;
}
// Clear current connection state.
if (this.wsClient && this.wsClient.connection) {
this.wsClient.connection.close('Normally closed.')
this.wsClient = null
}
this.wsClient = this.wsClient || new WebSocketClient()
this.wsClient.on('connectFailed', (error) => {
reject(error)
console.log(`Connect error: ${error.toString()}`)
})
this.wsClient.on('connect', (connection) => {
console.log('websocket connected')
self.wsClient.connection = connection
connection.on('error', (error) => {
console.log(`Connection error: ${error.toString()}`)
// reconnect after delay
setTimeout(() => {
console.log('reconnecting websocket after 3 seconds')
self.wsClient.connect(
wsAddress.replace('PORT', atom.config.get('weex-run.dumplingPort')),
undefined,
undefined,
{'from': 'thera'}
)
}, 1000 * 3)
})
connection.on('close', (error) => {
console.log('Connection closed: ' + error.toString())
notifyServerStatus.apply(self, [SERVER_STATUS_SHUTDOWN])
})
// dispatch message
connection.on('message', onRecvCallback.bind(self))
atom.commands.dispatch(atom.views.getView(atom.workspace), WS_CONNECTED)
this.watchLaunchConfig()
this.watchMockConfig()
resolve()
})
function onRecvCallback (message) {
// console.log(message)
this.wsBridge.dispatch(message)
}
function onSendCallback (message) {
// console.log(message)
this.wsClient.connection.sendUTF(message)
}
function notifyServerStatus(status) {
console.log('Server status: ' + status)
atom.commands.dispatch(atom.views.getView(atom.workspace), 'thera-live-server:shutdown')
}
if (this.wsBridge) {
this.wsBridge.dispose()
this.wsBridge = null
}
this.wsBridge = new WsBridge(onSendCallback.bind(this))
// connect with header from:thera
this.wsClient.connect(
wsAddress.replace('PORT', atom.config.get('weex-run.dumplingPort')),
undefined,
undefined,
{'from': 'thera'}
)
})
}
watchLaunchConfig() {
let projectPath = atom.project.getDirectories()[0].path
var launchConfigPath = path.join(projectPath, '.thera', 'launch.json')
fs.watchFile(launchConfigPath, (curr, prev) => {
this.sendLaunchConfig()
})
}
sendLaunchConfig() {
configurationManager.getConfig()
.then((configObject) => {
let options = {
url: THERA_CONFIG_URL.replace('PORT', atom.config.get('weex-run.dumplingPort')),
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'message': 'theraConfig',
'data': configObject
})
}
request(options, (err, response, body) => {
if (err) reject(err)
else {
console.log('start monitor file...')
console.log(body)
}
})
})
}
watchMockConfig(){
// watch config changes
fs.watchFile(this.mockConfigPath, (curr, prev) => {
this.sendMockConfig()
})
}
sendMockConfig(){
fsp.readJson(this.mockConfigPath)
.then((mockJSON) => {
let msg = this.parseMockConfig(mockJSON)
this.httpSend(msg)
})
}
parseMockConfig (config) {
let projectPath = atom.project.getDirectories()[0].path
var body
if (config) {
body = {
'message': 'mock',
'data': {
'mockData': [],
'mockModules': []
}
}
if(config.hasOwnProperty('mockData')){
config.mockData.forEach((data) => {
let mockUnit = {}
for (var key in data) {
if (data.hasOwnProperty(key)) {
mockUnit[key] = data[key].replace('${workspaceRoot}', projectPath)
}
}
body.data.mockData.push(mockUnit)
})
}
if(config.hasOwnProperty('mockModules')) {
body.data.mockModules = config.mockModules
}
}
let payload = {
url: MOCK_CONFIG_URL.replace('PORT', atom.config.get('weex-run.dumplingPort')),
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: body
}
return payload
}
}