This repository has been archived by the owner on Jan 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
usergrid.min.js
20 lines (20 loc) · 52.7 KB
/
usergrid.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function extend(subClass,superClass){var F=function(){};return F.prototype=superClass.prototype,subClass.prototype=new F,subClass.prototype.constructor=subClass,subClass.superclass=superClass.prototype,superClass.prototype.constructor==Object.prototype.constructor&&(superClass.prototype.constructor=superClass),subClass}function propCopy(from,to){for(var prop in from)from.hasOwnProperty(prop)&&(to[prop]="object"==typeof from[prop]&&"object"==typeof to[prop]?propCopy(from[prop],to[prop]):from[prop]);return to}function NOOP(){}function isValidUrl(url){if(!url)return!1;var doc,base,anchor,isValid=!1;try{doc=document.implementation.createHTMLDocument(""),base=doc.createElement("base"),base.href=base||window.lo,doc.head.appendChild(base),anchor=doc.createElement("a"),anchor.href=url,doc.body.appendChild(anchor),isValid=!(""===anchor.href)}catch(e){console.error(e)}finally{return doc.head.removeChild(base),doc.body.removeChild(anchor),base=null,anchor=null,doc=null,isValid}}function isUUID(uuid){return uuid?uuidValueRegex.test(uuid):!1}function encodeParams(params){var queryString;return params&&Object.keys(params)&&(queryString=[].slice.call(arguments).reduce(function(a,b){return a.concat(b instanceof Array?b:[b])},[]).filter(function(c){return"object"==typeof c}).reduce(function(p,c){return c instanceof Array?p.push(c):p=p.concat(Object.keys(c).map(function(key){return[key,c[key]]})),p},[]).reduce(function(p,c){return 2===c.length?p.push(c):p=p.concat(c),p},[]).reduce(function(p,c){return c[1]instanceof Array?c[1].forEach(function(v){p.push([c[0],v])}):p.push(c),p},[]).map(function(c){return c[1]=encodeURIComponent(c[1]),c.join("=")}).join("&")),queryString}function isFunction(f){return f&&null!==f&&"function"==typeof f}function doCallback(callback,params,context){var returnValue;return isFunction(callback)&&(params||(params=[]),context||(context=this),params.push(context),returnValue=callback.apply(context,params)),returnValue}function getSafeTime(prop){var time;switch(typeof prop){case"undefined":time=Date.now();break;case"number":time=prop;break;case"string":time=isNaN(prop)?Date.parse(prop):parseInt(prop);break;default:time=Date.parse(prop.toString())}return time}var UsergridEventable=function(){throw Error("'UsergridEventable' is not intended to be invoked directly")};UsergridEventable.prototype={bind:function(event,fn){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fn)},unbind:function(event,fn){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fn),1)},trigger:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},UsergridEventable.mixin=function(destObject){for(var props=["bind","unbind","trigger"],i=0;i<props.length;i++)props[i]in destObject.prototype&&(console.warn("overwriting '"+props[i]+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+props[i]+"' on '"+destObject.name+"'."),destObject.prototype["_"+props[i]]=destObject.prototype[props[i]]),destObject.prototype[props[i]]=UsergridEventable.prototype[props[i]]},function(){function Logger(name){this.logEnabled=!0,this.init(name,!0)}var name="Logger",global=this,overwrittenName=global[name];return Logger.METHODS=["log","error","warn","info","debug","assert","clear","count","dir","dirxml","exception","group","groupCollapsed","groupEnd","profile","profileEnd","table","time","timeEnd","trace"],Logger.prototype.init=function(name,logEnabled){this.name=name||"UNKNOWN",this.logEnabled=logEnabled||!0;var addMethod=function(method){this[method]=this.createLogMethod(method)}.bind(this);Logger.METHODS.forEach(addMethod)},Logger.prototype.createLogMethod=function(method){return Logger.prototype.log.bind(this,method)},Logger.prototype.prefix=function(method,args){var prepend="["+method.toUpperCase()+"]["+name+"]: ";return-1!==["log","error","warn","info"].indexOf(method)&&("string"==typeof args[0]?args[0]=prepend+args[0]:args.unshift(prepend)),args},Logger.prototype.log=function(){var args=[].slice.call(arguments);method=args.shift(),-1===Logger.METHODS.indexOf(method)&&(method="log"),this.logEnabled&&console&&console[method]&&(args=this.prefix(method,args),console[method].apply(console,args))},Logger.prototype.setLogEnabled=function(logEnabled){this.logEnabled=logEnabled||!0},Logger.mixin=function(destObject){destObject.__logger=new Logger(destObject.name||"UNKNOWN");var addMethod=function(method){method in destObject.prototype&&(console.warn("overwriting '"+method+"' on '"+destObject.name+"'."),console.warn("the previous version can be found at '_"+method+"' on '"+destObject.name+"'."),destObject.prototype["_"+method]=destObject.prototype[method]),destObject.prototype[method]=destObject.__logger.createLogMethod(method)};Logger.METHODS.forEach(addMethod)},global[name]=Logger,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Logger},global[name]}(),function(global){function Promise(){this.complete=!1,this.error=null,this.result=null,this.callbacks=[]}var name="Promise",overwrittenName=global[name];return Promise.prototype.then=function(callback,context){var f=function(){return callback.apply(context,arguments)};this.complete?f(this.error,this.result):this.callbacks.push(f)},Promise.prototype.done=function(error,result){if(this.complete=!0,this.error=error,this.result=result,this.callbacks){for(var i=0;i<this.callbacks.length;i++)this.callbacks[i](error,result);this.callbacks.length=0}},Promise.join=function(promises){function notifier(i){return function(error,result){completed+=1,errors[i]=error,results[i]=result,completed===total&&p.done(errors,results)}}for(var p=new Promise,total=promises.length,completed=0,errors=[],results=[],i=0;total>i;i++)promises[i]().then(notifier(i));return p},Promise.chain=function(promises,error,result){var p=new Promise;return null===promises||0===promises.length?p.done(error,result):promises[0](error,result).then(function(res,err){promises.splice(0,1),promises?Promise.chain(promises,res,err).then(function(r,e){p.done(r,e)}):p.done(res,err)}),p},global[name]=Promise,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Promise},global[name]}(this),function(){function partial(){var args=Array.prototype.slice.call(arguments),fn=args.shift();return fn.bind(this,args)}function Ajax(){function encode(data){var result="";if("string"==typeof data)result=data;else{var e=encodeURIComponent;for(var i in data)data.hasOwnProperty(i)&&(result+="&"+e(i)+"="+e(data[i]))}return result}function request(m,u,d){var timeout,p=new Promise;return self.logger.time(m+" "+u),function(xhr){xhr.onreadystatechange=function(){4===this.readyState&&(self.logger.timeEnd(m+" "+u),clearTimeout(timeout),p.done(null,this))},xhr.onerror=function(response){clearTimeout(timeout),p.done(response,null)},xhr.oncomplete=function(){clearTimeout(timeout),self.logger.timeEnd(m+" "+u),self.info("%s request to %s returned %s",m,u,this.status)},xhr.open(m,u),d&&("object"==typeof d&&(d=JSON.stringify(d)),xhr.setRequestHeader("Content-Type","application/json"),xhr.setRequestHeader("Accept","application/json")),timeout=setTimeout(function(){xhr.abort(),p.done("API Call timed out.",null)},3e4),xhr.send(encode(d))}(new XMLHttpRequest),p}this.logger=new global.Logger(name);var self=this;this.request=request,this.get=partial(request,"GET"),this.post=partial(request,"POST"),this.put=partial(request,"PUT"),this.delete=partial(request,"DELETE")}var exports,name="Ajax",global=this,overwrittenName=global[name];return global[name]=new Ajax,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}(),window.console=window.console||{},window.console.log=window.console.log||function(){};var uuidValueRegex=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;!function(global){function Usergrid(){this.logger=new Logger(name)}var name="Usergrid",overwrittenName=global[name],VALID_REQUEST_METHODS=["GET","POST","PUT","DELETE"];return Usergrid.isValidEndpoint=function(){return!0},Usergrid.Request=function(method,endpoint,query_params,data,callback){var p=new Promise;if(this.logger=new global.Logger("Usergrid.Request"),this.logger.time("process request "+method+" "+endpoint),this.endpoint=endpoint+"?"+encodeParams(query_params),this.method=method.toUpperCase(),this.data="object"==typeof data?JSON.stringify(data):data,-1===VALID_REQUEST_METHODS.indexOf(this.method))throw new UsergridInvalidHTTPMethodError("invalid request method '"+this.method+"'");if(!isValidUrl(this.endpoint))throw this.logger.error(endpoint,this.endpoint,/^https:\/\//.test(endpoint)),new UsergridInvalidURIError("The provided endpoint is not valid: "+this.endpoint);var request=function(){return Ajax.request(this.method,this.endpoint,this.data)}.bind(this),response=function(err,request){return new Usergrid.Response(err,request)}.bind(this),oncomplete=function(err,response){p.done(err,response),this.logger.info("REQUEST",err,response),doCallback(callback,[err,response]),this.logger.timeEnd("process request "+method+" "+endpoint)}.bind(this);return Promise.chain([request,response]).then(oncomplete),p},Usergrid.Response=function(err,response){var p=new Promise,data=null;try{data=JSON.parse(response.responseText)}catch(e){data={}}switch(Object.keys(data).forEach(function(key){Object.defineProperty(this,key,{value:data[key],enumerable:!0})}.bind(this)),Object.defineProperty(this,"logger",{enumerable:!1,configurable:!1,writable:!1,value:new global.Logger(name)}),Object.defineProperty(this,"success",{enumerable:!1,configurable:!1,writable:!0,value:!0}),Object.defineProperty(this,"err",{enumerable:!1,configurable:!1,writable:!0,value:err}),Object.defineProperty(this,"status",{enumerable:!1,configurable:!1,writable:!0,value:parseInt(response.status)}),Object.defineProperty(this,"statusGroup",{enumerable:!1,configurable:!1,writable:!0,value:this.status-this.status%100}),this.statusGroup){case 200:this.success=!0;break;case 400:case 500:case 300:case 100:default:this.success=!1}return this.success?p.done(null,this):p.done(UsergridError.fromResponse(data),this),p},Usergrid.Response.prototype.getEntities=function(){var entities;return this.success&&(entities=this.data?this.data.entities:this.entities),entities||[]},Usergrid.Response.prototype.getEntity=function(){var entities=this.getEntities();return entities[0]},Usergrid.VERSION=Usergrid.USERGRID_SDK_VERSION="0.11.0",global[name]=Usergrid,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),Usergrid},global[name]}(this),function(){var exports,name="Client",global=this,overwrittenName=global[name];return Usergrid.Client=function(options){this.URI=options.URI||"https://api.usergrid.com",options.orgName&&this.set("orgName",options.orgName),options.appName&&this.set("appName",options.appName),options.qs&&this.setObject("default_qs",options.qs),this.buildCurl=options.buildCurl||!1,this.logging=options.logging||!1},Usergrid.Client.prototype.request=function(options,callback){var uri,method=options.method||"GET",endpoint=options.endpoint,body=options.body||{},qs=options.qs||{},mQuery=options.mQuery||!1,orgName=this.get("orgName"),appName=this.get("appName"),default_qs=this.getObject("default_qs");if(!mQuery&&!orgName&&!appName)return logoutCallback();uri=mQuery?this.URI+"/"+endpoint:this.URI+"/"+orgName+"/"+appName+"/"+endpoint,this.getToken()&&(qs.access_token=this.getToken()),default_qs&&(qs=propCopy(qs,default_qs));{var self=this;new Usergrid.Request(method,uri,qs,body,function(err,response){err?doCallback(callback,[err,response,self],self):doCallback(callback,[null,response,self],self)})}},Usergrid.Client.prototype.buildAssetURL=function(uuid){var self=this,qs={},assetURL=this.URI+"/"+this.orgName+"/"+this.appName+"/assets/"+uuid+"/data";self.getToken()&&(qs.access_token=self.getToken());var encoded_params=encodeParams(qs);return encoded_params&&(assetURL+="?"+encoded_params),assetURL},Usergrid.Client.prototype.createGroup=function(options,callback){var group=new Usergrid.Group({path:options.path,client:this,data:options});group.save(function(err,response){doCallback(callback,[err,response,group],group)})},Usergrid.Client.prototype.createEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.save(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.getEntity=function(options,callback){var entity=new Usergrid.Entity({client:this,data:options});entity.fetch(function(err,response){doCallback(callback,[err,response,entity],entity)})},Usergrid.Client.prototype.restoreEntity=function(serializedObject){var data=JSON.parse(serializedObject),options={client:this,data:data},entity=new Usergrid.Entity(options);return entity},Usergrid.Client.prototype.createCounter=function(options,callback){var counter=new Usergrid.Counter({client:this,data:options});counter.save(callback)},Usergrid.Client.prototype.createAsset=function(options,callback){var file=options.file;file&&(options.name=options.name||file.name,options["content-type"]=options["content-type"]||file.type,options.path=options.path||"/",delete options.file);var asset=new Usergrid.Asset({client:this,data:options});asset.save(function(err,response,asset){file&&!err?asset.upload(file,callback):doCallback(callback,[err,response,asset],asset)})},Usergrid.Client.prototype.createCollection=function(options,callback){return options.client=this,new Usergrid.Collection(options,function(err,data,collection){console.log("createCollection",arguments),doCallback(callback,[err,collection,data])})},Usergrid.Client.prototype.restoreCollection=function(serializedObject){var data=JSON.parse(serializedObject);data.client=this;var collection=new Usergrid.Collection(data);return collection},Usergrid.Client.prototype.getFeedForUser=function(username,callback){var options={method:"GET",endpoint:"users/"+username+"/feed"};this.request(options,function(err,data){err?doCallback(callback,[err]):doCallback(callback,[err,data,data.getEntities()])})},Usergrid.Client.prototype.createUserActivity=function(user,options,callback){options.type="users/"+user+"/activities",options={client:this,data:options};var entity=new Usergrid.Entity(options);entity.save(function(err,data){doCallback(callback,[err,data,entity])})},Usergrid.Client.prototype.createUserActivityWithEntity=function(user,content,callback){var username=user.get("username"),options={actor:{displayName:username,uuid:user.get("uuid"),username:username,email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:content};this.createUserActivity(username,options,callback)},Usergrid.Client.prototype.calcTimeDiff=function(){var seconds=0,time=this._end-this._start;try{seconds=(time/10/60).toFixed(2)}catch(e){return 0}return seconds},Usergrid.Client.prototype.setToken=function(token){this.set("token",token)},Usergrid.Client.prototype.getToken=function(){return this.get("token")},Usergrid.Client.prototype.setObject=function(key,value){value&&(value=JSON.stringify(value)),this.set(key,value)},Usergrid.Client.prototype.set=function(key,value){var keyStore="apigee_"+key;this[key]=value,"undefined"!=typeof Storage&&(value?localStorage.setItem(keyStore,value):localStorage.removeItem(keyStore))},Usergrid.Client.prototype.getObject=function(key){return JSON.parse(this.get(key))},Usergrid.Client.prototype.get=function(key){var keyStore="apigee_"+key,value=null;return this[key]?value=this[key]:"undefined"!=typeof Storage&&(value=localStorage.getItem(keyStore)),value},Usergrid.Client.prototype.signup=function(username,password,email,name,callback){var options={type:"users",username:username,password:password,email:email,name:name};this.createEntity(options,callback)},Usergrid.Client.prototype.login=function(username,password,callback){var self=this,options={method:"POST",endpoint:"token",body:{username:username,password:password,grant_type:"password"}};self.request(options,function(err,response){var user={};if(err)self.logging&&console.log("error trying to log user in");else{var options={client:self,data:response.user};user=new Usergrid.Entity(options),self.setToken(response.access_token)}doCallback(callback,[err,response,user])})},Usergrid.Client.prototype.reAuthenticateLite=function(callback){var self=this,options={method:"GET",endpoint:"management/me",mQuery:!0};this.request(options,function(err,response){err&&self.logging?console.log("error trying to re-authenticate user"):self.setToken(response.data.access_token),doCallback(callback,[err])})},Usergrid.Client.prototype.reAuthenticate=function(email,callback){var self=this,options={method:"GET",endpoint:"management/users/"+email,mQuery:!0};this.request(options,function(err,response){var data,organizations={},applications={},user={};if(err&&self.logging)console.log("error trying to full authenticate user");else{data=response.data,self.setToken(data.token),self.set("email",data.email),localStorage.setItem("accessToken",data.token),localStorage.setItem("userUUID",data.uuid),localStorage.setItem("userEmail",data.email);var userData={username:data.username,email:data.email,name:data.name,uuid:data.uuid},options={client:self,data:userData};user=new Usergrid.Entity(options),organizations=data.organizations;var org="";try{var existingOrg=self.get("orgName");org=organizations[existingOrg]?organizations[existingOrg]:organizations[Object.keys(organizations)[0]],self.set("orgName",org.name)}catch(e){err=!0,self.logging&&console.log("error selecting org")}applications=self.parseApplicationsArray(org),self.selectFirstApp(applications),self.setObject("organizations",organizations),self.setObject("applications",applications)}doCallback(callback,[err,data,user,organizations,applications],self)})},Usergrid.Client.prototype.loginFacebook=function(facebookToken,callback){var self=this,options={method:"GET",endpoint:"auth/facebook",qs:{fb_access_token:facebookToken}};this.request(options,function(err,data){var user={};if(err&&self.logging)console.log("error trying to log user in");else{var options={client:self,data:data.user};user=new Usergrid.Entity(options),self.setToken(data.access_token)}doCallback(callback,[err,data,user],self)})},Usergrid.Client.prototype.getLoggedInUser=function(callback){var self=this;if(this.getToken()){var options={method:"GET",endpoint:"users/me"};this.request(options,function(err,response){if(err)self.logging&&console.log("error trying to log user in"),console.error(err,response),doCallback(callback,[err,response,self],self);else{var options={client:self,data:response.getEntity()},user=new Usergrid.Entity(options);doCallback(callback,[null,response,user],self)}})}else doCallback(callback,[new UsergridError("Access Token not set"),null,self],self)},Usergrid.Client.prototype.isLoggedIn=function(){var token=this.getToken();return"undefined"!=typeof token&&null!==token},Usergrid.Client.prototype.logout=function(){this.setToken()},Usergrid.Client.prototype.destroyToken=function(username,token,revokeAll,callback){var options={client:self,method:"PUT"};options.endpoint=revokeAll===!0?"users/"+username+"/revoketokens":null===token?"users/"+username+"/revoketoken?token="+this.getToken():"users/"+username+"/revoketoken?token="+token,this.request(options,function(err,data){err?(self.logging&&console.log("error destroying access token"),doCallback(callback,[err,data,null],self)):(console.log(revokeAll===!0?"all user tokens invalidated":"token invalidated"),doCallback(callback,[err,data,null],self))})},Usergrid.Client.prototype.logoutAndDestroyToken=function(username,token,revokeAll,callback){null===username?console.log("username required to revoke tokens"):(this.destroyToken(username,token,revokeAll,callback),(revokeAll===!0||token===this.getToken()||null===token)&&this.setToken(null))},Usergrid.Client.prototype.buildCurlCall=function(options){var curl=["curl"],method=(options.method||"GET").toUpperCase(),body=options.body,uri=options.uri;return curl.push("-X"),curl.push(["POST","PUT","DELETE"].indexOf(method)>=0?method:"GET"),curl.push(uri),"object"==typeof body&&Object.keys(body).length>0&&-1!==["POST","PUT"].indexOf(method)&&(curl.push("-d"),curl.push("'"+JSON.stringify(body)+"'")),curl=curl.join(" "),console.log(curl),curl},Usergrid.Client.prototype.getDisplayImage=function(email,picture,size){size=size||50;var image="https://apigee.com/usergrid/images/user_profile.png";try{picture?image=picture:email.length&&(image="https://secure.gravatar.com/avatar/"+MD5(email)+"?s="+size+encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png"))}catch(e){}finally{return image}},global[name]=Usergrid.Client,global[name].noConflict=function(){return overwrittenName&&(global[name]=overwrittenName),exports},global[name]}();var ENTITY_SYSTEM_PROPERTIES=["metadata","created","modified","oldpassword","newpassword","type","activated","uuid"];Usergrid.Entity=function(options){this._data={},this._client=void 0,options&&(this.set(options.data||{}),this._client=options.client||{})},Usergrid.Entity.isEntity=function(obj){return obj&&obj instanceof Usergrid.Entity},Usergrid.Entity.isPersistedEntity=function(obj){return isEntity(obj)&&isUUID(obj.get("uuid"))},Usergrid.Entity.prototype.serialize=function(){return JSON.stringify(this._data)},Usergrid.Entity.prototype.get=function(key){var value;if(0===arguments.length?value=this._data:arguments.length>1&&(key=[].slice.call(arguments).reduce(function(p,c){return c instanceof Array?p=p.concat(c):p.push(c),p},[])),key instanceof Array){var self=this;value=key.map(function(k){return self.get(k)})}else"undefined"!=typeof key&&(value=this._data[key]);return value},Usergrid.Entity.prototype.set=function(key,value){if("object"==typeof key)for(var field in key)this._data[field]=key[field];else"string"==typeof key?null===value?delete this._data[key]:this._data[key]=value:this._data={}},Usergrid.Entity.prototype.getEndpoint=function(){var name,type=this.get("type"),nameProperties=["uuid","name"];if(void 0===type)throw new UsergridError("cannot fetch entity, no entity type specified","no_type_specified");return/^users?$/.test(type)&&nameProperties.unshift("username"),name=this.get(nameProperties).filter(function(x){return null!==x&&"undefined"!=typeof x}).shift(),name?[type,name].join("/"):type},Usergrid.Entity.prototype.save=function(callback){var self=this,type=this.get("type"),method="POST",entityId=this.get("uuid"),entityData=this.get(),options={method:method,endpoint:type};entityId&&(options.method="PUT",options.endpoint+="/"+entityId),options.body=Object.keys(entityData).filter(function(key){return-1===ENTITY_SYSTEM_PROPERTIES.indexOf(key)}).reduce(function(data,key){return data[key]=entityData[key],data},{}),self._client.request(options,function(err,response){var entity=response.getEntity();entity&&(self.set(entity),self.set("type",/^\//.test(response.path)?response.path.substring(1):response.path)),err&&self._client.logging&&console.log("could not save entity"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.changePassword=function(oldpassword,newpassword,callback){var self=this;if("function"==typeof oldpassword&&void 0===callback&&(callback=oldpassword,oldpassword=self.get("oldpassword"),newpassword=self.get("newpassword")),self.set({password:null,oldpassword:null,newpassword:null}),!(/^users?$/.test(self.get("type"))&&oldpassword&&newpassword))throw new UsergridInvalidArgumentError("Invalid arguments passed to 'changePassword'");var options={method:"PUT",endpoint:"users/"+self.get("uuid")+"/password",body:{uuid:self.get("uuid"),username:self.get("username"),oldpassword:oldpassword,newpassword:newpassword}};self._client.request(options,function(err,response){err&&self._client.logging&&console.log("could not update user"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.fetch=function(callback){var endpoint,self=this;endpoint=this.getEndpoint();var options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,response){var entity=response.getEntity();entity&&self.set(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.destroy=function(callback){var self=this,endpoint=this.getEndpoint(),options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err||self.set(null),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.connect=function(connection,entity,callback){this.addOrRemoveConnection("POST",connection,entity,callback)},Usergrid.Entity.prototype.disconnect=function(connection,entity,callback){this.addOrRemoveConnection("DELETE",connection,entity,callback)},Usergrid.Entity.prototype.addOrRemoveConnection=function(method,connection,entity,callback){var self=this;if(-1==["POST","DELETE"].indexOf(method.toUpperCase()))throw new UsergridInvalidArgumentError("invalid method for connection call. must be 'POST' or 'DELETE'");var connecteeType=entity.get("type"),connectee=this.getEntityId(entity);if(!connectee)throw new UsergridInvalidArgumentError("connectee could not be identified");var connectorType=this.get("type"),connector=this.getEntityId(this);if(!connector)throw new UsergridInvalidArgumentError("connector could not be identified");var endpoint=[connectorType,connector,connection,connecteeType,connectee].join("/"),options={method:method,endpoint:endpoint};this._client.request(options,function(err,response){err&&self._client.logging&&console.log("There was an error with the connection call"),doCallback(callback,[err,response,self],self)})},Usergrid.Entity.prototype.getEntityId=function(entity){var id;return id=entity.get(isUUID(entity.get("uuid"))?"uuid":"users"===this.get("type")||"user"===this.get("type")?"username":"name")},Usergrid.Entity.prototype.getConnections=function(connection,callback){var self=this,connectorType=this.get("type"),connector=this.getEntityId(this);if(connector){var endpoint=connectorType+"/"+connector+"/"+connection+"/",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self[connection]={};for(var length=data&&data.entities?data.entities.length:0,i=0;length>i;i++)"user"===data.entities[i].type?self[connection][data.entities[i].username]=data.entities[i]:self[connection][data.entities[i].name]=data.entities[i];doCallback(callback,[err,data,data.entities],self)})}else if("function"==typeof callback){var error="Error in getConnections - no uuid specified.";self._client.logging&&console.log(error),doCallback(callback,[!0,error],self)}},Usergrid.Entity.prototype.getGroups=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/groups",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected"),self.groups=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getActivities=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/activities",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("entity could not be connected");for(var entity in data.entities)data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();self.activities=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowing=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/following",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user following");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.following=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.getFollowers=function(callback){var self=this,endpoint="users/"+this.get("uuid")+"/followers",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user followers");for(var entity in data.entities){data.entities[entity].createdDate=new Date(data.entities[entity].created).toUTCString();var image=self._client.getDisplayImage(data.entities[entity].email,data.entities[entity].picture);data.entities[entity]._portal_image_icon=image}self.followers=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Client.prototype.createRole=function(roleName,permissions,callback){var options={type:"role",name:roleName};this.createEntity(options,function(err,response,entity){err?doCallback(callback,[err,response,self]):entity.assignPermissions(permissions,function(err,data){err?doCallback(callback,[err,response,self]):doCallback(callback,[err,data,data.data],self)})})},Usergrid.Entity.prototype.getRoles=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/roles",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user roles"),self.roles=data.entities,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Entity.prototype.assignRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=self.get("username"):"group"==type&&null!=this.get("name")?entityID=self.get("name"):null!=this.get("uuid")&&(entityID=self.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.removeRole=function(roleName,callback){var entityID,self=this,type=self.get("type"),collection=type+"s";"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid")),"users"!=type&&"groups"!=type&&doCallback(callback,[new UsergridError("entity must be a group or user","invalid_entity_type"),null,this],this);var endpoint="roles/"+roleName+"/"+collection+"/"+entityID,options={method:"DELETE",endpoint:endpoint};this._client.request(options,function(err,response){err&&console.log("Could not assign role."),doCallback(callback,[err,response,self])})},Usergrid.Entity.prototype.assignPermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"POST",endpoint:endpoint,body:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not assign permissions"),doCallback(callback,[err,data,data.data],self)})},Usergrid.Entity.prototype.removePermissions=function(permissions,callback){var entityID,self=this,type=this.get("type");
"user"!=type&&"users"!=type&&"group"!=type&&"groups"!=type&&"role"!=type&&"roles"!=type&&doCallback(callback,[new UsergridError("entity must be a group, user, or role","invalid_entity_type"),null,this],this),"user"==type&&null!=this.get("username")?entityID=this.get("username"):"group"==type&&null!=this.get("name")?entityID=this.get("name"):null!=this.get("uuid")&&(entityID=this.get("uuid"));var endpoint=type+"/"+entityID+"/permissions",options={method:"DELETE",endpoint:endpoint,qs:{permission:permissions}};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not remove permissions"),doCallback(callback,[err,data,data.params.permission],self)})},Usergrid.Entity.prototype.getPermissions=function(callback){var self=this,endpoint=this.get("type")+"/"+this.get("uuid")+"/permissions",options={method:"GET",endpoint:endpoint};this._client.request(options,function(err,data){err&&self._client.logging&&console.log("could not get user permissions");var permissions=[];if(data.data){var perms=data.data,count=0;for(var i in perms){count++;var perm=perms[i],parts=perm.split(":"),ops_part="",path_part=parts[0];parts.length>1&&(ops_part=parts[0],path_part=parts[1]),ops_part=ops_part.replace("*","get,post,put,delete");var ops=ops_part.split(","),ops_object={};ops_object.get="no",ops_object.post="no",ops_object.put="no",ops_object.delete="no";for(var j in ops)ops_object[ops[j]]="yes";permissions.push({operations:ops_object,path:path_part,perm:perm})}}self.permissions=permissions,doCallback(callback,[err,data,data.entities],self)})},Usergrid.Collection=function(options){if(options&&(this._client=options.client,this._type=options.type,this.qs=options.qs||{},this._list=options.list||[],this._iterator=options.iterator||-1,this._previous=options.previous||[],this._next=options.next||null,this._cursor=options.cursor||null,options.list))for(var count=options.list.length,i=0;count>i;i++){var entity=this._client.restoreEntity(options.list[i]);this._list[i]=entity}},Usergrid.isCollection=function(obj){return obj&&obj instanceof Usergrid.Collection},Usergrid.Collection.prototype.serialize=function(){var data={};data.type=this._type,data.qs=this.qs,data.iterator=this._iterator,data.previous=this._previous,data.next=this._next,data.cursor=this._cursor,this.resetEntityPointer();var i=0;for(data.list=[];this.hasNextEntity();){var entity=this.getNextEntity();data.list[i]=entity.serialize(),i++}return data=JSON.stringify(data)},Usergrid.Collection.prototype.fetch=function(callback){var self=this,qs=this.qs;this._cursor?qs.cursor=this._cursor:delete qs.cursor;var options={method:"GET",endpoint:this._type,qs:this.qs};this._client.request(options,function(err,response){err&&self._client.logging?console.log("error getting collection"):(self.saveCursor(response.cursor||null),self.resetEntityPointer(),self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){var ent=new Usergrid.Entity({client:self._client});return ent.set(entity),ent.type=self._type,ent})),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addEntity=function(entityObject,callback){var self=this;entityObject.type=this._type,this._client.createEntity(entityObject,function(err,response,entity){err||self.addExistingEntity(entity),doCallback(callback,[err,response,self],self)})},Usergrid.Collection.prototype.addExistingEntity=function(entity){var count=this._list.length;this._list[count]=entity},Usergrid.Collection.prototype.destroyEntity=function(entity,callback){var self=this;entity.destroy(function(err,response){err?(self._client.logging&&console.log("could not destroy entity"),doCallback(callback,[err,response,self],self)):self.fetch(callback),self.removeEntity(entity)})},Usergrid.Collection.prototype.getEntitiesByCriteria=function(criteria){return this._list.filter(criteria)},Usergrid.Collection.prototype.getEntityByCriteria=function(criteria){return this.getEntitiesByCriteria(criteria).shift()},Usergrid.Collection.prototype.removeEntity=function(entity){var removedEntity=this.getEntityByCriteria(function(item){return entity.uuid===item.get("uuid")});return delete this._list[this._list.indexOf(removedEntity)],removedEntity},Usergrid.Collection.prototype.getEntityByUUID=function(uuid,callback){var entity=this.getEntityByCriteria(function(item){return item.get("uuid")===uuid});if(entity)doCallback(callback,[null,entity,entity],this);else{var options={data:{type:this._type,uuid:uuid},client:this._client};entity=new Usergrid.Entity(options),entity.fetch(callback)}},Usergrid.Collection.prototype.getFirstEntity=function(){var count=this._list.length;return count>0?this._list[0]:null},Usergrid.Collection.prototype.getLastEntity=function(){var count=this._list.length;return count>0?this._list[count-1]:null},Usergrid.Collection.prototype.hasNextEntity=function(){var next=this._iterator+1,hasNextElement=next>=0&&next<this._list.length;return hasNextElement?!0:!1},Usergrid.Collection.prototype.getNextEntity=function(){this._iterator++;var hasNextElement=this._iterator>=0&&this._iterator<=this._list.length;return hasNextElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.hasPrevEntity=function(){var previous=this._iterator-1,hasPreviousElement=previous>=0&&previous<this._list.length;return hasPreviousElement?!0:!1},Usergrid.Collection.prototype.getPrevEntity=function(){this._iterator--;var hasPreviousElement=this._iterator>=0&&this._iterator<=this._list.length;return hasPreviousElement?this._list[this._iterator]:!1},Usergrid.Collection.prototype.resetEntityPointer=function(){this._iterator=-1},Usergrid.Collection.prototype.saveCursor=function(cursor){this._next!==cursor&&(this._next=cursor)},Usergrid.Collection.prototype.resetPaging=function(){this._previous=[],this._next=null,this._cursor=null},Usergrid.Collection.prototype.hasNextPage=function(){return this._next},Usergrid.Collection.prototype.getNextPage=function(callback){this.hasNextPage()&&(this._previous.push(this._cursor),this._cursor=this._next,this._list=[],this.fetch(callback))},Usergrid.Collection.prototype.hasPreviousPage=function(){return this._previous.length>0},Usergrid.Collection.prototype.getPreviousPage=function(callback){this.hasPreviousPage()&&(this._next=null,this._cursor=this._previous.pop(),this._list=[],this.fetch(callback))},Usergrid.Group=function(options){this._path=options.path,this._list=[],this._client=options.client,this._data=options.data||{},this._data.type="groups"},Usergrid.Group.prototype=new Usergrid.Entity,Usergrid.Group.prototype.fetch=function(callback){var self=this,groupEndpoint="groups/"+this._path,memberEndpoint="groups/"+this._path+"/users",groupOptions={method:"GET",endpoint:groupEndpoint},memberOptions={method:"GET",endpoint:memberEndpoint};this._client.request(groupOptions,function(err,response){if(err)self._client.logging&&console.log("error getting group"),doCallback(callback,[err,response],self);else{var entities=response.getEntities();if(entities&&entities.length){{entities.shift()}self._client.request(memberOptions,function(err,response){err&&self._client.logging?console.log("error getting group users"):self._list=response.getEntities().filter(function(entity){return isUUID(entity.uuid)}).map(function(entity){return new Usergrid.Entity({type:entity.type,client:self._client,uuid:entity.uuid,response:entity})}),doCallback(callback,[err,response,self],self)})}}})},Usergrid.Group.prototype.members=function(){return this._list},Usergrid.Group.prototype.add=function(options,callback){var self=this;options.user?(options={method:"POST",endpoint:"groups/"+this._path+"/users/"+options.user.get("username")},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.remove=function(options,callback){var self=this;options.user?(options={method:"DELETE",endpoint:"groups/"+this._path+"/users/"+options.user.username},this._client.request(options,function(error,response){error?doCallback(callback,[error,response,self],self):self.fetch(callback)})):doCallback(callback,[new UsergridError("no user specified","no_user_specified"),null,this],this)},Usergrid.Group.prototype.feed=function(callback){var self=this,options={method:"GET",endpoint:"groups/"+this._path+"/feed"};this._client.request(options,function(err,response){doCallback(callback,[err,response,self],self)})},Usergrid.Group.prototype.createGroupActivity=function(options,callback){var self=this,user=options.user,entity=new Usergrid.Entity({client:this._client,data:{actor:{displayName:user.get("username"),uuid:user.get("uuid"),username:user.get("username"),email:user.get("email"),picture:user.get("picture"),image:{duration:0,height:80,url:user.get("picture"),width:80}},verb:"post",content:options.content,type:"groups/"+this._path+"/activities"}});entity.save(function(err,response){doCallback(callback,[err,response,self])})},Usergrid.Counter=function(options){this._client=options.client,this._data=options.data||{},this._data.category=options.category||"UNKNOWN",this._data.timestamp=options.timestamp||0,this._data.type="events",this._data.counters=options.counters||{}};var COUNTER_RESOLUTIONS=["all","minute","five_minutes","half_hour","hour","six_day","day","week","month"];Usergrid.Counter.prototype=new Usergrid.Entity,Usergrid.Counter.prototype.fetch=function(callback){this.getData({},callback)},Usergrid.Counter.prototype.increment=function(options,callback){var self=this,name=options.name,value=options.value;return name?isNaN(value)?doCallback(callback,[new UsergridInvalidArgumentError("'value' for increment, decrement must be a number"),null,self],self):(self._data.counters[name]=parseInt(value)||1,self.save(callback)):doCallback(callback,[new UsergridInvalidArgumentError("'name' for increment, decrement must be a number"),null,self],self)},Usergrid.Counter.prototype.decrement=function(options,callback){var self=this,name=options.name,value=options.value;self.increment({name:name,value:-(parseInt(value)||1)},callback)},Usergrid.Counter.prototype.reset=function(options,callback){var self=this,name=options.name;self.increment({name:name,value:0},callback)},Usergrid.Counter.prototype.getData=function(options,callback){var start_time,end_time,start=options.start||0,end=options.end||Date.now(),resolution=(options.resolution||"all").toLowerCase(),counters=options.counters||Object.keys(this._data.counters),res=(resolution||"all").toLowerCase();-1===COUNTER_RESOLUTIONS.indexOf(res)&&(res="all"),start_time=getSafeTime(start),end_time=getSafeTime(end);var self=this,params=Object.keys(counters).map(function(counter){return["counter",encodeURIComponent(counters[counter])].join("=")});params.push("resolution="+res),params.push("start_time="+String(start_time)),params.push("end_time="+String(end_time));var endpoint="counters?"+params.join("&");this._client.request({endpoint:endpoint},function(err,data){return data.counters&&data.counters.length&&data.counters.forEach(function(counter){self._data.counters[counter.name]=counter.value||counter.values}),doCallback(callback,[err,data,self],self)})},Usergrid.Folder=function(options,callback){var self=this;console.log("FOLDER OPTIONS",options),self._client=options.client,self._data=options.data||{},self._data.type="folders";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});return missingData?doCallback(callback,[new UsergridInvalidArgumentError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):void self.save(function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):(response&&response.entities&&response.entities.length&&self.set(response.entities[0]),doCallback(callback,[null,response,self],self))})},Usergrid.Folder.prototype=new Usergrid.Entity,Usergrid.Folder.prototype.fetch=function(callback){var self=this;Usergrid.Entity.prototype.fetch.call(self,function(err,data){console.log("self",self.get()),console.log("data",data),err?doCallback(callback,[null,data,self],self):self.getAssets(function(err,response){err?doCallback(callback,[new UsergridError(response),resonse,self],self):doCallback(callback,[null,self],self)})})},Usergrid.Folder.prototype.addAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset,asset instanceof Usergrid.Entity||(asset=new Usergrid.Asset(asset));break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}asset&&asset instanceof Usergrid.Entity&&asset.fetch(function(err,data){if(err)doCallback(callback,[new UsergridError(data),data,self],self);else{var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};self._client.request(options,callback)}})}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.removeAsset=function(options,callback){var self=this;if("asset"in options){var asset=null;switch(typeof options.asset){case"object":asset=options.asset;break;case"string":isUUID(options.asset)&&(asset=new Usergrid.Asset({client:self._client,data:{uuid:options.asset,type:"assets"}}))}if(asset&&null!==asset){var endpoint=["folders",self.get("uuid"),"assets",asset.get("uuid")].join("/");self._client.request({method:"DELETE",endpoint:endpoint},function(err,response){err?doCallback(callback,[new UsergridError(response),response,self],self):doCallback(callback,[null,response,self],self)})}}else doCallback(callback,[new UsergridInvalidArgumentError("No asset specified"),null,self],self)},Usergrid.Folder.prototype.getAssets=function(callback){return this.getConnections("assets",callback)},XMLHttpRequest.prototype.sendAsBinary||(XMLHttpRequest.prototype.sendAsBinary=function(sData){for(var nBytes=sData.length,ui8Data=new Uint8Array(nBytes),nIdx=0;nBytes>nIdx;nIdx++)ui8Data[nIdx]=255&sData.charCodeAt(nIdx);this.send(ui8Data)}),Usergrid.Asset=function(options,callback){var self=this;self._client=options.client,self._data=options.data||{},self._data.type="assets";var missingData=["name","owner","path"].some(function(required){return!(required in self._data)});missingData?doCallback(callback,[new UsergridError("Invalid asset data: 'name', 'owner', and 'path' are required properties."),null,self],self):self.save(function(err,data){err?doCallback(callback,[new UsergridError(data),data,self],self):(data&&data.entities&&data.entities.length&&self.set(data.entities[0]),doCallback(callback,[null,data,self],self))})},Usergrid.Asset.prototype=new Usergrid.Entity,Usergrid.Asset.prototype.addToFolder=function(options,callback){var self=this;if("folder"in options&&isUUID(options.folder)){Usergrid.Folder({uuid:options.folder},function(err,folder){if(err)doCallback(callback,[UsergridError.fromResponse(folder),folder,self],self);else{var endpoint=["folders",folder.get("uuid"),"assets",self.get("uuid")].join("/"),options={method:"POST",endpoint:endpoint};this._client.request(options,function(err,response){err?doCallback(callback,[UsergridError.fromResponse(folder),response,self],self):doCallback(callback,[null,folder,self],self)})}})}else doCallback(callback,[new UsergridError("folder not specified"),null,self],self)},Usergrid.Entity.prototype.attachAsset=function(file,callback){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return void doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser."),null,this],this);var self=this,args=arguments,type=this._data.type,attempts=self.get("attempts");if(isNaN(attempts)&&(attempts=3),"assets"!=type&&"asset"!=type)var endpoint=[this._client.URI,this._client.orgName,this._client.appName,type,self.get("uuid")].join("/");else{self.set("content-type",file.type),self.set("size",file.size);var endpoint=[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/")}var xhr=new XMLHttpRequest;xhr.open("POST",endpoint,!0),xhr.onerror=function(){doCallback(callback,[new UsergridError("The File APIs are not fully supported by your browser.")],xhr,self)},xhr.onload=function(){xhr.status>=500&&attempts>0?(self.set("attempts",--attempts),setTimeout(function(){self.attachAsset.apply(self,args)},100)):xhr.status>=300?(self.set("attempts"),doCallback(callback,[new UsergridError(JSON.parse(xhr.responseText)),xhr,self],self)):(self.set("attempts"),self.fetch(),doCallback(callback,[null,xhr,self],self))};var fr=new FileReader;fr.onload=function(){var binary=fr.result;("assets"===type||"asset"===type)&&(xhr.overrideMimeType("application/octet-stream"),xhr.setRequestHeader("Content-Type","application/octet-stream")),xhr.sendAsBinary(binary)},fr.readAsBinaryString(file)},Usergrid.Asset.prototype.upload=function(data,callback){this.attachAsset(data,function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},Usergrid.Entity.prototype.downloadAsset=function(callback){var endpoint,self=this,type=this._data.type,xhr=new XMLHttpRequest;endpoint="assets"!=type&&"asset"!=type?[this._client.URI,this._client.orgName,this._client.appName,type,self.get("uuid")].join("/"):[this._client.URI,this._client.orgName,this._client.appName,"assets",self.get("uuid"),"data"].join("/"),xhr.open("GET",endpoint,!0),xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;"assets"!=type&&"asset"!=type?doCallback(callback,[null,blob,xhr],self):doCallback(callback,[null,xhr,self],self)},xhr.onerror=function(err){callback(!0,err),doCallback(callback,[new UsergridError(err),xhr,self],self)},"assets"!=type&&"asset"!=type?xhr.setRequestHeader("Accept",self._data["file-metadata"]["content-type"]):xhr.overrideMimeType(self.get("content-type")),xhr.send()},Usergrid.Asset.prototype.download=function(callback){this.downloadAsset(function(err,response){err?doCallback(callback,[new UsergridError(err),response,self],self):doCallback(callback,[null,response,self],self)})},function(global){function UsergridError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridHTTPResponseError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidHTTPMethodError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_http_method",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidURIError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_uri",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridInvalidArgumentError(message,name,timestamp,duration,exception){this.message=message,this.name=name||"invalid_argument",this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}function UsergridKeystoreDatabaseUpgradeNeededError(message,name,timestamp,duration,exception){this.message=message,this.name=name,this.timestamp=timestamp||Date.now(),this.duration=duration||0,this.exception=exception}var short,name="UsergridError",_name=global[name],_short=short&&void 0!==short?global[short]:void 0;return UsergridError.prototype=new Error,UsergridError.prototype.constructor=UsergridError,UsergridError.fromResponse=function(response){return response&&"undefined"!=typeof response?new UsergridError(response.error_description,response.error,response.timestamp,response.duration,response.exception):new UsergridError},UsergridError.createSubClass=function(name){return name in global&&global[name]?global[name]:(global[name]=function(){},global[name].name=name,global[name].prototype=new UsergridError,global[name])},UsergridHTTPResponseError.prototype=new UsergridError,UsergridInvalidHTTPMethodError.prototype=new UsergridError,UsergridInvalidURIError.prototype=new UsergridError,UsergridInvalidArgumentError.prototype=new UsergridError,UsergridKeystoreDatabaseUpgradeNeededError.prototype=new UsergridError,global.UsergridHTTPResponseError=UsergridHTTPResponseError,global.UsergridInvalidHTTPMethodError=UsergridInvalidHTTPMethodError,global.UsergridInvalidURIError=UsergridInvalidURIError,global.UsergridInvalidArgumentError=UsergridInvalidArgumentError,global.UsergridKeystoreDatabaseUpgradeNeededError=UsergridKeystoreDatabaseUpgradeNeededError,global[name]=UsergridError,void 0!==short&&(global[short]=UsergridError),global[name].noConflict=function(){return _name&&(global[name]=_name),void 0!==short&&(global[short]=_short),UsergridError},global[name]}(this);