/[meteor]/trunk/public_html/meteor.js
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /trunk/public_html/meteor.js

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 20 by andrew.betts, Sat May 5 15:04:41 2007 UTC revision 39 by andrew.betts, Sat Feb 2 16:49:20 2008 UTC
# Line 1  Line 1 
1  // Set domain at highest level  /*
2  var domainparts = document.domain.split(".");  stream: xhrinteractive, iframe, serversent
3  document.domain = domainparts[domainparts.length-2]+"."+domainparts[domainparts.length-1];  longpoll
4    smartpoll
5  Function.prototype.bind = function(obj) {  simplepoll
6          var method = this,  */
7          temp = function() {  
8                  return method.apply(obj, arguments);  Meteor = {
9          };  
10          return temp;          callbacks: {
11  }                  process: function() {},
12  Function.prototype.andThen=function(g) {                  reset: function() {},
13          var f=this;                  eof: function() {},
14          var a=this.arguments                  statuschanged: function() {},
15          return function(args) {                  changemode: function() {}
16                  f(a);g(args);          },
17          }          channelcount: 0,
18  };          channels: {},
19            debugmode: false,
20  function Meteor(instID) {          frameref: null,
21            host: null,
22          this.transferDoc = false;          hostid: null,
23          this.pingtimer = false;          maxpollfreq: 60000,
24          this.updatepollfreqtimer = false;          minpollfreq: 2000,
25          this.lastrequest = 0;          mode: "stream",
26          this.recvtimes = [];          pingtimeout: 20000,
27          this.MHostId = false;          pingtimer: null,
28          this.callback_process = function() {};          pollfreq: 3000,
29          this.callback_reset = function() {};          port: 80,
30          this.callback_eof = function() {};          polltimeout: 30000,
31          this.callback_changemode = function() {};          recvtimes: [],
32          this.callback_statuschanged = function() {};          status: 0,
33          this.persist = true;          updatepollfreqtimer: null,
34          this.frameloadtimer = false;  
35          this.debugmode = false;          register: function(ifr) {
36          this.subsurl = false;                  ifr.p = Meteor.process;
37          this.channels = {};                  ifr.r = Meteor.reset;
38                    ifr.eof = Meteor.eof;
39          // Documented public properties                  clearTimeout(Meteor.frameloadtimer);
40          this.subdomain = "data";                  Meteor.setstatus(4);
41          this.dynamicpageaddress = "push";                  Meteor.log("Frame registered");
42          this.smartpoll = true;          },
43          this.pollfreq = 2000;  
44          this.minpollfreq = 2000;          joinChannel: function(channelname, backtrack) {
45          this.mode = "poll";                  if (typeof(Meteor.channels[channelname]) != "undefined") throw "Cannot join channel "+channelname+": already subscribed";
46          this.polltimeout=30000;                  Meteor.channels[channelname] = {backtrack:backtrack, lastmsgreceived:0};
47          this.pingtimeout = 10000;                  Meteor.log("Joined channel "+channelname);
48          this.maxmessages = 0;                  Meteor.channelcount++;
49          this.status = 0;                  if (Meteor.status != 0) Meteor.connect();
50            },
51          /* Statuses:    0 = Uninitialised,  
52                                          1 = Loading stream,          leaveChannel: function(channelname) {
53                                          2 = Loading controller frame,                  if (typeof(Meteor.channels[channelname]) == "undefined") throw "Cannot leave channel "+channelname+": not subscribed";
54                                          3 = Controller frame timeout, retrying.                  delete Meteor.channels[channelname];
55                                          4 = Controller frame loaded and ready                  Meteor.log("Left channel "+channelname);
56                                          5 = Receiving data                  if (Meteor.status != 0) Meteor.connect();
57          */                  Meteor.channelcount--;
58            },
59          this.instID = (typeof(instID) != "undefined") ? instID : 0;  
60          this.MHostId = Math.floor(Math.random()*100000000)+""+this.instID;          connect: function() {
61  }                  Meteor.log("Connecting");
62                    if (!Meteor.host) throw "Meteor host not specified";
63  Meteor.instances = new Array();                  if (isNaN(Meteor.port)) throw "Meteor port not specified";
64                    if (!Meteor.channelcount) throw "No channels specified";
65  Meteor.create = function(instID) {                  if (Meteor.status) Meteor.disconnect();
66          if (!instID) instID = Meteor.instances.length;                  Meteor.setstatus(1);
67          Meteor.instances[instID] = new Meteor(instID);                  var now = new Date();
68          return Meteor.instances[instID];                  var t = now.getTime();
69  }                  if (!Meteor.hostid) Meteor.hostid = t+""+Math.floor(Math.random()*1000000)
70                    document.domain = Meteor.extract_xss_domain(document.domain);
71  Meteor.register = function(ifr) {                  if (Meteor.mode=="stream") Meteor.mode = Meteor.selectStreamTransport();
72          instid = new String(ifr.window.frameElement.id);                  Meteor.log("Selected "+Meteor.mode+" transport");
73          instid = instid.replace(/.*_([0-9]*)$/, "$1");                  if (Meteor.mode=="xhrinteractive" || Meteor.mode=="iframe" || Meteor.mode=="serversent") {
74          ifr.p = this.instances[instid].process.bind(this.instances[instid]);                          if (Meteor.mode == "iframe") {
75          ifr.r = this.instances[instid].reset.bind(this.instances[instid]);                                  Meteor.loadFrame(Meteor.getSubsUrl());
76          ifr.eof = this.instances[instid].eof.bind(this.instances[instid]);                          } else {
77          ifr.get = this.instances[instid].get.bind(this.instances[instid]);                                  Meteor.loadFrame("http://"+Meteor.host+((Meteor.port==80)?"":":"+Meteor.port)+"/stream.html");
78          ifr.increasepolldelay = this.instances[instid].increasepolldelay.bind(this.instances[instid]);                          }
79          clearTimeout(this.instances[instid].frameloadtimer);                          clearTimeout(Meteor.pingtimer);
80          this.instances[instid].setstatus(4);                          Meteor.pingtimer = setTimeout(Meteor.pollmode, Meteor.pingtimeout);
81          if (this.debugmode) console.log("Frame registered");  
82  }                  } else {
83                            Meteor.loadFrame("http://"+Meteor.host+((Meteor.port==80)?"":":"+Meteor.port)+"/poll.html");
84  Meteor.reset = function(ifr) {                          Meteor.recvtimes[0] = t;
85          instid = new String(ifr.window.frameElement.id);                          if (Meteor.updatepollfreqtimer) clearTimeout(Meteor.updatepollfreqtimer);
86          instid = instid.replace(/.*_([0-9]*)$/, "$1");                          if (Meteor.mode=='smartpoll') Meteor.updatepollfreqtimer = setInterval(Meteor.updatepollfreq, 2500);
87          this.instances[instid].reset();                          if (Meteor.mode=='longpoll') Meteor.pollfreq = Meteor.minpollfreq;
88  }                  }
89                    Meteor.lastrequest = t;
90  Meteor.prototype.joinChannel = function(channelname, backtrack) {          },
91          if (typeof(this.channels[channelname]) != "undefined") throw "Cannot join channel "+channelname+": already subscribed";  
92          this.channels[channelname] = {backtrack:backtrack, lastmsgreceived:0};          disconnect: function() {
93          if (this.debugmode) console.log("Joined channel "+channelname+", channel list follows");                  if (Meteor.status) {
94          if (this.debugmode) console.log(this.channels);                          clearTimeout(Meteor.pingtimer);
95          if (this.status != 0) this.start();                          clearTimeout(Meteor.updatepollfreqtimer);
96  }                          clearTimeout(Meteor.frameloadtimer);
97                            if (typeof CollectGarbage == 'function') CollectGarbage();
98  Meteor.prototype.leaveChannel = function(channelname) {                          Meteor.setstatus(0);
99          if (typeof(this.channels[channelname]) == "undefined") throw "Cannot leave channel "+channelname+": not subscribed";                  }
100          delete this.channels[channelname];          },
101          if (this.status != 0) this.start();          
102  }          selectStreamTransport: function() {
103                    try {
104  Meteor.prototype.start = function() {                          var test = ActiveXObject;
105          this.persist = (this.maxmessages)?1:0;                          return "iframe";
106          this.smartpoll = (this.smartpoll)?1:0;                  } catch (e) {}
107          this.mode = (this.mode=="stream")?"stream":"poll";                  if ((typeof window.addEventStream) == "function") return "iframe";
108          if (!this.subdomain || this.channels.length) throw "Channel or Meteor subdomain host not specified";                  return "xhrinteractive";
109          this.stop();          },
110          var now = new Date();  
111          var t = now.getTime();          getSubsUrl: function() {
112          this.setstatus(1);                  var surl = "http://" + Meteor.host + ((Meteor.port==80)?"":":"+Meteor.port) + "/push/" + Meteor.hostid + "/" + Meteor.mode;
113          var surl = "http://" + this.subdomain + "." + location.hostname + "/" + this.dynamicpageaddress + "?id=" + this.MHostId;                  for (var c in Meteor.channels) {
114          if (this.maxmessages && !this.persist) surl += "&maxmessages=" + this.maxmessages;                          surl += "/"+c;
115          for (var c in this.channels) {                          if (Meteor.channels[c].lastmsgreceived > 0) {
116                  surl += "&channel="+c;                                  surl += ".r"+(Meteor.channels[c].lastmsgreceived+1);
117                  if (this.channels[c].lastmsgreceived >= 0) {                          } else if (Meteor.channels[c].backtrack > 0) {
118                          surl += "&restartfrom="+this.channels[c].lastmsgreceived;                                  surl += ".b"+Meteor.channels[c].backtrack;
119                  } else if (this.channels[c].backtrack > 0) {                          } else if (Meteor.channels[c].backtrack < 0 || isNaN(Meteor.channels[c].backtrack)) {
120                          surl += "&backtrack="+this.channels[c].backtrack;                                  surl += ".h";
121                  } else if (this.channels[c].backtrack < 0 || isNaN(this.channels[c].backtrack)) {                          }
122                          surl += "&restartfrom=";                  }
123                  }                  return surl;
124          }          },
125          this.subsurl = surl;  
126          if (this.mode=="stream") {          loadFrame: function(url) {
127                  this.createIframe(this.subsurl);                  try {
128                  var f = this.pollmode.bind(this);                          if (!Meteor.frameref) {
129                  clearTimeout(this.pingtimer);                                  var transferDoc = new ActiveXObject("htmlfile");
130                  this.pingtimer = setTimeout(f, this.pingtimeout);                                  Meteor.frameref = transferDoc;
131                            }
132          } else {                          Meteor.frameref.open();
133                  this.createIframe("http://"+this.subdomain+"."+location.hostname+"/poll.html");                          Meteor.frameref.write("<html><script>");
134                  this.recvtimes[0] = t;                          Meteor.frameref.write("document.domain=\""+(document.domain)+"\";");
135                  if (this.updatepollfreqtimer) clearTimeout(this.updatepollfreqtimer);                          Meteor.frameref.write("</"+"script></html>");
136                  this.updatepollfreqtimer = setInterval(this.updatepollfreq.bind(this), 2500);                          Meteor.frameref.parentWindow.Meteor = Meteor;
137          }                          Meteor.frameref.close();
138          this.lastrequest = t;                          var ifrDiv = Meteor.frameref.createElement("div");
139  }                          Meteor.frameref.appendChild(ifrDiv);
140                            ifrDiv.innerHTML = "<iframe src=\""+url+"\"></iframe>";
141  Meteor.prototype.createIframe = function(url) {                  } catch (e) {
142          if (document.all) {                          if (!Meteor.frameref) {
143                  this.transferDoc = new ActiveXObject("htmlfile");                                  var ifr = document.createElement("IFRAME");
144                  this.transferDoc.open();                                  ifr.style.width = "10px";
145                  this.transferDoc.write("<html>");                                  ifr.style.height = "10px";
146                  this.transferDoc.write("<script>document.domain=\""+(document.domain)+"\";</"+"script>");                                  ifr.style.border = "none";
147                  this.transferDoc.write("</html>");                                  ifr.style.position = "absolute";
148                  this.transferDoc.parentWindow.Meteor = Meteor;                                  ifr.style.top = "-10px";
149                  this.transferDoc.close();                                  ifr.style.marginTop = "-10px";
150                  var ifrDiv = this.transferDoc.createElement("div");                                  ifr.style.zIndex = "-20";
151                  this.transferDoc.appendChild(ifrDiv);                                  ifr.Meteor = Meteor;
152                  ifrDiv.innerHTML = "<iframe id=\"meteorframe_"+this.instID+"\" src=\""+url+"\" style=\"display: none;\"></iframe>";                                  document.body.appendChild(ifr);
153          } else {                                  Meteor.frameref = ifr;
154                  var ifr = document.createElement("IFRAME");                          }
155                  ifr.style.width = "10px";                          Meteor.frameref.setAttribute("src", url);
156                  ifr.style.height = "10px";                  }
157                  ifr.style.border = "none";                  Meteor.log("Loading URL '"+url+"' into frame...");
158                  ifr.style.position = "absolute";                  Meteor.frameloadtimer = setTimeout(Meteor.frameloadtimeout, 5000);
159                  ifr.style.top = "-10px";          },
160                  ifr.style.marginTop = "-10px";  
161                  ifr.style.zIndex = "-20";          pollmode: function() {
162                  ifr.setAttribute("id", "meteorframe_"+this.instID);                  Meteor.log("Ping timeout");
163                  ifr.Meteor = Meteor;                  Meteor.mode="simplepoll";
164                  var innerifr = document.createElement("IFRAME");                  clearTimeout(Meteor.pingtimer);
165                  innerifr.setAttribute("src", url);                  Meteor.connect();
166                  innerifr.setAttribute("id", "meteorinnerframe_"+this.instID);                  Meteor.callbacks["changemode"]("poll");
167                  ifr.appendChild(innerifr);                  Meteor.lastpingtime = false;
168                  document.body.appendChild(ifr);          },
169          }  
170          if (this.debugmode) console.log("Loading URL '"+url+"' into frame...");          process: function(id, channel, data) {
171          var f = this.frameloadtimeout.bind(this);                  if (id == -1) {
172          this.frameloadtimer = setTimeout(f, 5000);                          Meteor.log("Ping");
173  }                          Meteor.ping();
174                    } else if (typeof(Meteor.channels[channel]) != "undefined" && id > Meteor.channels[channel].lastmsgreceived) {
175  Meteor.prototype.stop = function() {                          Meteor.log("Message "+id+" received on channel "+channel+" (last id on channel: "+Meteor.channels[channel].lastmsgreceived+")\n"+data);
176          if (typeof(this.transferDoc)=="object") {                          Meteor.callbacks["process"](data);
177                  this.transferDoc = false;                          Meteor.channels[channel].lastmsgreceived = id;
178          }                          if (Meteor.mode=="smartpoll") {
179          if (document.getElementById("meteorframe_"+this.instID)) {                                  var now = new Date();
180                  document.getElementById("meteorframe_"+this.instID).src="about:blank";                                  Meteor.recvtimes[Meteor.recvtimes.length] = now.getTime();
181                  document.body.removeChild(document.getElementById("meteorframe_"+this.instID));                                  while (Meteor.recvtimes.length > 5) Meteor.recvtimes.shift();
182          }                          }
183          if (!isNaN(this.pingtimer)) clearTimeout(this.pingtimer);                  }
184          if (!isNaN(this.updatepollfreqtimer)) clearTimeout(this.updatepollfreqtimer);                  Meteor.setstatus(5);
185          if (!isNaN(this.frameloadtimer)) clearTimeout(this.frameloadtimer);          },
186          this.setstatus(0);  
187  }          ping: function() {
188                    if (Meteor.pingtimer) {
189  Meteor.prototype.pollmode = function() {                          clearTimeout(Meteor.pingtimer);
190          if (this.debugmode) console.log("Ping timeout");                          Meteor.pingtimer = setTimeout(Meteor.pollmode, Meteor.pingtimeout);
191          this.mode="poll";                          var now = new Date();
192          this.start();                          Meteor.lastpingtime = now.getTime();
193          this.callback_changemode("poll");                  }
194          this.lastpingtime = false;                  Meteor.setstatus(5);
195  }          },
196    
197  Meteor.prototype.process = function(id, channel, data) {          reset: function() {
198          if (id == -1) {                  Meteor.log("Stream reset");
199                  if (this.debugmode) console.log("Ping");                  Meteor.ping();
200                  this.ping();                  Meteor.callbacks["reset"]();
201          } else if (typeof(this.channels[channel]) != "undefined" && id > this.channels[channel].lastmsgreceived) {                  var now = new Date();
202                  if (this.debugmode) console.log("Message "+id+" received on channel "+channel+" (last id on channel: "+this.channels[channel].lastmsgreceived+")\n"+data);                  var t = now.getTime();
203                  this.callback_process(data);                  var x = Meteor.pollfreq - (t-Meteor.lastrequest);
204                  this.channels[channel].lastmsgreceived = id;                  if (x < 10) x = 10;
205                  if (this.mode=="poll") {                  setTimeout(Meteor.connect, x);
206                          var now = new Date();          },
207                          var t = now.getTime();  
208                          this.recvtimes[this.recvtimes.length] = t;          eof: function() {
209                          while (this.recvtimes.length > 5) this.recvtimes.shift();                  Meteor.callbacks["eof"]();
210                  }          },
211          }  
212          this.setstatus(5);          updatepollfreq: function() {
213  }                  var now = new Date();
214                    var t = now.getTime();
215  Meteor.prototype.ping = function() {                  var avg = 0;
216          if (this.mode=="stream" && this.pingtimer) {                  for (var i=1; i<Meteor.recvtimes.length; i++) {
217                  clearTimeout(this.pingtimer);                          avg += (Meteor.recvtimes[i]-Meteor.recvtimes[i-1]);
218                  var f = this.pollmode.bind(this);                  }
219                  this.pingtimer = setTimeout(f, this.pingtimeout);                  avg += (t-Meteor.recvtimes[Meteor.recvtimes.length-1]);
220                  var now = new Date();                  avg /= Meteor.recvtimes.length;
221                  this.lastpingtime = now.getTime();                  var target = avg/2;
222          }                  if (target < Meteor.pollfreq && Meteor.pollfreq > Meteor.minpollfreq) Meteor.pollfreq = Math.ceil(Meteor.pollfreq*0.9);
223          this.setstatus(5);                  if (target > Meteor.pollfreq && Meteor.pollfreq < Meteor.maxpollfreq) Meteor.pollfreq = Math.floor(Meteor.pollfreq*1.05);
224  }          },
225    
226  Meteor.prototype.reset = function() {          registerEventCallback: function(evt, funcRef) {
227          if (this.debugmode) console.log("Stream reset");                  Function.prototype.andThen=function(g) {
228          var now = new Date();                          var f=this;
229          var t = now.getTime();                          var a=Meteor.arguments
230          var x = this.pollfreq - (t-this.lastrequest);                          return function(args) {
231          if (x < 10) x = 10;                                  f(a);g(args);
232          this.ping();                          }
233          this.callback_reset();                  };
234          setTimeout(this.start.bind(this), x);                  if (typeof Meteor.callbacks[evt] == "function") {
235  }                          Meteor.callbacks[evt] = (Meteor.callbacks[evt]).andThen(funcRef);
236                    } else {
237  Meteor.prototype.eof = function() {                          Meteor.callbacks[evt] = funcRef;
238          this.callback_eof();                  }
239  }          },
240    
241  Meteor.prototype.get = function(varname) {          frameloadtimeout: function() {
242          eval("var a = this."+varname+";");                  Meteor.log("Frame load timeout");
243          if (typeof(a) == "undefined") throw "Cannot get value of "+varname;                  if (Meteor.frameloadtimer) clearTimeout(Meteor.frameloadtimer);
244          return a;                  Meteor.setstatus(3);
245  }                  setTimeout(Meteor.connect, 5000);
246            },
247  Meteor.prototype.increasepolldelay = function() {  
248          this.pollfreq *= 2;          extract_xss_domain: function(old_domain) {
249  }                  if (old_domain.match(/^(\d{1,3}\.){3}\d{1,3}$/)) return old_domain;
250                    domain_pieces = old_domain.split('.');
251  Meteor.prototype.updatepollfreq = function() {                  return domain_pieces.slice(-2, domain_pieces.length).join(".");
252          if (this.smartpoll) {          },
253                  var now = new Date();  
254                  var t = now.getTime();          setstatus: function(newstatus) {
255                  var avg = 0;                  // Statuses:    0 = Uninitialised,
256                  for (var i=1; i<this.recvtimes.length; i++) {                  //                              1 = Loading stream,
257                          var x = (this.recvtimes[i]-this.recvtimes[i-1]);                  //                              2 = Loading controller frame,
258                          avg += (x>60000)? 60000 : x;                  //                              3 = Controller frame timeout, retrying.
259                  }                  //                              4 = Controller frame loaded and ready
260                  x = (t-this.recvtimes[this.recvtimes.length-1]);                  //                              5 = Receiving data
261                  avg += (x>180000)? 180000 : x;  
262                  avg /= this.recvtimes.length;                  if (Meteor.status != newstatus) {
263                  if ((avg/3) < this.pollfreq && (avg/3) >= this.minpollfreq) this.pollfreq = Math.ceil(this.pollfreq*0.9);                          Meteor.status = newstatus;
264                  if ((avg/3) > this.pollfreq) this.pollfreq = Math.floor(this.pollfreq*1.05);                          Meteor.callbacks["statuschanged"](newstatus);
265          }                  }
266  }          },
267    
268  Meteor.prototype.registerEventCallback = function(evt, funcRef) {          log: function(logstr) {
269          if (evt=="process") {                  if (Meteor.debugmode) {
270                  this.callback_process = (this.callback_process).andThen(funcRef);                          if (window.console) {
271          } else if (evt=="reset") {                                  window.console.log(logstr);
272                  this.callback_reset = (this.callback_reset).andThen(funcRef);                          } else if (document.getElementById("meteorlogoutput")) {
273          } else if (evt=="eof") {                                  document.getElementById("meteorlogoutput").innerHTML += logstr+"<br/>";
274                  this.callback_eof = (this.callback_eof).andThen(funcRef);                          }
275          } else if (evt=="changemode") {                  }
276                  this.callback_changemode = (this.callback_changemode).andThen(funcRef);          }
277          } else if (evt=="changestatus") {  }
278                  this.callback_statuschanged = (this.callback_statuschanged).andThen(funcRef);  
279          }  var oldonunload = window.onunload;
280  }  if (typeof window.onunload != 'function') {
281            window.onunload = Meteor.disconnect;
282  Meteor.prototype.frameloadtimeout = function() {  } else {
283          if (this.debugmode) console.log("Frame load timeout");          window.onunload = function() {
284          if (this.frameloadtimer) clearTimeout(this.frameloadtimer);                  if (oldonunload) oldonunload();
285          this.setstatus(3);                  Meteor.disconnect();
286          setTimeout(this.start.bind(this), 5000);          }
 }  
 Meteor.prototype.setstatus = function(newstatus) {  
         if (this.status != newstatus) {  
                 this.status = newstatus;  
                 this.callback_statuschanged(newstatus);  
         }  
 }  
   
 Meteor.createCookie = function(name,value,days) {  
         if (days) {  
                 var date = new Date();  
                 date.setTime(date.getTime()+(days*24*60*60*1000));  
                 var expires = "; expires="+date.toGMTString();  
         }  
         else var expires = "";  
         document.cookie = name+"="+value+expires+"; path=/";  
 }  
   
 Meteor.readCookie = function(name) {  
         var nameEQ = name + "=";  
         var ca = document.cookie.split(';');  
         for(var i=0;i < ca.length;i++) {  
                 var c = ca[i];  
                 while (c.charAt(0)==' ') c = c.substring(1,c.length);  
                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);  
         }  
         return null;  
 }  
   
 Meteor.eraseCookie = function(name) {  
         createCookie(name,"",-1);  
287  }  }

Legend:
Removed from v.20  
changed lines
  Added in v.39

  ViewVC Help
Powered by ViewVC 1.1.26