Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/lib/sugar-web/bus.js
blob: 79fe9dd2cd25b71e62c6eea97ee29e37c02c76c3 (plain)
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
define(["sugar-web/env"], function (env) {
    var lastId = 0;
    var callbacks = {};
    var notificationCallbacks = {};
    var client = null;
    var inputStreams = [];

    function WebSocketClient(environment) {
        this.queue = [];
        this.socket = null;

        var that = this;

        env.getEnvironment(function (error, environment) {
            var port = environment.apiSocketPort;
            var socket = new WebSocket("ws://localhost:" + port);

            socket.binaryType = "arraybuffer";

            socket.onopen = function () {
                var params = [environment.activityId,
                              environment.apiSocketKey];

                socket.send(JSON.stringify({
                    "method": "authenticate",
                    "id": "authenticate",
                    "params": params
                }));

                while (that.queue.length > 0) {
                    socket.send(that.queue.shift());
                }
            };

            socket.onmessage = function (message) {
                that.onMessage(message);
            };

            that.socket = socket;
        });
    }

    WebSocketClient.prototype.send = function (data) {
        if (this.socket && this.socket.readyState == WebSocket.OPEN) {
            this.socket.send(data);
        } else {
            this.queue.push(data);
        }
    };

    WebSocketClient.prototype.close = function () {
        this.socket.close();
    };

    var bus = {};

    function InputStream() {
        this.streamId = null;
        this.readCallback = null;
    }

    InputStream.prototype.open = function (callback) {
        var that = this;
        bus.sendMessage("open_stream", [], function (error, result) {
            that.streamId = result[0];
            inputStreams[that.streamId] = that;
            callback(error);
        });
    };

    InputStream.prototype.read = function (count, callback) {
        if (this.readCallback) {
            throw Error("Read already in progress");
        }

        this.readCallback = callback;

        var buffer = new ArrayBuffer(8);

        var headerView = new Uint8Array(buffer, 0, 1);
        headerView[0] = this.streamId;

        var bodyView = new Uint32Array(buffer, 4, 1);
        bodyView[0] = count;

        bus.sendBinary(buffer);
    };

    InputStream.prototype.gotData = function (buffer) {
        var callback = this.readCallback;

        this.readCallback = null;

        callback(null, buffer);
    };

    InputStream.prototype.close = function (callback) {
        var that = this;

        function onStreamClosed(error, result) {
            if (callback) {
                callback(error);
            }
            delete inputStreams[that.streamId];
        }

        bus.sendMessage("close_stream", [this.streamId], onStreamClosed);
    };

    function OutputStream() {
        this.streamId = null;
    }

    OutputStream.prototype.open = function (callback) {
        var that = this;
        bus.sendMessage("open_stream", [], function (error, result) {
            that.streamId = result[0];
            callback(error);
        });
    };

    OutputStream.prototype.write = function (data) {
        var buffer = new ArrayBuffer(data.byteLength + 1);

        var bufferView = new Uint8Array(buffer);
        bufferView[0] = this.streamId;
        bufferView.set(new Uint8Array(data), 1);

        bus.sendBinary(buffer);
    };

    OutputStream.prototype.close = function (callback) {
        bus.sendMessage("close_stream", [this.streamId], callback);
    };

    bus.createInputStream = function (callback) {
        return new InputStream();
    };

    bus.createOutputStream = function (callback) {
        return new OutputStream();
    };

    bus.sendMessage = function (method, params, callback) {
        var message = {
            "method": method,
            "id": lastId,
            "params": params
        };

        if (callback) {
            callbacks[lastId] = callback;
        }

        client.send(JSON.stringify(message));

        lastId++;
    };

    bus.onNotification = function (method, callback) {
        notificationCallbacks[method] = callback;
    };

    bus.sendBinary = function (buffer, callback) {
        client.send(buffer);
    };

    bus.listen = function (customClient) {
        if (customClient) {
            client = customClient;
        } else {
            client = new WebSocketClient();
        }

        client.onMessage = function (message) {
            if (typeof message.data != "string") {
                var dataView = new Uint8Array(message.data);
                var streamId = dataView[0];

                if (streamId in inputStreams) {
                    var inputStream = inputStreams[streamId];
                    inputStream.gotData(message.data.slice(1));
                }

                return;
            }

            var parsed = JSON.parse(message.data);
            var responseId = parsed.id;

            if (parsed.method) {
                var notificationCallback = notificationCallbacks[parsed.method];
                if (notificationCallback !== undefined) {
                    notificationCallback(parsed.params);
                }
                return;
            }

            if (responseId in callbacks) {
                var callback = callbacks[responseId];

                if (parsed.error === null) {
                    callback(null, parsed.result);
                } else {
                    callback(new Error(parsed.error), null);
                }

                delete callbacks[responseId];
            }
        };
    };

    bus.close = function () {
        client.close();
        client = null;
    };

    return bus;
});