]> git.scottworley.com Git - reliable-chat/blob - webclient/rc.js
Bidirectional communication!
[reliable-chat] / webclient / rc.js
1 var servers = ['chkno.net', 'localhost'];
2
3 var session = Math.random();
4 var seen = {};
5
6 function rcserverbase(server) {
7 // Add the default port if server doesn't contain a port number already
8 if (server.indexOf(":") == -1) {
9 return "http://" + server + ":21059";
10 } else {
11 return "http://" + server;
12 }
13 }
14
15 function rcaddmessagetohistory(message) {
16 var d = document.createElement("div");
17 d.appendChild(document.createTextNode(message));
18 var h = document.getElementById("history");
19 h.appendChild(d);
20 window.scrollTo(0, document.body.scrollHeight);
21 return d;
22 }
23
24 function make_seen_key(id, text) {
25 return id.replace(/@/g, "@@") + "_@_" + text.replace(/@/g, "@@");
26 }
27
28 function receiveMessage(server, time, id, text) {
29 var seen_key = make_seen_key(id, text);
30 if (!(seen_key in seen)) {
31 seen[seen_key] = true;
32 rcaddmessagetohistory(text);
33 }
34 }
35
36 function receiveMessageEvent(event)
37 {
38 for (i in servers) {
39 if (event.origin === rcserverbase(servers[i])) {
40 messages = JSON.parse(event.data);
41 for (j in messages) {
42 if ('Time' in messages[j] &&
43 'ID' in messages[j] &&
44 'Text' in messages[j]) {
45 receiveMessage(servers[i], messages[j]['Time'], messages[j]['ID'], messages[j]['Text']);
46 }
47 }
48 }
49 }
50 }
51
52 function rcconnect() {
53 window.addEventListener("message", receiveMessageEvent, false);
54 for (i in servers) {
55 // Create a hidden iframe for same-origin workaround
56 var iframe = document.createElement("iframe");
57 iframe.setAttribute("src", rcserverbase(servers[i]) + "/frame");
58 document.body.insertBefore(iframe, document.body.firstChild);
59 }
60 }
61
62 function rcsend(d, message) {
63 var id = new Date().getTime() + "-" + session + "-" + Math.random();
64 seen[make_seen_key(id, message)] = true;
65 var path = "/speak" +
66 "?id=" + encodeURIComponent(id) +
67 "&text=" + encodeURIComponent(message);
68 for (i in servers) {
69 var uri = rcserverbase(servers[i]) + path;
70 var img = document.createElement("img");
71 img.setAttribute("src", uri);
72 d.appendChild(img);
73 }
74 }
75
76 function rckeydown(event) {
77 if (event.keyCode == 13) {
78 var d = rcaddmessagetohistory(document.input.say.value);
79 rcsend(d, document.input.say.value);
80 document.input.say.value = "";
81 return false;
82 }
83 }