Debian Codegraph @

gavo/resources/web/js/samp.js

raw
1 // samp
2 // ----
3 // Provides capabilities for using the SAMP Web Profile from JavaScript.
4 // Exported tokens are in the samp.* namespace.
5 // Inline documentation is somewhat patchy (partly because I don't know
6 // what javascript documentation is supposed to look like) - it is
7 // suggested to use it conjunction with the provided examples,
8 // currently visible at http://astrojs.github.com/sampjs/
9 // (gh-pages branch of github sources).
10
11 // LICENCE
12 // =======
13 // samp.js - A Javascript module for connection to VO SAMP hubs
14 // Written in 2013 by Mark Taylor
15 //
16 // This file is distributed under the CC0 Public Domain Dedication,
17 // <http://creativecommons.org/publicdomain/zero/1.0/>.
18 // To the extent possible under law, the author(s) have dedicated all
19 // copyright and related and neighboring rights to this software to the
20 // public domain worldwide. This software is distributed without any
21 // warranty.
22
23 var samp = (function() {
24
25 // Constants defining well-known location of SAMP Web Profile hub etc.
26 var WEBSAMP_PORT = 21012;
27 var WEBSAMP_PATH = "/";
28 var WEBSAMP_PREFIX = "samp.webhub.";
29 var WEBSAMP_CLIENT_PREFIX = "";
30
31 // Tokens representing permissible types in a SAMP object (e.g. a message)
32 var TYPE_STRING = "string";
33 var TYPE_LIST = "list";
34 var TYPE_MAP = "map";
35
36 var heir = function(proto) {
37 function F() {};
38 F.prototype = proto;
39 return new F();
40 };
41
42 // Utility functions for navigating DOM etc.
43 // -----------------------------------------
44
45 var getSampType = function(obj) {
46 if (typeof obj === "string") {
47 return TYPE_STRING;
48 }
49 else if (obj instanceof Array) {
50 return TYPE_LIST;
51 }
52 else if (obj instanceof Object && obj !== null) {
53 return TYPE_MAP;
54 }
55 else {
56 throw new Error("Not legal SAMP object type: " + obj);
57 }
58 };
59 var getChildElements = function(el, childTagName) {
60 var children = el.childNodes;
61 var child;
62 var childEls = [];
63 var i;
64 for (i = 0; i < children.length; i++) {
65 child = children[i];
66 if (child.nodeType === 1) { // Element
67 if (childTagName && (child.tagName !== childTagName)) {
68 throw new Error("Child <" + children[i].tagName + ">"
69 + " of <" + el.tagName + ">"
70 + " is not a <" + childTagName + ">");
71 }
72 childEls.push(child);
73 }
74 }
75 return childEls;
76 };
77 var getSoleChild = function(el, childTagName) {
78 var children = getChildElements(el, childTagName);
79 if (children.length === 1 ) {
80 return children[0];
81 }
82 else {
83 throw new Error("No sole child of <" + el.tagName + ">");
84 }
85 };
86 var getTextContent = function(el) {
87 var txt = "";
88 var i;
89 var child;
90 for (i = 0; i < el.childNodes.length; i++ ) {
91 child = el.childNodes[i];
92 if (child.nodeType === 1) { // Element
93 throw new Error("Element found in text content");
94 }
95 else if (child.nodeType === 3 || // Text
96 child.nodeType === 4 ) { // CDATASection
97 txt += child.nodeValue;
98 }
99 }
100 return txt;
101 };
102 var stringify = function(obj) {
103 return typeof JSON === "undefined" ? "..." : JSON.stringify(obj);
104 };
105
106 // XmlRpc class:
107 // Utilities for packing and unpacking XML-RPC messages.
108 // See xml-rpc.com.
109
110 var XmlRpc = {};
111
112 // Takes text and turns it into something suitable for use as the content
113 // of an XML-RPC string - special characters are escaped.
114 XmlRpc.escapeXml = function(s) {
115 return s.replace(/&/g, "&amp;")
116 .replace(/</g, "&lt;")
117 .replace(/>/g, "&gt;");
118 };
119
120 // Asserts that the elements of paramList match the types given by typeList.
121 // TypeList must be an array containing only TYPE_STRING, TYPE_LIST
122 // and TYPE_MAP objects in some combination. paramList must be the
123 // same length.
124 // In case of mismatch an error is thrown.
125 XmlRpc.checkParams = function(paramList, typeList) {
126 var i;
127 for (i = 0; i < typeList.length; i++) {
128 if (typeList[i] !== TYPE_STRING &&
129 typeList[i] !== TYPE_LIST &&
130 typeList[i] !== TYPE_MAP) {
131 throw new Error("Unknown type " + typeList[i]
132 + " in check list");
133 }
134 }
135 var npar = paramList.length;
136 var actualTypeList = [];
137 var ok = true;
138 for (i = 0; i < npar; i++) {
139 actualTypeList.push(getSampType(paramList[i]));
140 }
141 ok = ok && (typeList.length === npar);
142 for (i = 0; ok && i < npar; i++ ) {
143 ok = ok && typeList[i] === actualTypeList[i];
144 }
145 if (!ok) {
146 throw new Error("Param type list mismatch: "
147 + "[" + typeList + "] != "
148 + "[" + actualTypeList + "]");
149 }
150 };
151
152 // Turns a SAMP object (structure of strings, lists, maps) into an
153 // XML string suitable for use with XML-RPC.
154 XmlRpc.valueToXml = function v2x(obj, prefix) {
155 prefix = prefix || "";
156 var a;
157 var i;
158 var result;
159 var type = getSampType(obj);
160 if (type === TYPE_STRING) {
161 return prefix
162 + "<value><string>"
163 + XmlRpc.escapeXml(obj)
164 + "</string></value>";
165 }
166 else if (type === TYPE_LIST) {
167 result = [];
168 result.push(prefix + "<value>",
169 prefix + " <array>",
170 prefix + " <data>");
171 for (i = 0; i < obj.length; i++) {
172 result.push(v2x(obj[i], prefix + " "));
173 }
174 result.push(prefix + " </data>",
175 prefix + " </array>",
176 prefix + "</value>");
177
178 return result.join("\n");
179 }
180 else if (type === TYPE_MAP) {
181 result = [];
182 result.push(prefix + "<value>");
183 result.push(prefix + " <struct>");
184 for (i in obj) {
185 result.push(prefix + " <member>");
186 result.push(prefix + " <name>"
187 + XmlRpc.escapeXml(i)
188 + "</name>");
189 result.push(v2x(obj[i], prefix + " "));
190 result.push(prefix + " </member>");
191 }
192 result.push(prefix + " </struct>");
193 result.push(prefix + "</value>");
194 return result.join("\n");
195 }
196 else {
197 throw new Error("bad type"); // shouldn't get here
198 }
199 };
200
201 // Turns an XML string from and XML-RPC message into a SAMP object
202 // (structure of strings, lists, maps).
203 XmlRpc.xmlToValue = function x2v(valueEl, allowInt) {
204 var childEls = getChildElements(valueEl);
205 var i;
206 var j;
207 var txt;
208 var node;
209 var childEl;
210 var elName;
211 if (childEls.length === 0) {
212 return getTextContent(valueEl);
213 }
214 else if (childEls.length === 1) {
215 childEl = childEls[0];
216 elName = childEl.tagName;
217 if (elName === "string") {
218 return getTextContent(childEl);
219 }
220 else if (elName === "array") {
221 var valueEls =
222 getChildElements(getSoleChild(childEl, "data"), "value");
223 var list = [];
224 for (i = 0; i < valueEls.length; i++) {
225 list.push(x2v(valueEls[i], allowInt));
226 }
227 return list;
228 }
229 else if (elName === "struct") {
230 var memberEls = getChildElements(childEl, "member");
231 var map = {};
232 var s_name;
233 var s_value;
234 var jc;
235 for (i = 0; i < memberEls.length; i++) {
236 s_name = undefined;
237 s_value = undefined;
238 for (j = 0; j < memberEls[i].childNodes.length; j++) {
239 jc = memberEls[i].childNodes[j];
240 if (jc.nodeType == 1) {
241 if (jc.tagName === "name") {
242 s_name = getTextContent(jc);
243 }
244 else if (jc.tagName === "value") {
245 s_value = x2v(jc, allowInt);
246 }
247 }
248 }
249 if (s_name !== undefined && s_value !== undefined) {
250 map[s_name] = s_value;
251 }
252 else {
253 throw new Error("No <name> and/or <value> "
254 + "in <member>?");
255 }
256 }
257 return map;
258 }
259 else if (allowInt && (elName === "int" || elName === "i4")) {
260 return getTextContent(childEl);
261 }
262 else {
263 throw new Error("Non SAMP-friendly value content: "
264 + "<" + elName + ">");
265 }
266 }
267 else {
268 throw new Error("Bad XML-RPC <value> content - multiple elements");
269 }
270 };
271
272 // Turns the content of an XML-RPC <params> element into an array of
273 // SAMP objects.
274 XmlRpc.decodeParams = function(paramsEl) {
275 var paramEls = getChildElements(paramsEl, "param");
276 var i;
277 var results = [];
278 for (i = 0; i < paramEls.length; i++) {
279 results.push(XmlRpc.xmlToValue(getSoleChild(paramEls[i], "value")));
280 }
281 return results;
282 };
283
284 // Turns the content of an XML-RPC <fault> element into an XmlRpc.Fault
285 // object.
286 XmlRpc.decodeFault = function(faultEl) {
287 var faultObj = XmlRpc.xmlToValue(getSoleChild(faultEl, "value"), true);
288 return new XmlRpc.Fault(faultObj.faultString, faultObj.faultCode);
289 };
290
291 // Turns an XML-RPC response element (should be <methodResponse>) into
292 // either a SAMP response object or an XmlRpc.Fault object.
293 // Note that a fault response does not throw an error, so check for
294 // the type of the result if you want to know whether a fault occurred.
295 // An error will however be thrown if the supplied XML does not
296 // correspond to a legal XML-RPC response.
297 XmlRpc.decodeResponse = function(xml) {
298 var mrEl = xml.documentElement;
299 if (mrEl.tagName !== "methodResponse") {
300 throw new Error("Response element is not <methodResponse>");
301 }
302 var contentEl = getSoleChild(mrEl);
303 if (contentEl.tagName === "fault") {
304 return XmlRpc.decodeFault(contentEl);
305 }
306 else if (contentEl.tagName === "params") {
307 return XmlRpc.decodeParams(contentEl)[0];
308 }
309 else {
310 throw new Error("Bad XML-RPC response - unknown element"
311 + " <" + contentEl.tagName + ">");
312 }
313 };
314
315 // XmlRpc.Fault class:
316 // Represents an XML-RPC Fault response.
317 XmlRpc.Fault = function(faultString, faultCode) {
318 this.faultString = faultString;
319 this.faultCode = faultCode;
320 };
321 XmlRpc.Fault.prototype.toString = function() {
322 return "XML-RPC Fault (" + this.faultCode + "): " + this.faultString;
323 };
324
325 // XmlRpcRequest class:
326 // Represents an call which can be sent to an XML-RPC server.
327 var XmlRpcRequest = function(methodName, params) {
328 this.methodName = methodName;
329 this.params = params || [];
330 }
331 XmlRpcRequest.prototype.toString = function() {
332 return this.methodName + "(" + stringify(this.params) + ")";
333 };
334 XmlRpcRequest.prototype.addParam = function(param) {
335 this.params.push(param);
336 return this;
337 };
338 XmlRpcRequest.prototype.addParams = function(params) {
339 var i;
340 for (i = 0; i < params.length; i++) {
341 this.params.push(params[i]);
342 }
343 return this;
344 };
345 XmlRpcRequest.prototype.checkParams = function(typeList) {
346 XmlRpc.checkParams(this.params, typeList);
347 };
348 XmlRpcRequest.prototype.toXml = function() {
349 var lines = [];
350 lines.push(
351 "<?xml version='1.0'?>",
352 "<methodCall>",
353 " <methodName>" + this.methodName + "</methodName>",
354 " <params>");
355 for (var i = 0; i < this.params.length; i++) {
356 lines.push(" <param>",
357 XmlRpc.valueToXml(this.params[i], " "),
358 " </param>");
359 }
360 lines.push(
361 " </params>",
362 "</methodCall>");
363 return lines.join("\n");
364 };
365
366 // XmlRpcClient class:
367 // Object capable of sending XML-RPC calls to an XML-RPC server.
368 // That server will typically reside on the host on which the
369 // javascript is running; it is not likely to reside on the host
370 // which served the javascript. That means that sandboxing restrictions
371 // will be in effect. Much of the work done here is therefore to
372 // do the client-side work required to potentially escape the sandbox.
373 // The endpoint parameter, if supplied, is the URL of the XML-RPC server.
374 // If absent, the default SAMP Web Profile server is used.
375 var XmlRpcClient = function(endpoint) {
376 this.endpoint = endpoint ||
377 "http://localhost:" + WEBSAMP_PORT + WEBSAMP_PATH;
378 };
379
380 // Creates an XHR facade - an object that presents an interface
381 // resembling that of an XMLHttpRequest Level 2.
382 // This facade may be based on an actual XMLHttpRequest Level 2 object
383 // (on browsers that support it), or it may fake one using other
384 // available technology.
385 //
386 // The created facade in any case presents the following interface:
387 //
388 // open(method, url)
389 // send(body)
390 // abort()
391 // setContentType()
392 // responseText
393 // responseXML
394 // onload
395 // onerror(err) - includes timeout; abort is ignored
396 //
397 // See the documentation at http://www.w3.org/TR/XMLHttpRequest/
398 // for semantics.
399 //
400 // XMLHttpRequest Level 2 supports Cross-Origin Resource Sharing (CORS)
401 // which makes sandbox evasion possible. Faked XHRL2s returned by
402 // this method may use CORS or some other technology to evade the
403 // sandbox. The SAMP hub itself may selectively allow some of these
404 // technologies and not others, according to configuration.
405 XmlRpcClient.createXHR = function() {
406
407 // Creates an XHR facade based on a genuine XMLHttpRequest Level 2.
408 var XhrL2 = function(xhr) {
409 this.xhr = xhr;
410 xhr.onreadystatechange = (function(l2) {
411 return function() {
412 if (xhr.readyState !== 4) {
413 return;
414 }
415 else if (!l2.completed) {
416 if (+xhr.status === 200) {
417 l2.completed = true;
418 l2.responseText = xhr.responseText;
419 l2.responseXML = xhr.responseXML;
420 if (l2.onload) {
421 l2.onload();
422 }
423 }
424 }
425 };
426 })(this);
427 xhr.onerror = (function(l2) {
428 return function(event) {
429 if (!l2.completed) {
430 l2.completed = true;
431 if (l2.onerror) {
432 if (event) {
433 event.toString = function() {return "No hub?";};
434 }
435 else {
436 event = "No hub?";
437 }
438 l2.onerror(event);
439 }
440 }
441 };
442 })(this);
443 xhr.ontimeout = (function(l2) {
444 return function(event) {
445 if (!l2.completed) {
446 l2.completed = true;
447 if (l2.onerror) {
448 l2.onerror("timeout");
449 }
450 }
451 };
452 })(this);
453 };
454 XhrL2.prototype.open = function(method, url) {
455 this.xhr.open(method, url);
456 };
457 XhrL2.prototype.send = function(body) {
458 this.xhr.send(body);
459 };
460 XhrL2.prototype.abort = function() {
461 this.xhr.abort();
462 }
463 XhrL2.prototype.setContentType = function(mimeType) {
464 if ("setRequestHeader" in this.xhr) {
465 this.xhr.setRequestHeader("Content-Type", mimeType);
466 }
467 }
468
469 // Creates an XHR facade based on an XDomainRequest (IE8+ only).
470 var XdrL2 = function(xdr) {
471 this.xdr = xdr;
472 xdr.onload = (function(l2) {
473 return function() {
474 var e;
475 l2.responseText = xdr.responseText;
476 if (xdr.contentType === "text/xml" ||
477 xdr.contentType === "application/xml" ||
478 /\/x-/.test(xdr.contentType)) {
479 try {
480 var xdoc = new ActiveXObject("Microsoft.XMLDOM");
481 xdoc.loadXML(xdr.responseText);
482 l2.responseXML = xdoc;
483 }
484 catch (e) {
485 l2.responseXML = e;
486 }
487 }
488 if (l2.onload) {
489 l2.onload();
490 }
491 };
492 })(this);
493 xdr.onerror = (function(l2) {
494 return function(event) {
495 if (l2.onerror) {
496 l2.onerror(event);
497 }
498 };
499 })(this);
500 xdr.ontimeout = (function(l2) {
501 return function(event) {
502 if (l2.onerror) {
503 l2.onerror(event);
504 }
505 };
506 })(this);
507 };
508 XdrL2.prototype.open = function(method, url) {
509 this.xdr.open(method, url);
510 };
511 XdrL2.prototype.send = function(body) {
512 this.xdr.send(body);
513 };
514 XdrL2.prototype.abort = function() {
515 this.xdr.abort();
516 };
517 XdrL2.prototype.setContentType = function(mimeType) {
518 // can't do it.
519 };
520
521 // Creates an XHR Facade based on available XMLHttpRequest-type
522 // capabilibities.
523 // If an actual XMLHttpRequest Level 2 is available, use that.
524 if (typeof XMLHttpRequest !== "undefined") {
525 var xhr = new XMLHttpRequest();
526 if ("withCredentials" in xhr) {
527 return new XhrL2(xhr);
528 }
529 }
530
531 // Else if an XDomainRequest is available, use that.
532 if (typeof XDomainRequest !== "undefined") {
533 return new XdrL2(new XDomainRequest());
534 }
535
536 // Else fake an XMLHttpRequest using Flash/flXHR, if available
537 // and use that.
538 if (typeof flensed.flXHR !== "undefined") {
539 return new XhrL2(new flensed.flXHR({instancePooling: true}));
540 }
541
542 // No luck.
543 throw new Error("no cross-origin mechanism available");
544 };
545
546 // Executes a request by passing it to the XML-RPC server.
547 // On success, the result is passed to the resultHandler.
548 // On failure, the errHandler is called with one of two possible
549 // arguments: an XmlRpc.Fault object, or an Error object.
550 XmlRpcClient.prototype.execute = function(req, resultHandler, errHandler) {
551 (function(xClient) {
552 var xhr;
553 var e;
554 try {
555 xhr = XmlRpcClient.createXHR();
556 xhr.open("POST", xClient.endpoint);
557 xhr.setContentType("text/xml");
558 }
559 catch (e) {
560 errHandler(e);
561 throw e;
562 }
563 xhr.onload = function() {
564 var xml = xhr.responseXML;
565 var result;
566 var e;
567 if (xml) {
568 try {
569 result = XmlRpc.decodeResponse(xml);
570 }
571 catch (e) {
572 if (errHandler) {
573 errHandler(e);
574 }
575 return;
576 }
577 }
578 else {
579 if (errHandler) {
580 errHandler("no XML response");
581 }
582 return;
583 }
584 if (result instanceof XmlRpc.Fault) {
585 if (errHandler) {
586 errHandler(result);
587 }
588 }
589 else {
590 if (resultHandler) {
591 resultHandler(result);
592 }
593 }
594 };
595 xhr.onerror = function(event) {
596 if (event) {
597 event.toString = function() {return "No hub?";}
598 }
599 else {
600 event = "No hub";
601 }
602 if (errHandler) {
603 errHandler(event);
604 }
605 };
606 xhr.send(req.toXml());
607 return xhr;
608 })(this);
609 };
610
611 // Message class:
612 // Aggregates an MType string and a params map.
613 var Message = function(mtype, params) {
614 this["samp.mtype"] = mtype;
615 this["samp.params"] = params;
616 };
617
618 // Connection class:
619 // this is what clients use to communicate with the hub.
620 //
621 // All the methods from the Hub Abstract API as described in the
622 // SAMP standard are available as methods of a Connection object.
623 // The initial private-key argument required by the Web Profile is
624 // handled internally by this object - you do not need to supply it
625 // when calling one of the methods.
626 //
627 // All these calls have the same form:
628 //
629 // connection.method([method-args], resultHandler, errorHandler)
630 //
631 // the first argument is an array of the arguments (as per the SAMP
632 // abstract hub API), the second argument is a function which is
633 // called on successful completion with the result of the SAMP call
634 // as its argument, and the third argument is a function which is
635 // called on unsuccessful completion with an error object as its
636 // argument. The resultHandler and errorHandler arguments are optional.
637 //
638 // So for instance if you have a Connection object conn,
639 // you can send a notify message to all other clients by doing, e.g.:
640 //
641 // conn.notifyAll([new samp.Message(mtype, params)])
642 //
643 // Connection has other methods as well as the hub API ones
644 // as documented below.
645 var Connection = function(regInfo) {
646 this.regInfo = regInfo;
647 this.privateKey = regInfo["samp.private-key"];
648 if (! typeof(this.privateKey) === "string") {
649 throw new Error("Bad registration object");
650 }
651 this.xClient = new XmlRpcClient();
652 };
653 (function() {
654 var connMethods = {
655 call: [TYPE_STRING, TYPE_STRING, TYPE_MAP],
656 callAll: [TYPE_STRING, TYPE_MAP],
657 callAndWait: [TYPE_STRING, TYPE_MAP, TYPE_STRING],
658 declareMetadata: [TYPE_MAP],
659 declareSubscriptions: [TYPE_MAP],
660 getMetadata: [TYPE_STRING],
661 getRegisteredClients: [],
662 getSubscribedClients: [TYPE_STRING],
663 getSubscriptions: [TYPE_STRING],
664 notify: [TYPE_STRING, TYPE_MAP],
665 notifyAll: [TYPE_MAP],
666 ping: [],
667 reply: [TYPE_STRING, TYPE_MAP]
668 };
669 var fn;
670 var types;
671 for (fn in connMethods) {
672 (function(fname, types) {
673 // errHandler may be passed an XmlRpc.Fault or a thrown Error.
674 Connection.prototype[fname] =
675 function(sampArgs, resultHandler, errHandler) {
676 var closer =
677 (function(c) {return function() {c.close()}})(this);
678 errHandler = errHandler || closer
679 XmlRpc.checkParams(sampArgs, types);
680 var request = new XmlRpcRequest(WEBSAMP_PREFIX + fname);
681 request.addParam(this.privateKey);
682 request.addParams(sampArgs);
683 return this.xClient.
684 execute(request, resultHandler, errHandler);
685 };
686 })(fn, connMethods[fn]);
687 }
688 })();
689 Connection.prototype.unregister = function() {
690 var e;
691 if (this.callbackRequest) {
692 try {
693 this.callbackRequest.abort();
694 }
695 catch (e) {
696 }
697 }
698 var request = new XmlRpcRequest(WEBSAMP_PREFIX + "unregister");
699 request.addParam(this.privateKey);
700 try {
701 this.xClient.execute(request);
702 }
703 catch (e) {
704 // log unregister failed
705 }
706 delete this.regInfo;
707 delete this.privateKey;
708 };
709
710 // Closes this connection. It unregisters from the hub if still
711 // registered, but may harmlessly be called multiple times.
712 Connection.prototype.close = function() {
713 var e;
714 if (this.closed) {
715 return;
716 }
717 this.closed = true;
718 try {
719 if (this.regInfo) {
720 this.unregister();
721 }
722 }
723 catch (e) {
724 }
725 if (this.onclose) {
726 oc = this.onclose;
727 delete this.onclose;
728 try {
729 oc();
730 }
731 catch (e) {
732 }
733 }
734 };
735
736 // Arranges for this connection to receive callbacks.
737 //
738 // The callableClient argument must be an object implementing the
739 // SAMP callable client API, i.e. it must have the following methods:
740 //
741 // receiveNotification(string sender-id, map message)
742 // receiveCall(string sender-id, string msg-id, map message)
743 // receiveResponse(string responder-id, string msg-tag, map response)
744 //
745 // The successHandler argument will be called with no arguments if the
746 // allowCallbacks hub method completes successfully - it is a suitable
747 // hook to use for declaring subscriptions.
748 //
749 // The CallableClient class provides a suitable implementation, see below.
750 Connection.prototype.setCallable = function(callableClient,
751 successHandler) {
752 var e;
753 if (this.callbackRequest) {
754 try {
755 this.callbackRequest.abort();
756 }
757 catch (e) {
758 }
759 finally {
760 delete this.callbackRequest;
761 }
762 }
763 if (!callableClient && !this.regInfo) {
764 return;
765 }
766 var request =
767 new XmlRpcRequest(WEBSAMP_PREFIX + "allowReverseCallbacks");
768 request.addParam(this.privateKey);
769 request.addParam(callableClient ? "1" : "0");
770 var closer = (function(c) {return function() {c.close()}})(this);
771 if (callableClient) {
772 (function(connection) {
773 var invokeCallback = function(callback) {
774 var methodName = callback["samp.methodName"];
775 var methodParams = callback["samp.params"];
776 var handlerFunc = undefined;
777 if (methodName === WEBSAMP_CLIENT_PREFIX
778 + "receiveNotification") {
779 handlerFunc = callableClient.receiveNotification;
780 }
781 else if (methodName === WEBSAMP_CLIENT_PREFIX
782 + "receiveCall") {
783 handlerFunc = callableClient.receiveCall;
784 }
785 else if (methodName === WEBSAMP_CLIENT_PREFIX
786 + "receiveResponse") {
787 handlerFunc = callableClient.receiveResponse;
788 }
789 else {
790 // unknown callback??
791 }
792 if (handlerFunc) {
793 handlerFunc.apply(callableClient, methodParams);
794 }
795 };
796 var startTime;
797 var resultHandler = function(result) {
798 if (getSampType(result) != TYPE_LIST) {
799 errHandler(new Error("pullCallbacks result not List"));
800 return;
801 }
802 var i;
803 var e;
804 for (i = 0; i < result.length; i++) {
805 try {
806 invokeCallback(result[i]);
807 }
808 catch (e) {
809 // log here?
810 }
811 }
812 callWaiter();
813 };
814 var errHandler = function(error) {
815 var elapsed = new Date().getTime() - startTime;
816 if (elapsed < 1000) {
817 connection.close()
818 }
819 else {
820 // probably a timeout
821 callWaiter();
822 }
823 };
824 var callWaiter = function() {
825 if (!connection.regInfo) {
826 return;
827 }
828 var request =
829 new XmlRpcRequest(WEBSAMP_PREFIX + "pullCallbacks");
830 request.addParam(connection.privateKey);
831 request.addParam("600");
832 startTime = new Date().getTime();
833 connection.callbackRequest =
834 connection.xClient.
835 execute(request, resultHandler, errHandler);
836 };
837 var sHandler = function() {
838 callWaiter();
839 successHandler();
840 };
841 connection.xClient.execute(request, sHandler, closer);
842 })(this);
843 }
844 else {
845 this.xClient.execute(request, successHandler, closer);
846 }
847 };
848
849 // Takes a public URL and returns a URL that can be used from within
850 // this javascript context. Some translation may be required, since
851 // a URL sent by an external application may be cross-domain, in which
852 // case browser sandboxing would typically disallow access to it.
853 Connection.prototype.translateUrl = function(url) {
854 var translator = this.regInfo["samp.url-translator"] || "";
855 return translator + url;
856 };
857 Connection.Action = function(actName, actArgs, resultKey) {
858 this.actName = actName;
859 this.actArgs = actArgs;
860 this.resultKey = resultKey;
861 };
862
863 // Suitable implementation for a callable client object which can
864 // be supplied to Connection.setCallable().
865 // Its callHandler and replyHandler members are string->function maps
866 // which can be used to provide handler functions for MTypes and
867 // message tags respectively.
868 //
869 // In more detail:
870 // The callHandler member maps a string representing an MType to
871 // a function with arguments (senderId, message, isCall).
872 // The replyHandler member maps a string representing a message tag to
873 // a function with arguments (responderId, msgTag, response).
874 var CallableClient = function(connection) {
875 this.callHandler = {};
876 this.replyHandler = {};
877 };
878 CallableClient.prototype.init = function(connection) {
879 };
880 CallableClient.prototype.receiveNotification = function(senderId, message) {
881 var mtype = message["samp.mtype"];
882 var handled = false;
883 var e;
884 if (mtype in this.callHandler) {
885 try {
886 this.callHandler[mtype](senderId, message, false);
887 }
888 catch (e) {
889 }
890 handled = true;
891 }
892 return handled;
893 };
894 CallableClient.prototype.receiveCall = function(senderId, msgId, message) {
895 var mtype = message["samp.mtype"];
896 var handled = false;
897 var response;
898 var result;
899 var e;
900 if (mtype in this.callHandler) {
901 try {
902 result = this.callHandler[mtype](senderId, message, true) || {};
903 response = {"samp.status": "samp.ok",
904 "samp.result": result};
905 handled = true;
906 }
907 catch (e) {
908 response = {"samp.status": "samp.error",
909 "samp.error": {"samp.errortxt": e.toString()}};
910 }
911 }
912 else {
913 response = {"samp.status": "samp.warning",
914 "samp.result": {},
915 "samp.error": {"samp.errortxt": "no action"}};
916 }
917 this.connection.reply([msgId, response]);
918 return handled;
919 };
920 CallableClient.prototype.receiveResponse = function(responderId, msgTag,
921 response) {
922 var handled = false;
923 var e;
924 if (msgTag in this.replyHandler) {
925 try {
926 this.replyHandler[msgTag](responderId, msgTag, response);
927 handled = true;
928 }
929 catch (e) {
930 }
931 }
932 return handled;
933 };
934 CallableClient.prototype.calculateSubscriptions = function() {
935 var subs = {};
936 var mt;
937 for (mt in this.callHandler) {
938 subs[mt] = {};
939 }
940 return subs;
941 };
942
943 // ClientTracker is a CallableClient which also provides tracking of
944 // registered clients.
945 //
946 // Its onchange member, if defined, will be called with arguments
947 // (client-id, change-type, associated-data) whenever the list or
948 // characteristics of registered clients has changed.
949 var ClientTracker = function() {
950 var tracker = this;
951 this.ids = {};
952 this.metas = {};
953 this.subs = {};
954 this.replyHandler = {};
955 this.callHandler = {
956 "samp.hub.event.shutdown": function(senderId, message) {
957 tracker.connection.close();
958 },
959 "samp.hub.disconnect": function(senderId, message) {
960 tracker.connection.close();
961 },
962 "samp.hub.event.register": function(senderId, message) {
963 var id = message["samp.params"]["id"];
964 tracker.ids[id] = true;
965 tracker.changed(id, "register", null);
966 },
967 "samp.hub.event.unregister": function(senderId, message) {
968 var id = message["samp.params"]["id"];
969 delete tracker.ids[id];
970 delete tracker.metas[id];
971 delete tracker.subs[id];
972 tracker.changed(id, "unregister", null);
973 },
974 "samp.hub.event.metadata": function(senderId, message) {
975 var id = message["samp.params"]["id"];
976 var meta = message["samp.params"]["metadata"];
977 tracker.metas[id] = meta;
978 tracker.changed(id, "meta", meta);
979 },
980 "samp.hub.event.subscriptions": function(senderId, message) {
981 var id = message["samp.params"]["id"];
982 var subs = message["samp.params"]["subscriptions"];
983 tracker.subs[id] = subs;
984 tracker.changed(id, "subs", subs);
985 }
986 };
987 };
988 ClientTracker.prototype = heir(CallableClient.prototype);
989 ClientTracker.prototype.changed = function(id, type, data) {
990 if (this.onchange) {
991 this.onchange(id, type, data);
992 }
993 };
994 ClientTracker.prototype.init = function(connection) {
995 var tracker = this;
996 this.connection = connection;
997 var retrieveInfo = function(id, type, infoFuncName, infoArray) {
998 connection[infoFuncName]([id], function(info) {
999 infoArray[id] = info;
1000 tracker.changed(id, type, info);
1001 });
1002 };
1003 connection.getRegisteredClients([], function(idlist) {
1004 var i;
1005 var id;
1006 tracker.ids = {};
1007 for (i = 0; i < idlist.length; i++) {
1008 id = idlist[i];
1009 tracker.ids[id] = true;
1010 retrieveInfo(id, "meta", "getMetadata", tracker.metas);
1011 retrieveInfo(id, "subs", "getSubscriptions", tracker.subs);
1012 }
1013 tracker.changed(null, "ids", null);
1014 });
1015 };
1016 ClientTracker.prototype.getName = function(id) {
1017 var meta = this.metas[id];
1018 return (meta && meta["samp.name"]) ? meta["samp.name"] : "[" + id + "]";
1019 };
1020
1021 // Connector class:
1022 // A higher level class which can manage transparent hub
1023 // registration/unregistration and client tracking.
1024 //
1025 // On construction, the name argument is mandatory, and corresponds
1026 // to the samp.name item submitted at registration time.
1027 // The other arguments are optional.
1028 // meta is a metadata map (if absent, no metadata is declared)
1029 // callableClient is a callable client object for receiving callbacks
1030 // (if absent, the client is not callable).
1031 // subs is a subscriptions map (if absent, no subscriptions are declared)
1032 var Connector = function(name, meta, callableClient, subs) {
1033 this.name = name;
1034 this.meta = meta;
1035 this.callableClient = callableClient;
1036 this.subs = subs;
1037 this.regTextNodes = [];
1038 this.whenRegs = [];
1039 this.whenUnregs = [];
1040 this.connection = undefined;
1041 this.onreg = undefined;
1042 this.onunreg = undefined;
1043 };
1044 var setRegText = function(connector, txt) {
1045 var i;
1046 var nodes = connector.regTextNodes;
1047 var node;
1048 for (i = 0; i < nodes.length; i++) {
1049 node = nodes[i];
1050 node.innerHTML = "";
1051 node.appendChild(document.createTextNode(txt));
1052 }
1053 };
1054 Connector.prototype.setConnection = function(conn) {
1055 var connector = this;
1056 var e;
1057 if (this.connection) {
1058 this.connection.close();
1059 if (this.onunreg) {
1060 try {
1061 this.onunreg();
1062 }
1063 catch (e) {
1064 }
1065 }
1066 }
1067 this.connection = conn;
1068 if (conn) {
1069 conn.onclose = function() {
1070 connector.connection = null;
1071 if (connector.onunreg) {
1072 try {
1073 connector.onunreg();
1074 }
1075 catch (e) {
1076 }
1077 }
1078 connector.update();
1079 };
1080 if (this.meta) {
1081 conn.declareMetadata([this.meta]);
1082 }
1083 if (this.callableClient) {
1084 if (this.callableClient.init) {
1085 this.callableClient.init(conn);
1086 }
1087 conn.setCallable(this.callableClient, function() {
1088 conn.declareSubscriptions([connector.subs]);
1089 });
1090 }
1091 if (this.onreg) {
1092 try {
1093 this.onreg(conn);
1094 }
1095 catch (e) {
1096 }
1097 }
1098 }
1099 this.update();
1100 };
1101 Connector.prototype.register = function() {
1102 var connector = this;
1103 var regErrHandler = function(err) {
1104 setRegText(connector, "no (" + err.toString() + ")");
1105 };
1106 var regSuccessHandler = function(conn) {
1107 connector.setConnection(conn);
1108 setRegText(connector, conn ? "Yes" : "No");
1109 };
1110 register(this.name, regSuccessHandler, regErrHandler);
1111 };
1112 Connector.prototype.unregister = function() {
1113 if (this.connection) {
1114 this.connection.unregister([]);
1115 this.setConnection(null);
1116 }
1117 };
1118
1119 // Returns a document fragment which contains Register/Unregister
1120 // buttons for use by the user to attempt to connect/disconnect
1121 // with the hub. This is useful for models where explicit
1122 // user registration is encouraged or required, but when using
1123 // the register-on-demand model such buttons are not necessary.
1124 Connector.prototype.createRegButtons = function() {
1125 var connector = this;
1126 var regButt = document.createElement("button");
1127 regButt.setAttribute("type", "button");
1128 regButt.appendChild(document.createTextNode("Register"));
1129 regButt.onclick = function() {connector.register();};
1130 this.whenUnregs.push(regButt);
1131 var unregButt = document.createElement("button");
1132 unregButt.setAttribute("type", "button");
1133 unregButt.appendChild(document.createTextNode("Unregister"));
1134 unregButt.onclick = function() {connector.unregister();};
1135 this.whenRegs.push(unregButt);
1136 var regText = document.createElement("span");
1137 this.regTextNodes.push(regText);
1138 var node = document.createDocumentFragment();
1139 node.appendChild(regButt);
1140 node.appendChild(document.createTextNode(" "));
1141 node.appendChild(unregButt);
1142 var label = document.createElement("span");
1143 label.innerHTML = " <strong>Registered: </strong>";
1144 node.appendChild(label);
1145 node.appendChild(regText);
1146 this.update();
1147 return node;
1148 };
1149
1150 Connector.prototype.update = function() {
1151 var i;
1152 var isConnected = !! this.connection;
1153 var enableds = isConnected ? this.whenRegs : this.whenUnregs;
1154 var disableds = isConnected ? this.whenUnregs : this.whenRegs;
1155 for (i = 0; i < enableds.length; i++) {
1156 enableds[i].removeAttribute("disabled");
1157 }
1158 for (i = 0; i < disableds.length; i++) {
1159 disableds[i].setAttribute("disabled", "disabled");
1160 }
1161 setRegText(this, "No");
1162 };
1163
1164 // Provides execution of a SAMP operation with register-on-demand.
1165 // You can use this method to provide lightweight registration/use
1166 // of web SAMP. Simply provide a connHandler function which
1167 // does something with a connection (e.g. sends a message) and
1168 // Connector.runWithConnection on it. This will connect if not
1169 // already connected, and call the connHandler on with the connection.
1170 // No explicit registration action is then required from the user.
1171 //
1172 // If the regErrorHandler argument is supplied, it is a function of
1173 // one (error) argument called in the case that registration-on-demand
1174 // fails.
1175 //
1176 // This is a more-or-less complete sampjs page:
1177 // <script>
1178 // var connector = new samp.Connector("pinger", {"samp.name": "Pinger"})
1179 // var pingFunc = function(connection) {
1180 // connection.notifyAll([new samp.Message("samp.app.ping", {})])
1181 // }
1182 // </script>
1183 // <button onclick="connector.runWithConnection(pingFunc)">Ping</button>
1184 Connector.prototype.runWithConnection =
1185 function(connHandler, regErrorHandler) {
1186 var connector = this;
1187 var regSuccessHandler = function(conn) {
1188 connector.setConnection(conn);
1189 connHandler(conn);
1190 };
1191 var regFailureHandler = function(e) {
1192 connector.setConnection(undefined);
1193 regErrorHandler(e);
1194 };
1195 var pingResultHandler = function(result) {
1196 connHandler(connector.connection);
1197 };
1198 var pingErrorHandler = function(err) {
1199 register(this.name, regSuccessHandler, regFailureHandler);
1200 };
1201 if (this.connection) {
1202 // Use getRegisteredClients as the most lightweight check
1203 // I can think of that this connection is still OK.
1204 // Ping doesn't work because the server replies even if the
1205 // private-key is incorrect/invalid. Is that a bug or not?
1206 this.connection.
1207 getRegisteredClients([], pingResultHandler, pingErrorHandler);
1208 }
1209 else {
1210 register(this.name, regSuccessHandler, regFailureHandler);
1211 }
1212 };
1213
1214 // Sets up an interval timer to run at intervals and notify a callback
1215 // about whether a hub is currently running.
1216 // Every millis milliseconds, the supplied availHandler function is
1217 // called with a boolean argument: true if a (web profile) hub is
1218 // running, false if not.
1219 // Returns the interval timer (can be passed to clearInterval()).
1220 Connector.prototype.onHubAvailability = function(availHandler, millis) {
1221 samp.ping(availHandler);
1222
1223 // Could use the W3C Page Visibility API to avoid making these
1224 // checks when the page is not visible.
1225 return setInterval(function() {samp.ping(availHandler);}, millis);
1226 };
1227
1228 // Determines whether a given subscriptions map indicates subscription
1229 // to a given mtype.
1230 var isSubscribed = function(subs, mtype) {
1231 var matching = function(pattern, mtype) {
1232 if (pattern == mtype) {
1233 return true;
1234 }
1235 else if (pattern === "*") {
1236 return true;
1237 }
1238 else {
1239 var prefix;
1240 var split = /^(.*)\.\*$/.exec(pat);
1241 if (split) {
1242 prefix = split[1];
1243 if (prefix === mtype.substring(0, prefix.length)) {
1244 return true;
1245 }
1246 }
1247 }
1248 return false;
1249 };
1250 var pat;
1251 for (pat in subs) {
1252 if (matching(pat, mtype)) {
1253 return true;
1254 }
1255 }
1256 return false;
1257 }
1258
1259 // Attempts registration with a SAMP hub.
1260 // On success the supplied connectionHandler function is called
1261 // with the connection as an argument, on failure the supplied
1262 // errorHandler is called with an argument that may be an Error
1263 // or an XmlRpc.Fault.
1264 var register = function(appName, connectionHandler, errorHandler) {
1265 var xClient = new XmlRpcClient();
1266 var regRequest = new XmlRpcRequest(WEBSAMP_PREFIX + "register");
1267 var securityInfo = {"samp.name": appName};
1268 regRequest.addParam(securityInfo);
1269 regRequest.checkParams([TYPE_MAP]);
1270 var resultHandler = function(result) {
1271 var conn;
1272 var e;
1273 try {
1274 conn = new Connection(result);
1275 }
1276 catch (e) {
1277 errorHandler(e);
1278 return;
1279 }
1280 connectionHandler(conn);
1281 };
1282 xClient.execute(regRequest, resultHandler, errorHandler);
1283 };
1284
1285 // Calls the hub ping method once. It is not necessary to be
1286 // registered to do this.
1287 // The supplied pingHandler function is called with a boolean argument:
1288 // true if a (web profile) hub is running, false if not.
1289 var ping = function(pingHandler) {
1290 var xClient = new XmlRpcClient();
1291 var pingRequest = new XmlRpcRequest(WEBSAMP_PREFIX + "ping");
1292 var resultHandler = function(result) {
1293 pingHandler(true);
1294 };
1295 var errorHandler = function(error) {
1296 pingHandler(false);
1297 };
1298 xClient.execute(pingRequest, resultHandler, errorHandler);
1299 };
1300
1301
1302 /* Exports. */
1303 var jss = {};
1304 jss.XmlRpcRequest = XmlRpcRequest;
1305 jss.XmlRpcClient = XmlRpcClient;
1306 jss.Message = Message;
1307 jss.TYPE_STRING = TYPE_STRING;
1308 jss.TYPE_LIST = TYPE_LIST;
1309 jss.TYPE_MAP = TYPE_MAP;
1310 jss.register = register;
1311 jss.ping = ping;
1312 jss.isSubscribed = isSubscribed;
1313 jss.Connector = Connector;
1314 jss.Connection = Connection;
1315 jss.CallableClient = CallableClient;
1316 jss.ClientTracker = ClientTracker;
1317
1318 return jss;
1319 })();
1320
1321 if (typeof module !== 'undefined' && module.exports) {
1322 module.exports = { samp };
1323 }