1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | var 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 |
|
38 | Viewer.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 |
|
47 | Viewer.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 |
|
67 | Viewer.prototype.onCampaignResult = function (result) {
|
68 | this.resultsSent++;
|
69 | this.socket.write(JSON.stringify({
|
70 | type: "result",
|
71 | result: result
|
72 | }));
|
73 | };
|
74 |
|
75 | Viewer.prototype.onSocketDisconnected = function () {
|
76 | this.connected = false;
|
77 | if (this.allStoredResultsSent) {
|
78 | this.campaign.removeListener("result", this.onCampaignResult);
|
79 | }
|
80 | };
|
81 |
|
82 | module.exports = Viewer;
|