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

Legend:
Removed from v.22  
changed lines
  Added in v.32

  ViewVC Help
Powered by ViewVC 1.1.26