UNPKG

2.45 kBJavaScriptView Raw
1/*
2 * Copyright 2014 Amadeus s.a.s.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16var Viewer = function (socket, data, testServer) {
17 this.socket = socket;
18 this.campaign = testServer.findCampaign(data.campaignId || 1);
19 if (!this.campaign || !this.campaign.results) {
20 socket.disconnect();
21 return;
22 }
23 this.connected = true;
24
25 this.onCampaignResult = this.onCampaignResult.bind(this);
26 this.onSocketDisconnected = this.onSocketDisconnected.bind(this);
27 this.onSocketData = this.onSocketData.bind(this);
28
29 this.socket.on("close", this.onSocketDisconnected);
30
31 this.resultsSent = 0;
32 this.allStoredResultsSent = false;
33
34 this.sendFirstResults();
35 this.socket.on("data", this.onSocketData);
36};
37
38Viewer.prototype.onSocketData = function (message) {
39 try {
40 var data = JSON.parse(message);
41 if (data.type === "firstResults") {
42 this.sendFirstResults();
43 }
44 } catch (e) {}
45};
46
47Viewer.prototype.sendFirstResults = function () {
48 if (this.allStoredResultsSent) {
49 return;
50 }
51 var results = this.campaign.results;
52 var i = this.resultsSent;
53 for (var l = Math.min(i + 50, results.length); i < l; i++) {
54 this.onCampaignResult(results[i]);
55 }
56 this.socket.write(JSON.stringify({
57 type: "firstResults",
58 transmitted: i,
59 total: results.length
60 }));
61 if (i == results.length) {
62 this.allStoredResultsSent = true;
63 this.campaign.on("result", this.onCampaignResult);
64 }
65};
66
67Viewer.prototype.onCampaignResult = function (result) {
68 this.resultsSent++;
69 this.socket.write(JSON.stringify({
70 type: "result",
71 result: result
72 }));
73};
74
75Viewer.prototype.onSocketDisconnected = function () {
76 this.connected = false;
77 if (this.allStoredResultsSent) {
78 this.campaign.removeListener("result", this.onCampaignResult);
79 }
80};
81
82module.exports = Viewer;