This repository has been archived by the owner on Dec 10, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 101
/
qz-websocket.js
349 lines (296 loc) · 12 KB
/
qz-websocket.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
var qzConfig = {
callbackMap: {
findPrinter: 'qzDoneFinding',
findPrinters: 'qzDoneFinding',
appendFile: 'qzDoneAppending',
appendXML: 'qzDoneAppending',
appendPDF: 'qzDoneAppending',
appendImage: 'qzDoneAppending',
print: 'qzDonePrinting',
printPS: 'qzDonePrinting',
printHTML: 'qzDonePrinting',
printToHost: 'qzDonePrinting',
printToFile: 'qzDonePrinting',
findPorts: 'qzDoneFindingPorts',
openPort: 'qzDoneOpeningPort',
closePort: 'qzDoneClosingPort',
findNetworkInfo: 'qzDoneFindingNetwork'
},
protocols: ["wss://", "ws://"], // Protocols to use, will try secure WS before insecure
uri: "localhost", // Base URL to server
ports: [8181, 8282, 8383, 8484], // Ports to try, insecure WS uses port (ports[x] + 1)
keepAlive: (60 * 1000), // Interval in millis to send pings to server
debug: true,
port: function() { return qzConfig.ports[qzConfig.portIndex] + qzConfig.protocolIndex; },
protocol: function() { return qzConfig.protocols[qzConfig.protocolIndex]; },
url: function() { return qzConfig.protocol() + qzConfig.uri + ":" + qzConfig.port(); },
increment: function() {
if (++qzConfig.portIndex < qzConfig.ports.length) {
return true;
}
return false;
},
outOfBounds: function() { return qzConfig.portIndex >= qzConfig.ports.length },
init: function(){
qzConfig.preemptive = {isActive: '', getVersion: '', getPrinter: '', getLogPostScriptFeatures: ''};
qzConfig.protocolIndex = window.location.protocol == "https:" ? 0 : 1; // Used to track which value in 'protocol' array is being used
qzConfig.portIndex = 0; // Used to track which value in 'ports' array is being used
return qzConfig;
}
};
var logger = {
info: function(v) { console.log(v); },
log: function(v) { if (qzConfig.debug) { console.log(v); } },
warn: function(v) { console.warn(v); },
error: function(v) { console.error(v); }
}
function deployQZ(host, debug) {
if (host) {
qzConfig.uri = host;
}
if (debug === false) {
qzConfig.debug = false;
}
logger.log(WebSocket);
qzConfig.init();
// Old standard of WebSocket used const CLOSED as 2, new standards use const CLOSED as 3, we need the newer standard for jetty
if ("WebSocket" in window && WebSocket.CLOSED != null && WebSocket.CLOSED > 2) {
logger.info('Starting deploy of qz');
connectWebsocket();
} else {
alert("WebSocket not supported");
window["deployQZ"] = null;
}
}
function connectWebsocket() {
logger.log('Attempting connection on port ' + qzConfig.port());
try {
var websocket = new WebSocket(qzConfig.url());
}
catch(e) {
logger.error(e);
}
if (websocket != null) {
websocket.valid = false;
websocket.onopen = function(evt) {
logger.log('Open:');
logger.log(evt);
websocket.valid = true;
connectionSuccess(websocket);
// Create the QZ object
createQZ(websocket);
// Send keep-alive to the websocket so connection does not timeout
// keep-alive over reconnecting so server is always able to send to client
websocket.keepAlive = window.setInterval(function() {
websocket.send("ping");
}, qzConfig.keepAlive);
};
websocket.onclose = function(event) {
try {
if (websocket.valid || qzConfig.outOfBounds()) {
qzSocketClose(event);
}
// Safari compatibility fix to raise error event
if (!websocket.valid && navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
websocket.onerror();
}
websocket.cleanup();
} catch (ignore) {}
};
websocket.onerror = function(event) {
if (websocket.valid || qzConfig.outOfBounds()) {
qzSocketError(event);
}
// Move on to the next port
if (!websocket.valid) {
websocket.cleanup();
if (qzConfig.increment()) {
connectWebsocket();
} else {
qzNoConnection();
}
}
};
websocket.cleanup = function() {
// Explicitly clear setInterval
if (websocket.keepAlive) {
window.clearInterval(websocket.keepAlive);
}
websocket = null;
};
} else {
logger.warn('Websocket connection failed');
qzNoConnection();
}
}
// Prototype-safe JSON.stringify
function stringify(o) {
if (Array.prototype.toJSON) {
logger.warn("Overriding Array.prototype.toJSON");
var result = null;
var tmp = Array.prototype.toJSON;
delete Array.prototype.toJSON;
result = JSON.stringify(o);
Array.prototype.toJSON = tmp;
return result;
}
return JSON.stringify(o);
}
function connectionSuccess(websocket) {
logger.info('Websocket connection successful');
websocket.sendObj = function(objMsg) {
var msg = stringify(objMsg);
logger.log("Sending " + msg);
var ws = this;
// Determine if the message requires signing
if (objMsg.method === 'listMessages' || Object.keys(qzConfig.preemptive).indexOf(objMsg.method) != -1) {
ws.send(msg);
} else {
signRequest(msg,
function(signature) {
ws.send(signature + msg);
}
);
}
};
websocket.onmessage = function(evt) {
var message = JSON.parse(evt.data);
if (message.error != undefined) {
logger.error(message.error);
return;
}
// After we ask for the list, the value will come back as a message.
// That means we have to deal with the listMessages separately from everything else.
if (message.method == 'listMessages') {
// Take the list of messages and add them to the qz object
mapMethods(websocket, message.result);
} else {
// Got a return value from a call
logger.log('Message:');
logger.log(message);
if (typeof message.result == 'string') {
//unescape special characters
message.result = message.result.replace(/%5C/g, "\\").replace(/%22/g, "\"");
//ensure boolean strings are read as booleans
if (message.result == "true" || message.result == "false") {
message.result = (message.result == "true");
}
if (message.result.substring(0, 1) == '[') {
message.result = JSON.parse(message.result);
}
//ensure null is read as null
if (message.result == "null") {
message.result = null;
}
}
if (message.callback != 'setupMethods' && message.result != undefined && message.result.constructor !== Array) {
message.result = [message.result];
}
// Special case for getException
if (message.method == 'getException') {
if (message.result != null) {
var result = message.result;
message.result = {
getLocalizedMessage: function() {
return result;
}
};
}
}
if (message.callback == 'setupMethods') {
logger.log("Resetting function call");
logger.log(message.result);
qz[message.method] = function() {
return message.result;
}
}
if (message.callback != null) {
try {
logger.log("Callbacking: " + message.callback);
if (window["qz"][message.callback] != undefined) {
window["qz"][message.callback].apply(this, message.init ? [message.method] : message.result);
} else {
window[message.callback].apply(this, message.result);
}
}
catch(err) {
logger.error(err);
}
}
}
logger.log("Finished processing message");
};
}
function createQZ(websocket) {
// Get list of methods from websocket
getCertificate(function(cert) {
websocket.sendObj({method: 'listMessages', params: [cert]});
window["qz"] = {};
});
}
function mapMethods(websocket, methods) {
logger.log('Adding ' + methods.length + ' methods to qz object');
for(var x = 0; x < methods.length; x++) {
var name = methods[x].name;
var returnType = methods[x].returns;
var numParams = methods[x].parameters;
// Determine how many parameters there are and create method with that many
(function(_name, _numParams, _returnType) {
//create function to map function name to parameter counted function
window["qz"][_name] = function() {
var func = undefined;
if (typeof arguments[arguments.length - 1] == 'function') {
func = window["qz"][_name + '_' + (arguments.length - 1)];
} else {
func = window["qz"][_name + '_' + arguments.length];
}
func.apply(this, arguments);
};
//create parameter counted function to include overloaded java methods in javascript object
window["qz"][_name + '_' + _numParams] = function() {
var args = [];
for(var i = 0; i < _numParams; i++) {
args.push(arguments[i]);
}
var cb = arguments[arguments.length - 1];
var cbName = _name + '_callback';
if ($.isFunction(cb)) {
var method = cb.name;
// Special case for IE, which does not have function.name property ..
if (method == undefined) {
method = cb.toString().match(/^function\s*([^\s(]+)/)[1];
}
if (method == 'setupMethods') {
cbName = method;
}
window["qz"][cbName] = cb;
} else {
logger.log("Using mapped callback " + qzConfig.callbackMap[_name] + "() for " + _name + "()");
cbName = qzConfig.callbackMap[_name];
}
logger.log("Calling " + _name + "(" + args + ") --> CB: " + cbName + "()");
websocket.sendObj({method: _name, params: args, callback: cbName, init: (cbName == 'setupMethods')});
}
})(name, numParams, returnType);
}
// Re-setup all functions with static returns
for(var key in qzConfig.preemptive) {
window["qz"][key](setupMethods);
}
// Special case for getNetworkUtilities
qz.getNetworkUtilities = function() {
return {setHostname: qz.setHostname, setPort: qz.setPort}
};
logger.log("Sent methods off to get rehabilitated");
}
function setupMethods(methodName) {
if ($.param(qzConfig.preemptive).length > 0) {
logger.log("Reset " + methodName);
delete qzConfig.preemptive[methodName];
logger.log("Methods left to return: " + $.param(qzConfig.preemptive).length);
// Fire ready method when everything on the QZ object has been added
if ($.param(qzConfig.preemptive).length == 0) {
qzReady();
}
}
}