novnc-rails 0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (31) hide show
  1. checksums.yaml +7 -0
  2. data/COPYING +0 -0
  3. data/LICENSE.txt +0 -0
  4. data/README.md +0 -0
  5. data/lib/novnc-rails.rb +8 -0
  6. data/lib/novnc-rails/version.rb +5 -0
  7. data/vendor/assets/javascripts/noVNC/Orbitron700.ttf +0 -0
  8. data/vendor/assets/javascripts/noVNC/Orbitron700.woff +0 -0
  9. data/vendor/assets/javascripts/noVNC/base.css +512 -0
  10. data/vendor/assets/javascripts/noVNC/base64.js +113 -0
  11. data/vendor/assets/javascripts/noVNC/black.css +71 -0
  12. data/vendor/assets/javascripts/noVNC/blue.css +64 -0
  13. data/vendor/assets/javascripts/noVNC/des.js +276 -0
  14. data/vendor/assets/javascripts/noVNC/display.js +751 -0
  15. data/vendor/assets/javascripts/noVNC/input.js +388 -0
  16. data/vendor/assets/javascripts/noVNC/jsunzip.js +676 -0
  17. data/vendor/assets/javascripts/noVNC/keyboard.js +543 -0
  18. data/vendor/assets/javascripts/noVNC/keysym.js +378 -0
  19. data/vendor/assets/javascripts/noVNC/keysymdef.js +15 -0
  20. data/vendor/assets/javascripts/noVNC/logo.js +1 -0
  21. data/vendor/assets/javascripts/noVNC/playback.js +102 -0
  22. data/vendor/assets/javascripts/noVNC/rfb.js +1889 -0
  23. data/vendor/assets/javascripts/noVNC/ui.js +979 -0
  24. data/vendor/assets/javascripts/noVNC/util.js +656 -0
  25. data/vendor/assets/javascripts/noVNC/web-socket-js/README.txt +109 -0
  26. data/vendor/assets/javascripts/noVNC/web-socket-js/WebSocketMain.swf +0 -0
  27. data/vendor/assets/javascripts/noVNC/web-socket-js/swfobject.js +4 -0
  28. data/vendor/assets/javascripts/noVNC/web-socket-js/web_socket.js +391 -0
  29. data/vendor/assets/javascripts/noVNC/websock.js +388 -0
  30. data/vendor/assets/javascripts/noVNC/webutil.js +239 -0
  31. metadata +86 -0
@@ -0,0 +1,109 @@
1
+ * How to try
2
+
3
+ Assuming you have Web server (e.g. Apache) running at http://example.com/ .
4
+
5
+ - Download web_socket.rb from:
6
+ http://github.com/gimite/web-socket-ruby/tree/master
7
+ - Run sample Web Socket server (echo server) in example.com with: (#1)
8
+ $ ruby web-socket-ruby/samples/echo_server.rb example.com 10081
9
+ - If your server already provides socket policy file at port 843, modify the file to allow access to port 10081. Otherwise you can skip this step. See below for details.
10
+ - Publish the web-socket-js directory with your Web server (e.g. put it in ~/public_html).
11
+ - Change ws://localhost:10081 to ws://example.com:10081 in sample.html.
12
+ - Open sample.html in your browser.
13
+ - After "onopen" is shown, input something, click [Send] and confirm echo back.
14
+
15
+ #1: First argument of echo_server.rb means that it accepts Web Socket connection from HTML pages in example.com.
16
+
17
+
18
+ * Troubleshooting
19
+
20
+ If it doesn't work, try these:
21
+
22
+ 1. Try Chrome and Firefox 3.x.
23
+ - It doesn't work on Chrome:
24
+ -- It's likely an issue of your code or the server. Debug your code as usual e.g. using console.log.
25
+ - It works on Chrome but it doesn't work on Firefox:
26
+ -- It's likely an issue of web-socket-js specific configuration (e.g. 3 and 4 below).
27
+ - It works on both Chrome and Firefox, but it doesn't work on your browser:
28
+ -- Check "Supported environment" section below. Your browser may not be supported by web-socket-js.
29
+
30
+ 2. Add this line before your code:
31
+ WEB_SOCKET_DEBUG = true;
32
+ and use Developer Tools (Chrome/Safari) or Firebug (Firefox) to see if console.log outputs any errors.
33
+
34
+ 3. Make sure you do NOT open your HTML page as local file e.g. file:///.../sample.html. web-socket-js doesn't work on local file. Open it via Web server e.g. http:///.../sample.html.
35
+
36
+ 4. If you are NOT using web-socket-ruby as your WebSocket server, you need to place Flash socket policy file on your server. See "Flash socket policy file" section below for details.
37
+
38
+ 5. Check if sample.html bundled with web-socket-js works.
39
+
40
+ 6. Make sure the port used for WebSocket (10081 in example above) is not blocked by your server/client's firewall.
41
+
42
+ 7. Install debugger version of Flash Player available here to see Flash errors:
43
+ http://www.adobe.com/support/flashplayer/downloads.html
44
+
45
+
46
+ * Supported environments
47
+
48
+ It should work on:
49
+ - Google Chrome 4 or later (just uses native implementation)
50
+ - Firefox 3.x, Internet Explorer 8 + Flash Player 9 or later
51
+
52
+ It may or may not work on other browsers such as Safari, Opera or IE 6. Patch for these browsers are appreciated, but I will not work on fixing issues specific to these browsers by myself.
53
+
54
+
55
+ * Flash socket policy file
56
+
57
+ This implementation uses Flash's socket, which means that your server must provide Flash socket policy file to declare the server accepts connections from Flash.
58
+
59
+ If you use web-socket-ruby available at
60
+ http://github.com/gimite/web-socket-ruby/tree/master
61
+ , you don't need anything special, because web-socket-ruby handles Flash socket policy file request. But if you already provide socket policy file at port 843, you need to modify the file to allow access to Web Socket port, because it precedes what web-socket-ruby provides.
62
+
63
+ If you use other Web Socket server implementation, you need to provide socket policy file yourself. See
64
+ http://www.lightsphere.com/dev/articles/flash_socket_policy.html
65
+ for details and sample script to run socket policy file server. node.js implementation is available here:
66
+ http://github.com/LearnBoost/Socket.IO-node/blob/master/lib/socket.io/transports/flashsocket.js
67
+
68
+ Actually, it's still better to provide socket policy file at port 843 even if you use web-socket-ruby. Flash always try to connect to port 843 first, so providing the file at port 843 makes startup faster.
69
+
70
+
71
+ * Cookie considerations
72
+
73
+ Cookie is sent if Web Socket host is the same as the origin of JavaScript. Otherwise it is not sent, because I don't know way to send right Cookie (which is Cookie of the host of Web Socket, I heard).
74
+
75
+ Note that it's technically possible that client sends arbitrary string as Cookie and any other headers (by modifying this library for example) once you place Flash socket policy file in your server. So don't trust Cookie and other headers if you allow connection from untrusted origin.
76
+
77
+
78
+ * Proxy considerations
79
+
80
+ The WebSocket spec (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol) specifies instructions for User Agents to support proxied connections by implementing the HTTP CONNECT method.
81
+
82
+ The AS3 Socket class doesn't implement this mechanism, which renders it useless for the scenarios where the user trying to open a socket is behind a proxy.
83
+
84
+ The class RFC2817Socket (by Christian Cantrell) effectively lets us implement this, as long as the proxy settings are known and provided by the interface that instantiates the WebSocket. As such, if you want to support proxied conncetions, you'll have to supply this information to the WebSocket constructor when Flash is being used. One way to go about it would be to ask the user for proxy settings information if the initial connection fails.
85
+
86
+
87
+ * How to host HTML file and SWF file in different domains
88
+
89
+ By default, HTML file and SWF file must be in the same domain. You can follow steps below to allow hosting them in different domain.
90
+
91
+ WARNING: If you use the method below, HTML files in ANY domains can send arbitrary TCP data to your WebSocket server, regardless of configuration in Flash socket policy file. Arbitrary TCP data means that they can even fake request headers including Origin and Cookie.
92
+
93
+ - Unzip WebSocketMainInsecure.zip to extract WebSocketMainInsecure.swf.
94
+ - Put WebSocketMainInsecure.swf on your server, instead of WebSocketMain.swf.
95
+ - In JavaScript, set WEB_SOCKET_SWF_LOCATION to URL of your WebSocketMainInsecure.swf.
96
+
97
+
98
+ * How to build WebSocketMain.swf
99
+
100
+ Install Flex 4 SDK:
101
+ http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4
102
+
103
+ $ cd flash-src
104
+ $ ./build.sh
105
+
106
+
107
+ * License
108
+
109
+ New BSD License.
@@ -0,0 +1,4 @@
1
+ /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
2
+ is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
3
+ */
4
+ var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
@@ -0,0 +1,391 @@
1
+ // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
2
+ // License: New BSD License
3
+ // Reference: http://dev.w3.org/html5/websockets/
4
+ // Reference: http://tools.ietf.org/html/rfc6455
5
+
6
+ (function() {
7
+
8
+ if (window.WEB_SOCKET_FORCE_FLASH) {
9
+ // Keeps going.
10
+ } else if (window.WebSocket) {
11
+ return;
12
+ } else if (window.MozWebSocket) {
13
+ // Firefox.
14
+ window.WebSocket = MozWebSocket;
15
+ return;
16
+ }
17
+
18
+ var logger;
19
+ if (window.WEB_SOCKET_LOGGER) {
20
+ logger = WEB_SOCKET_LOGGER;
21
+ } else if (window.console && window.console.log && window.console.error) {
22
+ // In some environment, console is defined but console.log or console.error is missing.
23
+ logger = window.console;
24
+ } else {
25
+ logger = {log: function(){ }, error: function(){ }};
26
+ }
27
+
28
+ // swfobject.hasFlashPlayerVersion("10.0.0") doesn't work with Gnash.
29
+ if (swfobject.getFlashPlayerVersion().major < 10) {
30
+ logger.error("Flash Player >= 10.0.0 is required.");
31
+ return;
32
+ }
33
+ if (location.protocol == "file:") {
34
+ logger.error(
35
+ "WARNING: web-socket-js doesn't work in file:///... URL " +
36
+ "unless you set Flash Security Settings properly. " +
37
+ "Open the page via Web server i.e. http://...");
38
+ }
39
+
40
+ /**
41
+ * Our own implementation of WebSocket class using Flash.
42
+ * @param {string} url
43
+ * @param {array or string} protocols
44
+ * @param {string} proxyHost
45
+ * @param {int} proxyPort
46
+ * @param {string} headers
47
+ */
48
+ window.WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
49
+ var self = this;
50
+ self.__id = WebSocket.__nextId++;
51
+ WebSocket.__instances[self.__id] = self;
52
+ self.readyState = WebSocket.CONNECTING;
53
+ self.bufferedAmount = 0;
54
+ self.__events = {};
55
+ if (!protocols) {
56
+ protocols = [];
57
+ } else if (typeof protocols == "string") {
58
+ protocols = [protocols];
59
+ }
60
+ // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
61
+ // Otherwise, when onopen fires immediately, onopen is called before it is set.
62
+ self.__createTask = setTimeout(function() {
63
+ WebSocket.__addTask(function() {
64
+ self.__createTask = null;
65
+ WebSocket.__flash.create(
66
+ self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
67
+ });
68
+ }, 0);
69
+ };
70
+
71
+ /**
72
+ * Send data to the web socket.
73
+ * @param {string} data The data to send to the socket.
74
+ * @return {boolean} True for success, false for failure.
75
+ */
76
+ WebSocket.prototype.send = function(data) {
77
+ if (this.readyState == WebSocket.CONNECTING) {
78
+ throw "INVALID_STATE_ERR: Web Socket connection has not been established";
79
+ }
80
+ // We use encodeURIComponent() here, because FABridge doesn't work if
81
+ // the argument includes some characters. We don't use escape() here
82
+ // because of this:
83
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
84
+ // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
85
+ // preserve all Unicode characters either e.g. "\uffff" in Firefox.
86
+ // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
87
+ // additional testing.
88
+ var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
89
+ if (result < 0) { // success
90
+ return true;
91
+ } else {
92
+ this.bufferedAmount += result;
93
+ return false;
94
+ }
95
+ };
96
+
97
+ /**
98
+ * Close this web socket gracefully.
99
+ */
100
+ WebSocket.prototype.close = function() {
101
+ if (this.__createTask) {
102
+ clearTimeout(this.__createTask);
103
+ this.__createTask = null;
104
+ this.readyState = WebSocket.CLOSED;
105
+ return;
106
+ }
107
+ if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
108
+ return;
109
+ }
110
+ this.readyState = WebSocket.CLOSING;
111
+ WebSocket.__flash.close(this.__id);
112
+ };
113
+
114
+ /**
115
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
116
+ *
117
+ * @param {string} type
118
+ * @param {function} listener
119
+ * @param {boolean} useCapture
120
+ * @return void
121
+ */
122
+ WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
123
+ if (!(type in this.__events)) {
124
+ this.__events[type] = [];
125
+ }
126
+ this.__events[type].push(listener);
127
+ };
128
+
129
+ /**
130
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
131
+ *
132
+ * @param {string} type
133
+ * @param {function} listener
134
+ * @param {boolean} useCapture
135
+ * @return void
136
+ */
137
+ WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
138
+ if (!(type in this.__events)) return;
139
+ var events = this.__events[type];
140
+ for (var i = events.length - 1; i >= 0; --i) {
141
+ if (events[i] === listener) {
142
+ events.splice(i, 1);
143
+ break;
144
+ }
145
+ }
146
+ };
147
+
148
+ /**
149
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
150
+ *
151
+ * @param {Event} event
152
+ * @return void
153
+ */
154
+ WebSocket.prototype.dispatchEvent = function(event) {
155
+ var events = this.__events[event.type] || [];
156
+ for (var i = 0; i < events.length; ++i) {
157
+ events[i](event);
158
+ }
159
+ var handler = this["on" + event.type];
160
+ if (handler) handler.apply(this, [event]);
161
+ };
162
+
163
+ /**
164
+ * Handles an event from Flash.
165
+ * @param {Object} flashEvent
166
+ */
167
+ WebSocket.prototype.__handleEvent = function(flashEvent) {
168
+
169
+ if ("readyState" in flashEvent) {
170
+ this.readyState = flashEvent.readyState;
171
+ }
172
+ if ("protocol" in flashEvent) {
173
+ this.protocol = flashEvent.protocol;
174
+ }
175
+
176
+ var jsEvent;
177
+ if (flashEvent.type == "open" || flashEvent.type == "error") {
178
+ jsEvent = this.__createSimpleEvent(flashEvent.type);
179
+ } else if (flashEvent.type == "close") {
180
+ jsEvent = this.__createSimpleEvent("close");
181
+ jsEvent.wasClean = flashEvent.wasClean ? true : false;
182
+ jsEvent.code = flashEvent.code;
183
+ jsEvent.reason = flashEvent.reason;
184
+ } else if (flashEvent.type == "message") {
185
+ var data = decodeURIComponent(flashEvent.message);
186
+ jsEvent = this.__createMessageEvent("message", data);
187
+ } else {
188
+ throw "unknown event type: " + flashEvent.type;
189
+ }
190
+
191
+ this.dispatchEvent(jsEvent);
192
+
193
+ };
194
+
195
+ WebSocket.prototype.__createSimpleEvent = function(type) {
196
+ if (document.createEvent && window.Event) {
197
+ var event = document.createEvent("Event");
198
+ event.initEvent(type, false, false);
199
+ return event;
200
+ } else {
201
+ return {type: type, bubbles: false, cancelable: false};
202
+ }
203
+ };
204
+
205
+ WebSocket.prototype.__createMessageEvent = function(type, data) {
206
+ if (document.createEvent && window.MessageEvent && !window.opera) {
207
+ var event = document.createEvent("MessageEvent");
208
+ event.initMessageEvent("message", false, false, data, null, null, window, null);
209
+ return event;
210
+ } else {
211
+ // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
212
+ return {type: type, data: data, bubbles: false, cancelable: false};
213
+ }
214
+ };
215
+
216
+ /**
217
+ * Define the WebSocket readyState enumeration.
218
+ */
219
+ WebSocket.CONNECTING = 0;
220
+ WebSocket.OPEN = 1;
221
+ WebSocket.CLOSING = 2;
222
+ WebSocket.CLOSED = 3;
223
+
224
+ // Field to check implementation of WebSocket.
225
+ WebSocket.__isFlashImplementation = true;
226
+ WebSocket.__initialized = false;
227
+ WebSocket.__flash = null;
228
+ WebSocket.__instances = {};
229
+ WebSocket.__tasks = [];
230
+ WebSocket.__nextId = 0;
231
+
232
+ /**
233
+ * Load a new flash security policy file.
234
+ * @param {string} url
235
+ */
236
+ WebSocket.loadFlashPolicyFile = function(url){
237
+ WebSocket.__addTask(function() {
238
+ WebSocket.__flash.loadManualPolicyFile(url);
239
+ });
240
+ };
241
+
242
+ /**
243
+ * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
244
+ */
245
+ WebSocket.__initialize = function() {
246
+
247
+ if (WebSocket.__initialized) return;
248
+ WebSocket.__initialized = true;
249
+
250
+ if (WebSocket.__swfLocation) {
251
+ // For backword compatibility.
252
+ window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
253
+ }
254
+ if (!window.WEB_SOCKET_SWF_LOCATION) {
255
+ logger.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
256
+ return;
257
+ }
258
+ if (!window.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR &&
259
+ !WEB_SOCKET_SWF_LOCATION.match(/(^|\/)WebSocketMainInsecure\.swf(\?.*)?$/) &&
260
+ WEB_SOCKET_SWF_LOCATION.match(/^\w+:\/\/([^\/]+)/)) {
261
+ var swfHost = RegExp.$1;
262
+ if (location.host != swfHost) {
263
+ logger.error(
264
+ "[WebSocket] You must host HTML and WebSocketMain.swf in the same host " +
265
+ "('" + location.host + "' != '" + swfHost + "'). " +
266
+ "See also 'How to host HTML file and SWF file in different domains' section " +
267
+ "in README.md. If you use WebSocketMainInsecure.swf, you can suppress this message " +
268
+ "by WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;");
269
+ }
270
+ }
271
+ var container = document.createElement("div");
272
+ container.id = "webSocketContainer";
273
+ // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
274
+ // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
275
+ // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
276
+ // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
277
+ // the best we can do as far as we know now.
278
+ container.style.position = "absolute";
279
+ if (WebSocket.__isFlashLite()) {
280
+ container.style.left = "0px";
281
+ container.style.top = "0px";
282
+ } else {
283
+ container.style.left = "-100px";
284
+ container.style.top = "-100px";
285
+ }
286
+ var holder = document.createElement("div");
287
+ holder.id = "webSocketFlash";
288
+ container.appendChild(holder);
289
+ document.body.appendChild(container);
290
+ // See this article for hasPriority:
291
+ // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
292
+ swfobject.embedSWF(
293
+ WEB_SOCKET_SWF_LOCATION,
294
+ "webSocketFlash",
295
+ "1" /* width */,
296
+ "1" /* height */,
297
+ "10.0.0" /* SWF version */,
298
+ null,
299
+ null,
300
+ {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
301
+ null,
302
+ function(e) {
303
+ if (!e.success) {
304
+ logger.error("[WebSocket] swfobject.embedSWF failed");
305
+ }
306
+ }
307
+ );
308
+
309
+ };
310
+
311
+ /**
312
+ * Called by Flash to notify JS that it's fully loaded and ready
313
+ * for communication.
314
+ */
315
+ WebSocket.__onFlashInitialized = function() {
316
+ // We need to set a timeout here to avoid round-trip calls
317
+ // to flash during the initialization process.
318
+ setTimeout(function() {
319
+ WebSocket.__flash = document.getElementById("webSocketFlash");
320
+ WebSocket.__flash.setCallerUrl(location.href);
321
+ WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
322
+ for (var i = 0; i < WebSocket.__tasks.length; ++i) {
323
+ WebSocket.__tasks[i]();
324
+ }
325
+ WebSocket.__tasks = [];
326
+ }, 0);
327
+ };
328
+
329
+ /**
330
+ * Called by Flash to notify WebSockets events are fired.
331
+ */
332
+ WebSocket.__onFlashEvent = function() {
333
+ setTimeout(function() {
334
+ try {
335
+ // Gets events using receiveEvents() instead of getting it from event object
336
+ // of Flash event. This is to make sure to keep message order.
337
+ // It seems sometimes Flash events don't arrive in the same order as they are sent.
338
+ var events = WebSocket.__flash.receiveEvents();
339
+ for (var i = 0; i < events.length; ++i) {
340
+ WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
341
+ }
342
+ } catch (e) {
343
+ logger.error(e);
344
+ }
345
+ }, 0);
346
+ return true;
347
+ };
348
+
349
+ // Called by Flash.
350
+ WebSocket.__log = function(message) {
351
+ logger.log(decodeURIComponent(message));
352
+ };
353
+
354
+ // Called by Flash.
355
+ WebSocket.__error = function(message) {
356
+ logger.error(decodeURIComponent(message));
357
+ };
358
+
359
+ WebSocket.__addTask = function(task) {
360
+ if (WebSocket.__flash) {
361
+ task();
362
+ } else {
363
+ WebSocket.__tasks.push(task);
364
+ }
365
+ };
366
+
367
+ /**
368
+ * Test if the browser is running flash lite.
369
+ * @return {boolean} True if flash lite is running, false otherwise.
370
+ */
371
+ WebSocket.__isFlashLite = function() {
372
+ if (!window.navigator || !window.navigator.mimeTypes) {
373
+ return false;
374
+ }
375
+ var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
376
+ if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
377
+ return false;
378
+ }
379
+ return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
380
+ };
381
+
382
+ if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
383
+ // NOTE:
384
+ // This fires immediately if web_socket.js is dynamically loaded after
385
+ // the document is loaded.
386
+ swfobject.addDomLoadEvent(function() {
387
+ WebSocket.__initialize();
388
+ });
389
+ }
390
+
391
+ })();