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

Legend:
Removed from v.3  
changed lines
  Added in v.60

  ViewVC Help
Powered by ViewVC 1.1.26