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

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

  ViewVC Help
Powered by ViewVC 1.1.26