/[meteor]/googlecode.com/svn/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 /googlecode.com/svn/trunk/public_html/meteor.js

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

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

Legend:
Removed from v.7  
changed lines
  Added in v.53

  ViewVC Help
Powered by ViewVC 1.1.26