@function module:kurentoClient.KurentoClient~deferred

@param {module:core/abstracts.MediaObject} mediaObject
@param {external:Object} params
@param {external:Promise} prevRpc
@param {external:Function} callback

@return {external:Promise}
500345
function deferred(mediaObject, params, prevRpc, callback) {
  var promises = [];

  if (mediaObject != undefined)
    promises.push(mediaObject);

  for (var key in params) {
    var param = params[key];
    if (param !== undefined)
      promises.push(param);
  };

  if (prevRpc != undefined)
    promises.push(prevRpc);

  return promiseCallback(Promise.all(promises), callback);
}
872820
function contributedExecFunc(service, name, progress, returnType, addedOutputFunction) {
		if (typeof(service.callback) !== "function") { //$NON-NLS-0$
			return undefined;
		}

		return function(args, context) {
			/* Use orion/Deferred since it supports progress, gcli/promise does not */
			//var promise = context.createPromise();
			var promise = new Deferred();

			var output = null;
			if (addedOutputFunction) {
				output = args["output"]; //$NON-NLS-0$
				if (output) {
					if (output.resourceExists()) {
						/* value is an array of nodes, in this context will always have a size of 1 */
						output = output.getValue()[0];
					} else {
						/* value is a string representing a non-existent resource */
						output = output.getValue();
					}
				}
				delete args.output;
			}

			/*
			 * The following function calls getPluginRepresentation(), if present, on all
			 * properties in object, in order to give custom types an opportunity to provide
			 * plugins with different representations of their instances than are used
			 * internally.
			 */
			var convertToPluginArgs = function(object, resultFn) {
				var keys = Object.keys(object);
				if (keys.length === 0) {
					resultFn(object);
				} else {
					var resultCount = 0;
					keys.forEach(function(current) {
						(function(key) {
							(function(value, fn) {
								if (value && value.getPluginRepresentation) {
									value.getPluginRepresentation().then(function(newValue) {
										fn(newValue);
									});
								} else {
									fn(value);
								}
							}(object[key], function(newValue) {
								object[key] = newValue;
								if (++resultCount === keys.length) {
									resultFn(object);
								}
							}));
						}(current));
					});
				}
			};

			convertToPluginArgs(args, function(pluginArgs) {
				function getCommandString(name, args) {
					var result = name;
					for (var key in args){
						result += " "; //$NON-NLS-0$
						result += args[key];
					}
					return result;
				}
				var resolvedFn = function(result) {
					var commandResult = new CommandResult(result, returnType);
					processResult(promise, commandResult, output);
				};
				var errorFn = function(error) {
					resolveError(promise, error);
				};
				var progressFn = function(data) {
					if (data && data.uriTemplate) {
						/* delegated UI request */
						var uriTemplate = new URITemplate(data.uriTemplate);
						var cwd = shellPageFileService.getCurrentDirectory();
						var href = uriTemplate.expand({}); // TODO
						var iframe = document.createElement("iframe"); //$NON-NLS-0$
						iframe.id = name;
						iframe.name = name;
						iframe.type = "text/html"; //$NON-NLS-0$
						iframe.sandbox = "allow-scripts allow-same-origin allow-forms"; //$NON-NLS-0$
						iframe.frameborder = 1;
						iframe.src = href;
						iframe.className = "delegatedUI"; //$NON-NLS-0$
						if (data.width) {
							iframe.style.width = data.width;
						}
						if (data.height) {
							iframe.style.height = data.height;
						}
						var outputElements = document.getElementsByClassName("gcli-row-out"); //$NON-NLS-0$
						var parentElement = outputElements[outputElements.length - 1];
						parentElement.appendChild(iframe);
						/* listen for notification from the iframe, expecting either a "result", "error" or "progress" property */
						window.addEventListener("message", function _messageHandler(event) { //$NON-NLS-0$
							if (event.source !== iframe.contentWindow) {
								return;
							}
							if (typeof event.data === "string") { //$NON-NLS-0$
								var data = JSON.parse(event.data);
								if (data.pageService === "orion.page.delegatedUI" && data.source === name) { //$NON-NLS-0$
									window.removeEventListener("message", _messageHandler, false); //$NON-NLS-0$
									if (data.error) {
										errorFn(data.error);
									} else {
										parentElement.removeChild(iframe);
										if (data.result) {
											resolvedFn(data.result);
										} else if (data.progress) {
											progressFn(data.progress);
										}
									}
								}
							}
						}, false);
					} else {
						if (typeof promise.progress === "function") { //$NON-NLS-0$
							var commandResult = new CommandResult(data, returnType);
							processResult(promise, commandResult, output, true);
						}
					}
				};
				progress.progress(service.callback(pluginArgs, {cwd: getCWD()}), "Executing command " + getCommandString(name, args)).then(resolvedFn, errorFn, progressFn); //$NON-NLS-0$
			});
			return promise;
		};
	}
195292
function(pMessage, pRequest, pResponse, fNext)
		{
			var tmpSessionID = null;
			if (pRequest.UserSession)
			{
				tmpSessionID = pRequest.UserSession.SessionID;
			}

			_Log.warn('API Error: '+pMessage, {SessionID: tmpSessionID, RequestID:pRequest.RequestUUID, RequestURL:pRequest.url, Action:'APIError'}, pRequest);
			pResponse.send({Error:pMessage});

			return fNext();
		}
1094598
public static <T> AsyncCallback<T> before (AsyncCallback<T> target,
                                               final Function<T, Void> preOp)
    {
        return new ChainedCallback<T, T>(target) {
            @Override public void onSuccess (T result) {
                preOp.apply(result);
                forwardSuccess(result);
            }
        };
    }
1098247
function(RTCPeerConnection) {
    var methods = ['createOffer', 'createAnswer'];
    methods.forEach(function(method) {
      var nativeMethod = RTCPeerConnection.prototype[method];
      RTCPeerConnection.prototype[method] = function() {
        var args = arguments;
        if (typeof args[0] === 'function' ||
            typeof args[1] === 'function') { // legacy
          return nativeMethod.apply(this, [arguments[2]])
            .then(function(description) {
              if (typeof args[0] === 'function') {
                args[0].apply(null, [description]);
              }
            }, function(error) {
              if (typeof args[1] === 'function') {
                args[1].apply(null, [error]);
              }
            });
        }
        return nativeMethod.apply(this, arguments);
      };
    });

    methods = ['setLocalDescription', 'setRemoteDescription',
      'addIceCandidate'];
    methods.forEach(function(method) {
      var nativeMethod = RTCPeerConnection.prototype[method];
      RTCPeerConnection.prototype[method] = function() {
        var args = arguments;
        if (typeof args[1] === 'function' ||
            typeof args[2] === 'function') { // legacy
          return nativeMethod.apply(this, arguments)
            .then(function() {
              if (typeof args[1] === 'function') {
                args[1].apply(null);
              }
            }, function(error) {
              if (typeof args[2] === 'function') {
                args[2].apply(null, [error]);
              }
            });
        }
        return nativeMethod.apply(this, arguments);
      };
    });

    // getStats is special. It doesn't have a spec legacy method yet we support
    // getStats(something, cb) without error callbacks.
    ['getStats'].forEach(function(method) {
      var nativeMethod = RTCPeerConnection.prototype[method];
      RTCPeerConnection.prototype[method] = function() {
        var args = arguments;
        if (typeof args[1] === 'function') {
          return nativeMethod.apply(this, arguments)
            .then(function() {
              if (typeof args[1] === 'function') {
                args[1].apply(null);
              }
            });
        }
        return nativeMethod.apply(this, arguments);
      };
    });
  }
769807
function (template, templateUrl) {
                    var deferred = $q.defer();
                    if (template) {
                        deferred.resolve(template);
                    } else if (templateUrl) {
                        $templateRequest(templateUrl, true)
                            .then(function (template) {
                                deferred.resolve(template);
                            }, function (error) {
                                deferred.reject(error);
                            });
                    } else {
                        deferred.reject("No template or templateUrl has been specified.");
                    }
                    return deferred.promise;
                }
124897
function(p, callback) {

		var _this = this;
		var error = _this.error;

		// This has to go through a POST request
		if (!_this.isEmpty(p.data) && !('FileList' in window) && _this.hasBinary(p.data)) {

			// Disable XHR and JSONP
			p.xhr = false;
			p.jsonp = false;
		}

		// Check if the browser and service support CORS
		var cors = this.request_cors(function() {
			// If it does then run this...
			return ((p.xhr === undefined) || (p.xhr && (typeof (p.xhr) !== 'function' || p.xhr(p, p.query))));
		});

		if (cors) {

			formatUrl(p, function(url) {

				var x = _this.xhr(p.method, url, p.headers, p.data, callback);
				x.onprogress = p.onprogress || null;

				// Windows Phone does not support xhr.upload, see #74
				// Feature detect
				if (x.upload && p.onuploadprogress) {
					x.upload.onprogress = p.onuploadprogress;
				}

			});

			return;
		}

		// Clone the query object
		// Each request modifies the query object and needs to be tared after each one.
		var _query = p.query;

		p.query = _this.clone(p.query);

		// Assign a new callbackID
		p.callbackID = _this.globalEvent();

		// JSONP
		if (p.jsonp !== false) {

			// Clone the query object
			p.query.callback = p.callbackID;

			// If the JSONP is a function then run it
			if (typeof (p.jsonp) === 'function') {
				p.jsonp(p, p.query);
			}

			// Lets use JSONP if the method is 'get'
			if (p.method === 'get') {

				formatUrl(p, function(url) {
					_this.jsonp(url, callback, p.callbackID, p.timeout);
				});

				return;
			}
			else {
				// It's not compatible reset query
				p.query = _query;
			}

		}

		// Otherwise we're on to the old school, iframe hacks and JSONP
		if (p.form !== false) {

			// Add some additional query parameters to the URL
			// We're pretty stuffed if the endpoint doesn't like these
			p.query.redirect_uri = p.redirect_uri;
			p.query.state = JSON.stringify({callback:p.callbackID});

			var opts;

			if (typeof (p.form) === 'function') {

				// Format the request
				opts = p.form(p, p.query);
			}

			if (p.method === 'post' && opts !== false) {

				formatUrl(p, function(url) {
					_this.post(url, p.data, opts, callback, p.callbackID, p.timeout);
				});

				return;
			}
		}

		// None of the methods were successful throw an error
		callback(error('invalid_request', 'There was no mechanism for handling this request'));

		return;

		// Format URL
		// Constructs the request URL, optionally wraps the URL through a call to a proxy server
		// Returns the formatted URL
		function formatUrl(p, callback) {

			// Are we signing the request?
			var sign;

			// OAuth1
			// Remove the token from the query before signing
			if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) {

				// OAUTH SIGNING PROXY
				sign = p.query.access_token;

				// Remove the access_token
				delete p.query.access_token;

				// Enfore use of Proxy
				p.proxy = true;
			}

			// POST body to querystring
			if (p.data && (p.method === 'get' || p.method === 'delete')) {
				// Attach the p.data to the querystring.
				_this.extend(p.query, p.data);
				p.data = null;
			}

			// Construct the path
			var path = _this.qs(p.url, p.query);

			// Proxy the request through a server
			// Used for signing OAuth1
			// And circumventing services without Access-Control Headers
			if (p.proxy) {
				// Use the proxy as a path
				path = _this.qs(p.oauth_proxy, {
					path: path,
					access_token: sign || '',

					// This will prompt the request to be signed as though it is OAuth1
					then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'),
					method: p.method.toLowerCase(),
					suppress_response_codes: true
				});
			}

			callback(path);
		}
	}
431215
function (methodName, params, execOptions) {
                var defer = vow.defer();
                var url = this._basePath + methodName;
                var data = JSON.stringify(params);

                sendAjaxRequest(url, data, execOptions).then(
                    this._resolvePromise.bind(this, defer),
                    this._rejectPromise.bind(this, defer)
                );

                return defer.promise();
            }
305310
function StereoAudioRecorder(mediaStream) {
    // void start(optional long timeSlice)
    // timestamp to fire "ondataavailable"
    this.start = function(timeSlice) {
        timeSlice = timeSlice || 1000;

        mediaRecorder = new StereoAudioRecorderHelper(mediaStream, this);

        mediaRecorder.record();

        timeout = setInterval(function() {
            mediaRecorder.requestData();
        }, timeSlice);
    };

    this.stop = function() {
        if (mediaRecorder) {
            mediaRecorder.stop();
            clearTimeout(timeout);
            this.onstop();
        }
    };

    this.pause = function() {
        if (!mediaRecorder) {
            return;
        }

        mediaRecorder.pause();
    };

    this.resume = function() {
        if (!mediaRecorder) {
            return;
        }

        mediaRecorder.resume();
    };

    this.ondataavailable = function() {};
    this.onstop = function() {};

    // Reference to "StereoAudioRecorder" object
    var mediaRecorder;
    var timeout;
}
1357949
function createObject(constructor) {
    var mediaObject = new constructor(strict)

    mediaObject.on('_describe', describe);
    mediaObject.on('_rpc', encodeRpc);

    if (mediaObject instanceof register.abstracts['kurento.Hub'] ||
      mediaObject instanceof register
      .classes['kurento.MediaPipeline'])
      mediaObject.on('_create', encodeCreate);

    if (mediaObject instanceof register.classes['kurento.MediaPipeline'])
      mediaObject.on('_transaction', encodeTransaction);

    return mediaObject;
  }
403293
function (azurePromise) {
      var deferred = $q.defer();
      azurePromise.done(function (items) {
        deferred.resolve(items);
      }, function (err) {
        deferred.reject(err);
      });
      return deferred.promise;
    }
516732
function Deferred(opts){
 	/**
	 * @define {object} Collection of public methods.
	 */
	var self = {};

	/**
	 * @define {object} options for the constructor 
	 */
	var opts = opts || {};

	/**
	 * @define {object} A promise object that will be returned
	 */
	var promise = {};

	/**
	 * @define {object} Event system for controlling events
	 */
	var event = Event();
	
	/**
	 * Promise then method
	 * This is for chaining promis callbacks
	 * @example promiseFunction().then(
	 * function(){ // success }, 
	 * function(){ // rejected }, 
	 * function(){ // notify } 
	 * ).then( ... );
	 * @param {function} sucess Success callback
	 * @param {function} reject Reject callback
	 * @param {function} notify notify callback
	 * @return {object} Returns the promise object
	 */
	function promiseThen(success, reject, notify){
		/**
		 * @define {object} Return a new promise
		 */
		var def = Deferred();

		/**
		 * Resolved promise
		 * @example example
		 * @param {string} A string key for the event system
		 * @param {function} A callback when event is triggered
		 * @return {object} Returns promise object
		 */
		event.on('resolve', function(){ 
			/**
			 * If the success callback returns a promise
			 * then resolve/reject/notify that returned promise
			 */
			var promise = success();
			if(!promise) return;
			promise.success(function(){
				/** handle the returned deferred object */
				def.resolve();
			});
			promise.error(function(){
				def.reject();
			});
			promise.notify(function(){
				def.notify();
			});
		});

		/**
		 * If promise is rejected/notify trigger the callback
		 */
		event.on('reject', function(){ 
			if(reject) reject();
		});

		event.on('notify', function(){ 
			if(notify) notify();
		});

		/**
		 * @return {object} Returns a promise object
		 */
		return def.promise; 
	}

	/**
	 * Promise methods
	 * @example promise.then( //new promise ).then(...)
	 * @example promise.success(...).error(...).notify(...)
	 * @param {function} callback A callback for the promise
	 * @return {object} Return the promise
	 */
	function promiseSuccess(callback){
		event.on('resolve', callback);
		return promise;
	}

	function promiseError(callback){
		event.on('reject', callback);
		return promise;
	}

	function promiseNotified(callback){
		event.on('notify', callback);
		return promise;
	}

	/**
	 * Deferred methods to trigger the promise
	 * @example def.resolve(args)
	 * @example def.reject(args)
	 * @example def.notify(args)
	 */
	function resolve(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('resolve', args);
	}

	function reject(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('reject', args);	
	}

	function notify(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('notify', args);		
	}

	/**
	 * Add the promise methods to the promise object
	 */
	promise.then = promiseThen;
	promise.success = promiseSuccess;
	promise.error = promiseError;
	promise.notify = promiseNotified;

	/**
	 * The promise object
	 * @public {object}
	 */
	self.promise = promise;

	/**
	 * Deferred public methods	
	 * @public {function}
	 */
	self.resolve = resolve;
	self.reject = reject;
	self.notify = notify;

	/**
	 * @return {object} return public methos
	 */
	return self;
}
1270759
function remoteCreateProject(auth, name) {
    return new Promise((resolve, reject) => {
        const drive = google.drive('v3');
        const options = {
            auth,
            resource: {
                name,
                mimeType: constants.MIME_GAS_JSON,
            },
            media: {
                mimeType: constants.MIME_GAS_JSON,
                body: JSON.stringify(files),
            },
        };

        drive.files.create(options, (err, result) => {
            if (err) {
                triageGoogleError(err, 'remoteCreateProject').then((triaged) => {
                    reject(triaged);
                }).catch((notTriaged) => {
                    reject(notTriaged);
                });
            } else {
                resolve(result.data);
                return;
            }
            return;
        });
    });
}
746938
function(ri, Receiver, recv_url, AjaxObject) {
    var that = this;
    that.ri = ri;
    that.Receiver = Receiver;
    that.recv_url = recv_url;
    that.AjaxObject = AjaxObject;
    that._scheduleRecv();
}
824457
function createDocumentLoader(promise) {
    return function(url, callback) {
      promise(url).then(
        // success
        function(remoteDocument) {
          callback(null, remoteDocument);
        },
        // failure
        callback
      );
    };
  }
79852
function bindAsObject (vm, key, source, cancelCallback) {
  defineReactive(vm, key, {})
  var cb = source.on('value', function (snapshot) {
    vm[key] = createRecord(snapshot)
  }, cancelCallback)
  vm._wilddogListeners[key] = { value: cb }
}
10521
function () {
                var deferred = $q.defer();
                if (!window.cordova) {
                    deferred.reject('Not supported in browser');
                } else {
                    if (!window.ThreeDeeTouch) {
                        deferred.reject('Could not find 3D touch plugin');
                    } else {
                        window.ThreeDeeTouch.isAvailable(function (value) {
                            deferred.resolve(value);
                        }, function (err) {
                            deferred.reject(err);
                        });
                    }
                }

                return deferred.promise;
            }