resources/js/qwebchannel.js raw
  1// Copyright (C) 2016 The Qt Company Ltd.
  2// Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>
  3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
  4// Qt-Security score:critical reason:data-parser
  5
  6"use strict";
  7
  8var QWebChannelMessageTypes = {
  9    signal: 1,
 10    propertyUpdate: 2,
 11    init: 3,
 12    idle: 4,
 13    debug: 5,
 14    invokeMethod: 6,
 15    connectToSignal: 7,
 16    disconnectFromSignal: 8,
 17    setProperty: 9,
 18    response: 10,
 19};
 20
 21var QWebChannel = function(transport, initCallback, converters)
 22{
 23    if (typeof transport !== "object" || typeof transport.send !== "function") {
 24        console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." +
 25                      " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send));
 26        return;
 27    }
 28
 29    var channel = this;
 30    this.transport = transport;
 31
 32    var converterRegistry =
 33    {
 34        Date : function(response) {
 35            if (typeof response === "string"
 36                && response.match(
 37                        /^-?\d+-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?([-+\u2212](\d{2}):(\d{2})|Z)?$/)) {
 38                var date = new Date(response);
 39                if (!isNaN(date))
 40                    return date;
 41            }
 42            return undefined; // Return undefined if current converter is not applicable
 43        }
 44    };
 45
 46    this.usedConverters = [];
 47
 48    this.addConverter = function(converter)
 49    {
 50        if (typeof converter === "string") {
 51            if (converterRegistry.hasOwnProperty(converter))
 52                this.usedConverters.push(converterRegistry[converter]);
 53            else
 54                console.error("Converter '" + converter + "' not found");
 55        } else if (typeof converter === "function") {
 56            this.usedConverters.push(converter);
 57        } else {
 58            console.error("Invalid converter object type " + typeof converter);
 59        }
 60    }
 61
 62    if (Array.isArray(converters)) {
 63        for (const converter of converters)
 64            this.addConverter(converter);
 65    } else if (converters !== undefined) {
 66        this.addConverter(converters);
 67    }
 68
 69    this.send = function(data)
 70    {
 71        if (typeof(data) !== "string") {
 72            data = JSON.stringify(data);
 73        }
 74        channel.transport.send(data);
 75    }
 76
 77    this.transport.onmessage = function(message)
 78    {
 79        var data = message.data;
 80        if (typeof data === "string") {
 81            data = JSON.parse(data);
 82        }
 83        switch (data.type) {
 84            case QWebChannelMessageTypes.signal:
 85                channel.handleSignal(data);
 86                break;
 87            case QWebChannelMessageTypes.response:
 88                channel.handleResponse(data);
 89                break;
 90            case QWebChannelMessageTypes.propertyUpdate:
 91                channel.handlePropertyUpdate(data);
 92                break;
 93            default:
 94                console.error("invalid message received:", message.data);
 95                break;
 96        }
 97    }
 98
 99    this.execCallbacks = {};
100    this.execId = 0;
101    this.exec = function(data, callback)
102    {
103        if (!callback) {
104            // if no callback is given, send directly
105            channel.send(data);
106            return;
107        }
108        if (channel.execId === Number.MAX_VALUE) {
109            // wrap
110            channel.execId = Number.MIN_VALUE;
111        }
112        if (data.hasOwnProperty("id")) {
113            console.error("Cannot exec message with property id: " + JSON.stringify(data));
114            return;
115        }
116        data.id = channel.execId++;
117        channel.execCallbacks[data.id] = callback;
118        channel.send(data);
119    };
120
121    this.objects = {};
122
123    this.handleSignal = function(message)
124    {
125        var object = channel.objects[message.object];
126        if (object) {
127            object.signalEmitted(message.signal, message.args);
128        } else {
129            console.warn("Unhandled signal: " + message.object + "::" + message.signal);
130        }
131    }
132
133    this.handleResponse = function(message)
134    {
135        if (!message.hasOwnProperty("id")) {
136            console.error("Invalid response message received: ", JSON.stringify(message));
137            return;
138        }
139        channel.execCallbacks[message.id](message.data);
140        delete channel.execCallbacks[message.id];
141    }
142
143    this.handlePropertyUpdate = function(message)
144    {
145        message.data.forEach(data => {
146            var object = channel.objects[data.object];
147            if (object) {
148                object.propertyUpdate(data.signals, data.properties);
149            } else {
150                console.warn("Unhandled property update: " + data.object + "::" + data.signal);
151            }
152        });
153        channel.exec({type: QWebChannelMessageTypes.idle});
154    }
155
156    this.debug = function(message)
157    {
158        channel.send({type: QWebChannelMessageTypes.debug, data: message});
159    };
160
161    channel.exec({type: QWebChannelMessageTypes.init}, function(data) {
162        for (const objectName of Object.keys(data)) {
163            new QObject(objectName, data[objectName], channel);
164        }
165
166        // now unwrap properties, which might reference other registered objects
167        for (const objectName of Object.keys(channel.objects)) {
168            channel.objects[objectName].unwrapProperties();
169        }
170
171        if (initCallback) {
172            initCallback(channel);
173        }
174        channel.exec({type: QWebChannelMessageTypes.idle});
175    });
176};
177
178function QObject(name, data, webChannel)
179{
180    this.__id__ = name;
181    webChannel.objects[name] = this;
182
183    // List of callbacks that get invoked upon signal emission
184    this.__objectSignals__ = {};
185
186    // Cache of all properties, updated when a notify signal is emitted
187    this.__propertyCache__ = {};
188
189    var object = this;
190
191    // ----------------------------------------------------------------------
192
193    this.unwrapQObject = function(response)
194    {
195        for (const converter of webChannel.usedConverters) {
196            var result = converter(response);
197            if (result !== undefined)
198                return result;
199        }
200
201        if (response instanceof Array) {
202            // support list of objects
203            return response.map(qobj => object.unwrapQObject(qobj))
204        }
205        if (!(response instanceof Object))
206            return response;
207
208        if (!response["__QObject*__"] || response.id === undefined) {
209            var jObj = {};
210            for (const propName of Object.keys(response)) {
211                jObj[propName] = object.unwrapQObject(response[propName]);
212            }
213            return jObj;
214        }
215
216        var objectId = response.id;
217        if (webChannel.objects[objectId])
218            return webChannel.objects[objectId];
219
220        if (!response.data) {
221            console.error("Cannot unwrap unknown QObject " + objectId + " without data.");
222            return;
223        }
224
225        var qObject = new QObject( objectId, response.data, webChannel );
226        qObject.destroyed.connect(function() {
227            if (webChannel.objects[objectId] === qObject) {
228                delete webChannel.objects[objectId];
229                // reset the now deleted QObject to an empty {} object
230                // just assigning {} though would not have the desired effect, but the
231                // below also ensures all external references will see the empty map
232                // NOTE: this detour is necessary to workaround QTBUG-40021
233                Object.keys(qObject).forEach(name => delete qObject[name]);
234            }
235        });
236        // here we are already initialized, and thus must directly unwrap the properties
237        qObject.unwrapProperties();
238        return qObject;
239    }
240
241    this.unwrapProperties = function()
242    {
243        for (const propertyIdx of Object.keys(object.__propertyCache__)) {
244            object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]);
245        }
246    }
247
248    function addSignal(signalData, isPropertyNotifySignal)
249    {
250        var signalName = signalData[0];
251        var signalIndex = signalData[1];
252        object[signalName] = {
253            connect: function(callback) {
254                if (typeof(callback) !== "function") {
255                    console.error("Bad callback given to connect to signal " + signalName);
256                    return;
257                }
258
259                object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || [];
260                object.__objectSignals__[signalIndex].push(callback);
261
262                // only required for "pure" signals, handled separately for properties in propertyUpdate
263                if (isPropertyNotifySignal)
264                    return;
265
266                // also note that we always get notified about the destroyed signal
267                if (signalName === "destroyed" || signalName === "destroyed()" || signalName === "destroyed(QObject*)")
268                    return;
269
270                // and otherwise we only need to be connected only once
271                if (object.__objectSignals__[signalIndex].length == 1) {
272                    webChannel.exec({
273                        type: QWebChannelMessageTypes.connectToSignal,
274                        object: object.__id__,
275                        signal: signalIndex
276                    });
277                }
278            },
279            disconnect: function(callback) {
280                if (typeof(callback) !== "function") {
281                    console.error("Bad callback given to disconnect from signal " + signalName);
282                    return;
283                }
284                // This makes a new list. This is important because it won't interfere with
285                // signal processing if a disconnection happens while emittig a signal
286                object.__objectSignals__[signalIndex] = (object.__objectSignals__[signalIndex] || []).filter(function(c) {
287                  return c != callback;
288                });
289                if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) {
290                    // only required for "pure" signals, handled separately for properties in propertyUpdate
291                    webChannel.exec({
292                        type: QWebChannelMessageTypes.disconnectFromSignal,
293                        object: object.__id__,
294                        signal: signalIndex
295                    });
296                }
297            }
298        };
299    }
300
301    /**
302     * Invokes all callbacks for the given signalname. Also works for property notify callbacks.
303     */
304    function invokeSignalCallbacks(signalName, signalArgs)
305    {
306        var connections = object.__objectSignals__[signalName];
307        if (connections) {
308            connections.forEach(function(callback) {
309                callback.apply(callback, signalArgs);
310            });
311        }
312    }
313
314    this.propertyUpdate = function(signals, propertyMap)
315    {
316        // update property cache
317        for (const propertyIndex of Object.keys(propertyMap)) {
318            var propertyValue = propertyMap[propertyIndex];
319            object.__propertyCache__[propertyIndex] = this.unwrapQObject(propertyValue);
320        }
321
322        for (const signalName of Object.keys(signals)) {
323            // Invoke all callbacks, as signalEmitted() does not. This ensures the
324            // property cache is updated before the callbacks are invoked.
325            invokeSignalCallbacks(signalName, signals[signalName]);
326        }
327    }
328
329    this.signalEmitted = function(signalName, signalArgs)
330    {
331        invokeSignalCallbacks(signalName, this.unwrapQObject(signalArgs));
332    }
333
334    function addMethod(methodData)
335    {
336        var methodName = methodData[0];
337        var methodIdx = methodData[1];
338
339        // Fully specified methods are invoked by id, others by name for host-side overload resolution
340        var invokedMethod = methodName[methodName.length - 1] === ')' ? methodIdx : methodName
341
342        object[methodName] = function() {
343            var args = [];
344            var callback;
345            var errCallback;
346            for (var i = 0; i < arguments.length; ++i) {
347                var argument = arguments[i];
348                if (typeof argument === "function")
349                    callback = argument;
350                else
351                    args.push(argument);
352            }
353
354            var result;
355            // during test, webChannel.exec synchronously calls the callback
356            // therefore, the promise must be constucted before calling
357            // webChannel.exec to ensure the callback is set up
358            if (!callback && (typeof(Promise) === 'function')) {
359              result = new Promise(function(resolve, reject) {
360                callback = resolve;
361                errCallback = reject;
362              });
363            }
364
365            webChannel.exec({
366                "type": QWebChannelMessageTypes.invokeMethod,
367                "object": object.__id__,
368                "method": invokedMethod,
369                "args": args
370            }, function(response) {
371                if (response !== undefined) {
372                    var result = object.unwrapQObject(response);
373                    if (callback) {
374                        (callback)(result);
375                    }
376                } else if (errCallback) {
377                  (errCallback)();
378                }
379            });
380
381            return result;
382        };
383    }
384
385    function bindGetterSetter(propertyInfo)
386    {
387        var propertyIndex = propertyInfo[0];
388        var propertyName = propertyInfo[1];
389        var notifySignalData = propertyInfo[2];
390        // initialize property cache with current value
391        // NOTE: if this is an object, it is not directly unwrapped as it might
392        // reference other QObject that we do not know yet
393        object.__propertyCache__[propertyIndex] = propertyInfo[3];
394
395        if (notifySignalData) {
396            if (notifySignalData[0] === 1) {
397                // signal name is optimized away, reconstruct the actual name
398                notifySignalData[0] = propertyName + "Changed";
399            }
400            addSignal(notifySignalData, true);
401        }
402
403        Object.defineProperty(object, propertyName, {
404            configurable: true,
405            get: function () {
406                var propertyValue = object.__propertyCache__[propertyIndex];
407                if (propertyValue === undefined) {
408                    // This shouldn't happen
409                    console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__);
410                }
411
412                return propertyValue;
413            },
414            set: function(value) {
415                if (value === undefined) {
416                    console.warn("Property setter for " + propertyName + " called with undefined value!");
417                    return;
418                }
419                object.__propertyCache__[propertyIndex] = value;
420                var valueToSend = value;
421                webChannel.exec({
422                    "type": QWebChannelMessageTypes.setProperty,
423                    "object": object.__id__,
424                    "property": propertyIndex,
425                    "value": valueToSend
426                });
427            }
428        });
429
430    }
431
432    // ----------------------------------------------------------------------
433
434    data.methods.forEach(addMethod);
435
436    data.properties.forEach(bindGetterSetter);
437
438    data.signals.forEach(function(signal) { addSignal(signal, false); });
439
440    Object.assign(object, data.enums);
441}
442
443QObject.prototype.toJSON = function() {
444    if (this.__id__ === undefined) return {};
445    return {
446        id: this.__id__,
447        "__QObject*__": true
448    };
449};
450
451//required for use with nodejs
452if (typeof module === 'object') {
453    module.exports = {
454        QWebChannel: QWebChannel
455    };
456}