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

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

  ViewVC Help
Powered by ViewVC 1.1.26