]> git.scottworley.com Git - reliable-chat/blame - webclient/rc.js
Bidirectional communication!
[reliable-chat] / webclient / rc.js
CommitLineData
f0e385c7 1var servers = ['chkno.net', 'localhost'];
991a5820
SW
2
3var session = Math.random();
f0e385c7 4var seen = {};
991a5820 5
f0e385c7 6function rcserverbase(server) {
991a5820
SW
7 // Add the default port if server doesn't contain a port number already
8 if (server.indexOf(":") == -1) {
f0e385c7 9 return "http://" + server + ":21059";
991a5820 10 } else {
f0e385c7
SW
11 return "http://" + server;
12 }
13}
14
15function 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
24function make_seen_key(id, text) {
25 return id.replace(/@/g, "@@") + "_@_" + text.replace(/@/g, "@@");
26}
27
28function 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
36function 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
52function 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);
991a5820
SW
59 }
60}
61
62function rcsend(d, message) {
63 var id = new Date().getTime() + "-" + session + "-" + Math.random();
f0e385c7 64 seen[make_seen_key(id, message)] = true;
991a5820
SW
65 var path = "/speak" +
66 "?id=" + encodeURIComponent(id) +
67 "&text=" + encodeURIComponent(message);
68 for (i in servers) {
f0e385c7 69 var uri = rcserverbase(servers[i]) + path;
991a5820
SW
70 var img = document.createElement("img");
71 img.setAttribute("src", uri);
72 d.appendChild(img);
73 }
74}
75
827f21bb
SW
76function rckeydown(event) {
77 if (event.keyCode == 13) {
f0e385c7 78 var d = rcaddmessagetohistory(document.input.say.value);
991a5820 79 rcsend(d, document.input.say.value);
827f21bb
SW
80 document.input.say.value = "";
81 return false;
82 }
83}