diff --git a/package.json b/package.json index 27fccff8..c7dca5e0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "tinode-webapp", "description": "Tinode messenger for the web", - "version": "0.15.7-rc4", + "version": "0.15.7-rc5", "devDependencies": { "babel-cli": "^6.26.0", "babel-preset-env": "^1.7.0", @@ -68,6 +68,6 @@ "firebase": "^5.5.2", "react": "^16.5.2", "react-dom": "^16.5.2", - "tinode-sdk": "^0.15.7-rc4" + "tinode-sdk": "^0.15.7-rc5" } } diff --git a/umd/index.dev.js b/umd/index.dev.js index 5ba0833c..ffd2a4ba 100644 --- a/umd/index.dev.js +++ b/umd/index.dev.js @@ -27774,7 +27774,7 @@ if (process.env.NODE_ENV === 'production') { }).call(this,require('_process')) },{"./cjs/schedule-tracing.development.js":17,"./cjs/schedule-tracing.production.min.js":18,"_process":28}],23:[function(require,module,exports){ (function (global){ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Tinode=e()}}(function(){var e={},t=[{name:"ST",start:/(?:^|\W)(\*)[^\s*]/,end:/[^\s*](\*)(?=$|\W)/},{name:"EM",start:/(?:^|[\W_])(_)[^\s_]/,end:/[^\s_](_)(?=$|[\W_])/},{name:"DL",start:/(?:^|\W)(~)[^\s~]/,end:/[^\s~](~)(?=$|\W)/},{name:"CO",start:/(?:^|\W)(`)[^`]/,end:/[^`](`)(?=$|\W)/}],n=[{name:"LN",dataName:"url",pack:function(e){return/^[a-z]+:\/\//i.test(e)||(e="http://"+e),{url:e}},re:/(https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/g},{name:"MN",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B@(\w\w+)/g},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#(\w\w+)/g}],s={ST:{name:"b",isVoid:!1},EM:{name:"i",isVoid:!1},DL:{name:"del",isVoid:!1},CO:{name:"tt",isVoid:!1},BR:{name:"br",isVoid:!0},LN:{name:"a",isVoid:!1},MN:{name:"a",isVoid:!1},HT:{name:"a",isVoid:!1},IM:{name:"img",isVoid:!0}};function i(e,t){var n;try{n=atob(e)}catch(e){console.log("Drafty: failed to decode base64-encoded object",e.message),n=atob("")}for(var s=n.length,i=new ArrayBuffer(s),r=new Uint8Array(i),o=0;o"},close:function(){return""}},EM:{open:function(){return""},close:function(){return""}},DL:{open:function(){return""},close:function(){return""}},CO:{open:function(){return""},close:function(){return""}},BR:{open:function(){return""},close:function(){return"
"}},LN:{open:function(e){return''},close:function(e){return""},props:function(e){return{href:e.url,target:"_blank"}}},MN:{open:function(e){return''},close:function(e){return""},props:function(e){return{name:e.val}}},HT:{open:function(e){return''},close:function(e){return""},props:function(e){return{name:e.val}}},IM:{open:function(e){var t=i(e.val,e.mime),n=e.ref?e.ref:t,s=(e.name?'':"")+'';return console.log("open: "+s),s},close:function(e){return e.name?"":""},props:function(e){return{src:i(e.val,e.mime),title:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":.75*e.val.length|0,"data-mime":e.mime}}}},o=function(){};o.parse=function(e){if("string"!=typeof e)return null;var s=e.split(/\r?\n/),i=[],r={},o=[];s.map(function(e){var s,a,c=[];if(t.map(function(t){c=c.concat(function(e,t,n,s){for(var i=[],r=0,o=e.slice(0);o.length>0;){var a=t.exec(o);if(null==a)break;var c=a.index+a[0].lastIndexOf(a[1]);o=o.slice(c+1),r=(c+=r)+1;var u=n?n.exec(o):null;if(null==u)break;var h=u.index+u[0].indexOf(u[1]);o=o.slice(h+1),r=(h+=r)+1,i.push({text:e.slice(c+1,h),children:[],start:c,end:h,type:s})}return i}(e,t.start,t.end,t.name))}),0==c.length)a={txt:e};else{c.sort(function(e,t){return e.start-t.start}),c=function e(t){if(0==t.length)return[];for(var n=[t[0]],s=t[0],i=1;is.end?(n.push(t[i]),s=t[i]):t[i].endn&&r.push({text:t.slice(n,a.start)});var c={type:a.type},u=e(t,a.start+1,a.end-1,a.children);u.length>0?c.children=u:c.text=a.text,r.push(c),n=a.end+1}return ni;return i=e.offset+e.len,t})}(a.txt)).length>0){var h=[];for(var l in s){var d=s[l],f=r[d.unique];f||(f=i.length,r[d.unique]=f,i.push({tp:d.type,data:d.data})),h.push({at:d.offset,len:d.len,key:f})}a.ent=h}o.push(a)});var a={txt:""};if(o.length>0){a.txt=o[0].txt,a.fmt=(o[0].fmt||[]).concat(o[0].ent||[]);for(var c=1;c0&&(a.ent=i)}return a},o.insertImage=function(e,t,n,s,i,r,o,a,c){return(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:t,len:1,key:e.ent.length}),e.ent.push({tp:"IM",data:{mime:n,val:s,width:i,height:r,name:o,ref:c,size:0|a}}),e},o.attachFile=function(e,t,n,s,i,r){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length});var o={tp:"EX",data:{mime:t,val:n,name:s,ref:r,size:0|i}};return r instanceof Promise&&(o.data.ref=r.then(function(e){o.data.ref=e},function(e){})),e.ent.push(o),e},o.UNSAFE_toHTML=function(e){var t,n,s,i=e.txt,o=e.fmt,a=e.ent,c=[];if(o)for(var u in o){var h,l=o[u],d=l.tp;if(!d){var f=a[l.key];f&&(d=f.tp,h=f.data)}r[d]&&(c.push({idx:l.at+l.len,what:r[d].close(h)}),c.push({idx:l.at,what:r[d].open(h)}))}for(var u in c.sort(function(e,t){return t.idx-e.idx}),c)c[u].what&&(t=i,n=c[u].idx,s=c[u].what,i=t.slice(0,n)+s+t.slice(n));return i},o.format=function(e,t,n){var i=e.txt,r=e.fmt,o=e.ent;if(i=i||"",!r)return[i];var a=[].concat(r);return a.map(function(e){e.at=e.at||0,e.len=e.len||0}),a.sort(function(e,t){return e.at-t.at==0?t.len-e.len:e.at-t.at}),a=a.map(function(e){var t,n=e.tp;return n||(e.key=e.key||0,t=o[e.key].data,n=o[e.key].tp),{tp:n,data:t,at:e.at,len:e.len}}),function e(t,n,i,r,o,a){for(var c=[],u=0;u0)for(var t in e.ent)if("EX"==e.ent[t].tp)return!0;return!1},o.attachments=function(e,t,n){if(e.ent&&e.ent.length>0)for(var s in e.ent)"EX"==e.ent[s].tp&&t.call(n,e.ent[s].data,s)},o.getDownloadUrl=function(e){var t=null;return e.val?t=i(e.val,e.mime):"string"==typeof e.ref&&(t=e.ref),t},o.isUploading=function(e){return e.ref instanceof Promise},o.getPreviewUrl=function(e){return e.val?i(e.val,e.mime):null},o.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},o.getEntityMimeType=function(e){return e.mime||"text/plain"},o.tagName=function(e){return s[e]?s[e].name:void 0},o.attrValue=function(e,t){if(t&&r[e])return r[e].props(t)},o.getContentType=function(){return"text/x-drafty"},e=o;var a={};function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}if("function"==typeof require)var u="0.15.7-rc4";var h="0",l=u||"0.15",d="tinodejs/"+l;function f(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)}))}function p(e,t,n){if(null==t)return e;if("object"!==c(t))return t||e;if(t instanceof Date)return t;if(t instanceof T)return new T(t);if(t instanceof Array)return t.length>0?t:e;for(var s in e||(e=t.constructor()),t)!t.hasOwnProperty(s)||!t[s]&&!1!==t[s]||n&&n[s]||"_generated"==s||(e[s]=p(e[s],t[s]));return e}function g(e,t,n,s){return e[t]=p(e[t],n,s),e[t]}function _(){var e=null;if("withCredentials"in new XMLHttpRequest)e=new XMLHttpRequest;else{if("undefined"==typeof XDomainRequest)throw new Error("browser not supported");e=new XDomainRequest}return e}function v(e,t){if("ts"===e&&"string"==typeof t&&t.length>=20&&t.length<=24){var n=new Date(t);if(n)return n}else if("acs"===e&&"object"===c(t))return new T(t);return t}function m(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":function(e,t){if(t instanceof Date)t=function(e){if(e&&0!=e.getTime()){var t=e.getUTCMilliseconds();return e.getUTCFullYear()+"-"+n(e.getUTCMonth()+1)+"-"+n(e.getUTCDate())+"T"+n(e.getUTCHours())+":"+n(e.getUTCMinutes())+":"+n(e.getUTCSeconds())+(t?"."+n(t,3):"")+"Z"}function n(e,t){return"0".repeat((t=t||2)-(""+e).length)+e}}(t);else if(null==t||!1===t||Array.isArray(t)&&0==t.length||"object"===c(t)&&0===Object.keys(t).length)return;return t}(0,t)}function b(e,t,n){var s=null;return"http"!==t&&"https"!==t&&"ws"!==t&&"wss"!==t||(s=t+"://","/"!==(s+=e).charAt(s.length-1)&&(s+="/"),s+="v"+h+"/channels","http"!==t&&"https"!==t||(s+="/lp"),s+="?apikey="+n),s}var w=function(e,t,n,s,i){var r=this,o=e,a=s,u=t,h=i,l=2e3,d=10,f=.3,p=null,g=0,m=!1,w=function(e){r.logger&&r.logger(e)};function M(e){var t=null;e.connect=function(n){return t&&1===t.readyState?Promise.resolve():(n&&(o=n),new Promise(function(n,s){var i=b(o,a?"wss":"ws",u);w("Connecting to: "+i);var r=new WebSocket(i);r.onopen=function(t){m=!1,e.onOpen&&e.onOpen(),n(),h&&(window.clearTimeout(p),p=null,g=0)},r.onclose=function(n){t=null,e.onDisconnect&&e.onDisconnect(null),!m&&h&&function(){var e=this;clearTimeout(p);var t=l*(Math.pow(2,g)*(1+f*Math.random()));g=g>=d?g:g+1,p=setTimeout(function(){w("Reconnecting, iter="+g+", timeout="+t),m||e.connect().catch(function(){})},t)}.call(e)},r.onerror=function(e){s(e)},r.onmessage=function(t){e.onMessage&&e.onMessage(t.data)},t=r}))},e.disconnect=function(){t&&(m=!0,t.close()),t=null},e.sendText=function(e){if(!t||t.readyState!=t.OPEN)throw new Error("Websocket is not connected");t.send(e)},e.isConnected=function(){return t&&1===t.readyState}}function S(e){var t=null,n=null,s=null;e.connect=function(s){return n?Promise.resolve():(s&&(o=s),new Promise(function(s,i){var r=b(o,a?"https":"http",u);w("Connecting to: "+r),(n=function n(s,i,r){var o=_();return o.onreadystatechange=function(a){if(4==o.readyState)if(201==o.status){var c=JSON.parse(o.responseText,v);o.responseText,t=s+"&sid="+c.ctrl.params.sid,(o=n(t)).send(null),e.onOpen&&e.onOpen(),i&&i()}else 200==o.status?(e.onMessage&&e.onMessage(o.responseText),(o=n(t)).send(null)):(r&&r(o.responseText),e.onMessage&&e.onMessage(o.responseText),e.onDisconnect&&e.onDisconnect(new Error(o.status+" "+o.responseText)))},o.open("GET",s,!0),o}(r,s,i)).send(null)}).catch(function(){}))},e.disconnect=function(){s&&(s.abort(),s=null),n&&(n.abort(),n=null),e.onDisconnect&&e.onDisconnect(null),t=null},e.sendText=function(e){var n,i;if(n=t,(i=_()).onreadystatechange=function(e){if(4==i.readyState&&i.status>=400)throw new Error("LP sender failed, "+i.status)},i.open("POST",n,!0),!(s=i)||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(e)},e.isConnected=function(){return n&&!0}}"lp"===n?S(this):"ws"===n?M(this):"object"==("undefined"==typeof window?"undefined":c(window))&&window.WebSocket?M(this):S(this),this.onMessage=void 0,this.onDisconnect=void 0,this.onOpen=void 0,this.logger=void 0},M=function(e,t,n,s,i){var r=this;this._appName=e||"Undefined",this._apiKey=n,this._browser="",this._platform="undefined",this._humanLanguage="xx","undefined"!=typeof navigator&&(this._browser=function(e){var t,n=(e=(e||"").replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(n){for(var s=["chrome","safari","mobile","version"],i=e.substr(n.index+n[0].length).split(" "),r=[],o=0;o0?r[0][0]+"/"+r[0][1]:n[1]}else t=/trident/i.test(e)?(n=/(?:\brv[ :]+([.\d]+))|(?:\bMSIE ([.\d]+))/g.exec(e))?"MSIE/"+(n[1]||n[2]):"MSIE/?":/firefox/i.test(e)?(n=/Firefox\/([.\d]+)/g.exec(e))?"Firefox/"+n[1]:"Firefox/?":/presto/i.test(e)?(n=/Opera\/([.\d]+)/g.exec(e))?"Opera/"+n[1]:"Opera/?":(n=/([\w.]+)\/([.\d]+)/.exec(e))?n[1]+"/"+n[2]:(n=e.split(" "))[0];if((n=t.split("/")).length>1){var c=n[1].split(".");t=n[0]+"/"+c[0]+(c[1]?"."+c[1]:"")}return t}(navigator.userAgent),this._platform=navigator.platform,this._humanLanguage=navigator.language||"en-US"),this._loggingEnabled=!1,this._trimLongStrings=!1,this._myUID=null,this._authenticated=!1,this._login=null,this._authToken=null,this._inPacketCount=0,this._messageId=Math.floor(65535*Math.random()+65535),this._serverInfo=null,this._deviceToken=null,this._pendingPromises={},this._connection=new w(t,n,s,i,!0),this.logger=function(e){if(r._loggingEnabled){var t=new Date,n=("0"+t.getUTCHours()).slice(-2)+":"+("0"+t.getUTCMinutes()).slice(-2)+":"+("0"+t.getUTCSeconds()).slice(-2)+":"+("0"+t.getUTCMilliseconds()).slice(-3);console.log("["+n+"] "+e)}},this._connection.logger=this.logger,this._cache={};var o=this.cachePut=function(e,t,n){r._cache[e+":"+t]=n},a=this.cacheGet=function(e,t){return r._cache[e+":"+t]},u=this.cacheDel=function(e,t){delete r._cache[e+":"+t]},h=this.cacheMap=function(e,t){for(var n in r._cache)if(e(r._cache[n],n,t))break};this.attachCacheToTopic=function(e){e._tinode=r,e._cacheGetUser=function(e){var t=a("user",e);if(t)return{user:e,public:p({},t)}},e._cachePutUser=function(e,t){return o("user",e,p({},t.public))},e._cacheDelUser=function(e){return u("user",e)},e._cachePutSelf=function(){return o("topic",e.name,e)},e._cacheDelSelf=function(){return u("topic",e.name)}};var f=function(e,t,n,s){var i=r._pendingPromises[e];i&&(delete r._pendingPromises[e],t>=200&&t<400?i.resolve&&i.resolve(n):i.reject&&i.reject(new Error("Error: "+s+" ("+t+")")))},g=this.getNextUniqueId=function(){return 0!=r._messageId?""+r._messageId++:void 0};this.initPacket=function(e,t){switch(e){case"hi":return{hi:{id:g(),ver:l,ua:r._appName+" ("+(r._browser?r._browser+"; ":"")+r._platform+"); "+d,dev:r._deviceToken,lang:r._humanLanguage}};case"acc":return{acc:{id:g(),user:null,scheme:null,secret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:g(),scheme:null,secret:null}};case"sub":return{sub:{id:g(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:g(),topic:t,unsub:!1}};case"pub":return{pub:{id:g(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:g(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:g(),topic:t,desc:{},sub:{},tags:[]}};case"del":return{del:{id:g(),topic:t,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:t,what:null,seq:void 0}};default:throw new Error("Unknown packet type requested: "+e)}},this.send=function(e,t){var n;t&&(n=function(e){var t=null;return e&&(t=new Promise(function(t,n){r._pendingPromises[e]={resolve:t,reject:n}})),t}(t)),e=function e(t){return Object.keys(t).forEach(function(n){"_"==n[0]?delete t[n]:t[n]?Array.isArray(t[n])&&0==t[n].length?delete t[n]:t[n]?"object"!=c(t[n])||t[n]instanceof Date||(e(t[n]),0==Object.getOwnPropertyNames(t[n]).length&&delete t[n]):delete t[n]:delete t[n]}),t}(e);var s=JSON.stringify(e);r.logger("out: "+(r._trimLongStrings?JSON.stringify(e,m):s));try{r._connection.sendText(s)}catch(e){if(!t)throw e;f(t,503,null,e.message)}return n},this.loginSuccessful=function(e){e.params&&e.params.user&&(r._myUID=e.params.user,r._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?r._authToken={token:e.params.token,expires:new Date(e.params.expires)}:r._authToken=null,r.onLogin&&r.onLogin(e.code,e.text))},this._connection.onMessage=function(e){if(e){r._inPacketCount++,r.onRawMessage&&r.onRawMessage(e);var t=JSON.parse(e,v);if(t)if(r.logger("in: "+(r._trimLongStrings?JSON.stringify(t,m):e)),r.onMessage&&r.onMessage(t),t.ctrl)r.onCtrlMessage&&r.onCtrlMessage(t.ctrl),t.ctrl.id&&f(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),t.ctrl.params&&"data"==t.ctrl.params.what&&(n=a("topic",t.ctrl.topic))&&n._allMessagesReceived(t.ctrl.params.count);else if(t.meta)(n=a("topic",t.meta.topic))&&n._routeMeta(t.meta),r.onMetaMessage&&r.onMetaMessage(t.meta);else if(t.data)(n=a("topic",t.data.topic))&&n._routeData(t.data),r.onDataMessage&&r.onDataMessage(t.data);else if(t.pres)(n=a("topic",t.pres.topic))&&n._routePres(t.pres),r.onPresMessage&&r.onPresMessage(t.pres);else if(t.info){var n;(n=a("topic",t.info.topic))&&n._routeInfo(t.info),r.onInfoMessage&&r.onInfoMessage(t.info)}else r.logger("ERROR: Unknown packet received.");else r.logger("in: "+e),r.logger("ERROR: failed to parse data")}},this._connection.onOpen=function(){r.hello()},this._connection.onDisconnect=function(e){r._inPacketCount=0,r._serverInfo=null,r._authenticated=!1,h(function(e,t){0===t.lastIndexOf("topic:",0)&&e._resetSub()}),r.onDisconnect&&r.onDisconnect(e)}};M.credential=function(e,t,n,s){if("object"==c(e)){var i=e;t=i.val,n=i.params,s=i.resp,e=i.meth}return e&&(t||s)?[{meth:e,val:t,resp:s,params:n}]:null},M.topicType=function(e){return{me:"me",fnd:"fnd",grp:"grp",new:"grp",usr:"p2p"}["string"==typeof e?e.substring(0,3):"xxx"]},M.isNewGroupTopicName=function(e){return"string"==typeof e&&"new"==e.substring(0,3)},M.getVersion=function(){return l},M.getLibrary=function(){return d},M.MESSAGE_STATUS_NONE=0,M.MESSAGE_STATUS_QUEUED=1,M.MESSAGE_STATUS_SENDING=2,M.MESSAGE_STATUS_SENT=3,M.MESSAGE_STATUS_RECEIVED=4,M.MESSAGE_STATUS_READ=5,M.MESSAGE_STATUS_TO_ME=6,M.DEL_CHAR="\u2421",M.prototype={connect:function(e){return this._connection.connect(e)},disconnect:function(){this._connection&&this._connection.disconnect()},isConnected:function(){return this._connection&&this._connection.isConnected()},isAuthenticated:function(){return this._authenticated},account:function(e,t,n,s,i){var r=this.initPacket("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=n,r.acc.login=s,i&&(r.acc.desc.defacs=i.defacs,r.acc.desc.public=i.public,r.acc.desc.private=i.private,r.acc.tags=i.tags,r.acc.cred=i.cred,r.acc.token=i.token),this.send(r,r.acc.id)},createAccount:function(e,t,n,s){var i=this,r=this.account("new",e,t,n,s);return n&&(r=r.then(function(e){return i.loginSuccessful(e),e})),r},createAccountBasic:function(e,t,n){return e=e||"",t=t||"",this.createAccount("basic",f(e+":"+t),!0,n)},updateAccountBasic:function(e,t,n,s){return t=t||"",n=n||"",this.account(e,"basic",f(t+":"+n),!1,s)},hello:function(){var e=this,t=this.initPacket("hi");return this.send(t,t.hi.id).then(function(t){return t.params&&(e._serverInfo=t.params),e.onConnect&&e.onConnect(),t}).catch(function(t){e.onDisconnect&&e.onDisconnect(t)})},setDeviceToken:function(e,t){var n=!1;return e&&e!=this._deviceToken&&(this._deviceToken=e,t&&this.isConnected()&&this.isAuthenticated()&&(this.send({hi:{dev:e}}),n=!0)),n},login:function(e,t,n){var s=this,i=this.initPacket("login");return i.login.scheme=e,i.login.secret=t,i.login.cred=n,this.send(i,i.login.id).then(function(e){return s.loginSuccessful(e),e})},loginBasic:function(e,t,n){var s=this;return this.login("basic",f(e+":"+t),n).then(function(t){return s._login=e,t})},loginToken:function(e,t){return this.login("token",e,t)},requestResetAuthSecret:function(e,t,n){return this.login("reset",f(e+":"+t+":"+n))},getAuthToken:function(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)},setAuthToken:function(e){this._authToken=e},subscribe:function(e,t,n){var s=this.initPacket("sub",e);return e||(e="new"),s.sub.get=t,n&&(n.sub&&(s.sub.set.sub=n.sub),M.isNewGroupTopicName(e)&&n.desc&&(s.sub.set.desc=n.desc),n.tags&&(s.sub.set.tags=n.tags)),this.send(s,s.sub.id)},leave:function(e,t){var n=this.initPacket("leave",e);return n.leave.unsub=t,this.send(n,n.leave.id)},createMessage:function(t,n,s){var i=this.initPacket("pub",t),r="string"==typeof n?e.parse(n):n;return r&&!e.isPlainText(r)&&(i.pub.head={mime:e.getContentType()},n=r),i.pub.noecho=s,i.pub.content=n,i.pub},publish:function(e,t,n){return this.publishMessage(this.createMessage(e,t,n))},publishMessage:function(e){return(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0,this.send({pub:e},e.id)},getMeta:function(e,t){var n=this.initPacket("get",e);return n.get=p(n.get,t),this.send(n,n.get.id)},setMeta:function(e,t){var n=this.initPacket("set",e),s=[];return t&&["desc","sub","tags"].map(function(e){t.hasOwnProperty(e)&&(s.push(e),n.set[e]=t[e])}),0==s.length?Promise.reject(new Error("Invalid {set} parameters")):this.send(n,n.set.id)},delMessages:function(e,t,n){var s=this.initPacket("del",e);return s.del.what="msg",s.del.delseq=t,s.del.hard=n,this.send(s,s.del.id)},delTopic:function(e){var t=this,n=this.initPacket("del",e);return n.del.what="topic",this.send(n,n.del.id).then(function(n){return t.cacheDel("topic",e),t.ctrl})},delSubscription:function(e,t){var n=this.initPacket("del",e);return n.del.what="sub",n.del.user=t,this.send(n,n.del.id)},note:function(e,t,n){if(n<=0||n>=268435455)throw new Error("Invalid message id "+n);var s=this.initPacket("note",e);s.note.what=t,s.note.seq=n,this.send(s)},noteKeyPress:function(e){var t=this.initPacket("note",e);t.note.what="kp",this.send(t)},getTopic:function(e){var t=this.cacheGet("topic",e);return!t&&e&&(t="me"==e?new D:"fnd"==e?new E:new y(e),this.cachePut("topic",e,t),this.attachCacheToTopic(t)),t},newTopic:function(e){var t=new y("new",e);return this.attachCacheToTopic(t),t},newGroupTopicName:function(){return"new"+this.getNextUniqueId()},newTopicWith:function(e,t){var n=new y(e,t);return this.attachCacheToTopic(n),n},getMeTopic:function(){return this.getTopic("me")},getFndTopic:function(){return this.getTopic("fnd")},getLargeFileHelper:function(){return new x(this)},getCurrentUserID:function(){return this._myUID},getCurrentLogin:function(){return this._login},getServerInfo:function(){return this._serverInfo},enableLogging:function(e,t){this._loggingEnabled=e,this._trimLongStrings=t},isTopicOnline:function(e){var t=this.getMeTopic(),n=t&&t.getContact(e);return n&&n.online},wantAkn:function(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0},onWebsocketOpen:void 0,onConnect:void 0,onDisconnect:void 0,onLogin:void 0,onCtrlMessage:void 0,onDataMessage:void 0,onPresMessage:void 0,onMessage:void 0,onRawMessage:void 0};var S=function(e){this.topic=e;var t=e._tinode.getMeTopic();this.contact=t&&t.getContact(e.name),this.what={}};S.prototype={_get_ims:function(){var e=this.contact&&this.contact.updated,t=this.topic._lastDescUpdate||0;return e>t?e:t},withData:function(e,t,n){return this.what.data={since:e,before:t,limit:n},this},withLaterData:function(e){return this.withData(this.topic._maxSeq>0?this.topic._maxSeq+1:void 0,void 0,e)},withEarlierData:function(e){return this.withData(void 0,this.topic._minSeq>0?this.topic._minSeq:void 0,e)},withDesc:function(e){return this.what.desc={ims:e},this},withLaterDesc:function(){return this.withDesc(this._get_ims())},withSub:function(e,t,n){var s={ims:e,limit:t};return"me"==this.topic.getType()?s.topic=n:s.user=n,this.what.sub=s,this},withOneSub:function(e,t){return this.withSub(e,void 0,t)},withLaterOneSub:function(e){return this.withOneSub(this.topic._lastSubsUpdate,e)},withLaterSub:function(e){return this.withSub("p2p"==this.topic.getType()?this._get_ims():this.topic._lastSubsUpdate,e)},withTags:function(){return this.what.tags=!0,this},withDel:function(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this},withLaterDel:function(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)},build:function(){var e={},t=[],n=this;return["data","sub","desc","tags","del"].map(function(s){n.what.hasOwnProperty(s)&&(t.push(s),Object.getOwnPropertyNames(n.what[s]).length>0&&(e[s]=n.what[s]))}),t.length>0?e.what=t.join(" "):e=void 0,e}};var T=function e(t){t&&(this.given="number"==typeof t.given?t.given:e.decode(t.given),this.want="number"==typeof t.want?t.want:e.decode(t.want),this.mode=t.mode?"number"==typeof t.mode?t.mode:e.decode(t.mode):this.given&this.want)};T._NONE=0,T._JOIN=1,T._READ=2,T._WRITE=4,T._PRES=8,T._APPROVE=16,T._SHARE=32,T._DELETE=64,T._OWNER=128,T._BITMASK=T._JOIN|T._READ|T._WRITE|T._PRES|T._APPROVE|T._SHARE|T._DELETE|T._OWNER,T._INVALID=1048576,T.decode=function(e){if(!e)return null;if("number"==typeof e)return e&T._BITMASK;if("N"===e||"n"===e)return T._NONE;for(var t={J:T._JOIN,R:T._READ,W:T._WRITE,P:T._PRES,A:T._APPROVE,S:T._SHARE,D:T._DELETE,O:T._OWNER},n=T._NONE,s=0;s0)){c=!0;break}r=o-1}return c?o:s?-1:a<0?o+1:o}function s(e,t){var s=n(e,t,!1);return t.splice(s,0,e),t}return e=e||function(e,t){return e===t?0:e0)return n[0]},delRange:function(e,n){return t.splice(e,n-e)},size:function(){return t.length},reset:function(e){t=[]},forEach:function(e,n,s,i){n|=0,s=s||t.length;for(var r=n;r=300)return e;if(n._subscribed=!0,n.acs=e.params&&e.params.acs?e.params.acs:n.acs,n._new){n._new=!1,n.name=e.topic,n.created=e.ts,n.updated=e.ts,n.touched=e.ts,n._cachePutSelf();var s=n._tinode.getMeTopic();s&&s._processMetaSub([{_generated:!0,topic:n.name,created:e.ts,updated:e.ts,touched:e.ts,acs:n.acs}]),t&&t.desc&&(t.desc._generated=!0,n._processMetaDesc(t.desc))}return e})},publish:function(e,t){return this.publishMessage(this.createMessage(e,t))},createMessage:function(e,t){return this._tinode.createMessage(this.name,e,t)},publishMessage:function(t){if(!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));if(e.hasAttachments(t.content)){var n=[];e.attachments(t.content,function(e){n.push(e.ref)}),t.head.attachments=n}return t._sending=!0,this._tinode.publishMessage(t)},publishDraft:function(e,t){var n=this;return t||this._subscribed?(e.seq=this._getQueuedSeqId(),e._generated=!0,e.ts=new Date,e.from=this._tinode.getCurrentUserID(),e.noecho=!0,this._messages.put(e),this.onData&&this.onData(e),(t||Promise.resolve()).then(function(){return e._cancelled?{code:300,text:"cancelled"}:n.publishMessage(e).then(function(t){return e._sending=!1,e.seq=t.params.seq,e.ts=t.ts,n._routeData(e),t})},function(t){e._sending=!1,n._messages.delAt(n._messages.find(e)),n.onData&&n.onData()})):Promise.reject(new Error("Cannot publish on inactive topic"))},leave:function(e){var t=this;return this._subscribed||e?this._tinode.leave(this.name,e).then(function(n){return t._resetSub(),e&&t._gone(),n}):Promise.reject(new Error("Cannot leave inactive topic"))},getMeta:function(e){return this._subscribed?this._tinode.getMeta(this.name,e):Promise.reject(new Error("Cannot query inactive topic"))},getMessagesPage:function(e,t){var n=this,s=this.startMetaQuery();t?s.withLaterData(e):s.withEarlierData(e);var i=this.getMeta(s.build());return t||(i=i.then(function(e){e&&e.params&&!e.params.count&&(n._noEarlierMsgs=!0)})),i},setMeta:function(e){var t=this;return this._subscribed?(e.tags&&(e.tags=function(e){var t=[];if(Array.isArray(e)){for(var n=0,s=e.length;n1&&t.push(i)}t.sort().filter(function(e,t,n){return!t||e!=n[t-1]})}return 0==t.length&&t.push(M.DEL_CHAR),t}(e.tags)),this._tinode.setMeta(this.name,e).then(function(n){return n&&n.code>=300?n:(e.sub&&(n.params&&n.params.acs&&(e.sub.acs=n.params.acs,e.sub.updated=n.ts),e.sub.user||(e.sub.user=t._tinode.getCurrentUserID(),e.desc||(e.desc={})),e.sub._generated=!0,t._processMetaSub([e.sub])),e.desc&&(n.params&&n.params.acs&&(e.desc.acs=n.params.acs,e.desc.updated=n.ts),t._processMetaDesc(e.desc)),e.tags&&t._processMetaTags(e.tags),n)})):Promise.reject(new Error("Cannot update inactive topic"))},invite:function(e,t){return this.setMeta({sub:{user:e,mode:t}})},delMessages:function(e,t){var n=this;if(!this._subscribed)return Promise.reject(new Error("Cannot delete messages in inactive topic"));e.sort(function(e,t){return e.low=t.hi)});var s=e.reduce(function(e,t){return t.low<268435455&&(!t.hi||t.hi<268435455?e.push(t):e.push({low:t.low,hi:n._maxSeq+1})),e},[]);return(e.length>0?this._tinode.delMessages(this.name,s,t):Promise.resolve({params:{del:0}})).then(function(t){return t.params.del>n._maxDel&&(n._maxDel=t.params.del),e.map(function(e){e.hi?n.flushMessageRange(e.low,e.hi):n.flushMessage(e.low)}),n.onData&&n.onData(),t})},delMessagesAll:function(e){return this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)},delMessagesList:function(e,t){e.sort(function(e,t){return e-t});var n=e.reduce(function(e,t){if(0==e.length)e.push({low:t});else{var n=e[e.length-1];!n.hi&&t!=n.low+1||t>n.hi?e.push({low:t}):n.hi=n.hi?Math.max(n.hi,t+1):t+1}return e},[]);return this.delMessages(n,t)},delTopic:function(){var e=this;return this._tinode.delTopic(this.name).then(function(t){return e._resetSub(),e._gone(),t})},delSubscription:function(e){var t=this;return this._subscribed?this._tinode.delSubscription(this.name,e).then(function(n){return delete t._users[e],t.onSubsUpdated&&t.onSubsUpdated(Object.keys(t._users)),n}):Promise.reject(new Error("Cannot delete subscription in inactive topic"))},note:function(e,t){var n=this._users[this._tinode.getCurrentUserID()];n?((!n[e]||n[e]0)for(var i in this._users){var r=this._users[i];r.user!==s&&r[e]>=t&&n++}return n},msgReadCount:function(e){return this.msgReceiptCount("read",e)},msgRecvCount:function(e){return this.msgReceiptCount("recv",e)},msgHasMoreMessages:function(e){return e?this.seq>this._maxSeq:this._minSeq>1&&!this._noEarlierMsgs},isNewMessage:function(e){return this._maxSeq<=e},flushMessage:function(e){var t=this._messages.find({seq:e});return t>=0?this._messages.delAt(t):void 0},flushMessageRange:function(e,t){var n=this._messages.find({seq:e});return n>=0?this._messages.delRange(n,this._messages.find({seq:t},!0)):[]},cancelSend:function(e){var t=this._messages.find({seq:e});if(t>=0){var n=this._messages.getAt(t);if(1==this.msgStatus(n))return n._cancelled=!0,this._messages.delAt(t),!0}return!1},getType:function(){return M.topicType(this.name)},getAccessMode:function(){return this.acs},getDefaultAccess:function(){return this.defacs},startMetaQuery:function(){return new S(this)},msgStatus:function(e){var t=0;return e.from==this._tinode.getCurrentUserID()?e._sending?t=2:e.seq>=268435455?t=1:this.msgReadCount(e.seq)>0?t=5:this.msgRecvCount(e.seq)>0?t=4:e.seq>0&&(t=3):t=6,t},_routeData:function(e){e.content&&((!this.touched||this.touchedthis._maxSeq&&(this._maxSeq=e.seq),(e.seq0&&(this._lastSubsUpdate=e.ts,this._processMetaSub(e.sub)),e.del&&this._processDelMessages(e.del.clear,e.del.delseq),e.tags&&this._processMetaTags(e.tags),this.onMeta&&this.onMeta(e)},_routePres:function(e){var t;switch(e.what){case"del":this._processDelMessages(e.clear,e.delseq);break;case"on":case"off":(t=this._users[e.src])?t.online="on"==e.what:this._tinode.logger("Presence update for an unknown user",this.name,e.src);break;case"acs":var n="me"==e.src?this._tinode.getCurrentUserID():e.src;if(t=this._users[n])t.acs.updateAll(e.dacs),n==this._tinode.getCurrentUserID()&&this.acs.updateAll(e.dacs),t.acs&&t.acs.mode!=T._NONE||("p2p"==this.getType()&&this.leave(),this._processMetaSub([{user:n,deleted:new Date,_generated:!0}]));else{var s=(new T).updateAll(e.dacs);s&&s.mode!=T._NONE&&((t=this._cacheGetUser(n))?t.acs=s:(t={user:n,acs:s},this.getMeta(this.startMetaQuery().withOneSub(void 0,n).build())),t._generated=!0,t.updated=new Date,this._processMetaSub([t]))}break;default:this._tinode.logger("Ignored presence update",e.what)}this.onPres&&this.onPres(e)},_routeInfo:function(e){if("kp"!==e.what){var t=this._users[e.from];t&&(t[e.what]=e.seq)}this.onInfo&&this.onInfo(e)},_processMetaDesc:function(e,t){if(p(this,e),"string"==typeof this.created&&(this.created=new Date(this.created)),"string"==typeof this.updated&&(this.updated=new Date(this.updated)),"string"==typeof this.touched&&(this.touched=new Date(this.touched)),"me"!==this.name&&!t&&!e._generated){var n=this._tinode.getMeTopic();n&&n._processMetaSub([{_generated:!0,topic:this.name,updated:this.updated,touched:this.touched,acs:this.acs,public:this.public,private:this.private}])}this.onMetaDesc&&this.onMetaDesc(this)},_processMetaSub:function(e){var t=void 0;for(var n in e){var s=e[n];if(s.user){s.updated=new Date(s.updated),s.deleted=s.deleted?new Date(s.deleted):null;var i=null;s.deleted?(delete this._users[s.user],i=s):((i=this._users[s.user])||(i=this._cacheGetUser(s.user)),i=this._updateCachedUser(s.user,s,s._generated)),this.onMetaSub&&this.onMetaSub(i)}else s._generated||(t=s)}t&&this.onMetaDesc&&this.onMetaDesc(t),this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users))},_processMetaTags:function(e){1==e.length&&e[0]==M.DEL_CHAR&&(e=[]),this._tags=e,this.onTagsUpdated&&this.onTagsUpdated(e)},_processDelMessages:function(e,t){this._maxDel=Math.max(e,this._maxDel),this.clear=Math.max(e,this.clear);var n=this,s=0;Array.isArray(t)&&t.map(function(e){if(e.hi)for(var t=e.low;t0&&this.onData&&this.onData()},_allMessagesReceived:function(e){this.onAllMessagesReceived&&this.onAllMessagesReceived(e)},_resetSub:function(){this._subscribed=!1},_gone:function(){this._messages.reset(),this._users={},this.acs=new T(null),this.private=null,this.public=null,this._maxSeq=0,this._minSeq=0,this._subscribed=!1;var e=this._tinode.getMeTopic();e&&e._routePres({_generated:!0,what:"gone",topic:"me",src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()},_updateCachedUser:function(e,t,n){var s=this._cacheGetUser(e);return s?s=p(s,t):(n&&this.getMeta(this.startMetaQuery().withLaterOneSub(e).build()),s=p({},t)),this._cachePutUser(e,s),g(this._users,e,s)},_getQueuedSeqId:function(){return this._queuedSeqId++}};var D=function(e){y.call(this,"me",e),this._contacts={},e&&(this.onContactUpdate=e.onContactUpdate)};D.prototype=Object.create(y.prototype,{_processMetaSub:{value:function(e){var t=0;for(var n in e){var s=e[n],i=s.topic;if("fnd"!=i&&"me"!=i){s.updated=new Date(s.updated),s.touched=s.touched?new Date(s.touched):null,s.deleted=s.deleted?new Date(s.deleted):null,s.seq=0|s.seq,s.recv=0|s.recv,s.read=0|s.read,s.unread=s.seq-s.read;var r=null;if(s.deleted)r=s,delete this._contacts[i];else if(s.seen&&s.seen.when&&(s.seen.when=new Date(s.seen.when)),r=g(this._contacts,i,s),"p2p"==M.topicType(i)&&this._cachePutUser(i,r),!s._generated){var o=this._tinode.getTopic(i);o&&o._processMetaDesc(s,!0)}t++,this.onMetaSub&&this.onMetaSub(r)}}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))},enumerable:!0,configurable:!0,writable:!1},_routePres:{value:function(e){var t=this._contacts[e.src];if(t){switch(e.what){case"on":t.online=!0;break;case"off":t.online&&(t.online=!1,t.seen?t.seen.when=new Date:t.seen={when:new Date});break;case"msg":t.touched=new Date,t.seq=0|e.seq,t.unread=t.seq-t.read;break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":t.acs?t.acs.updateAll(e.dacs):t.acs=(new T).updateAll(e.dacs);break;case"ua":t.seen={when:new Date,ua:e.ua};break;case"recv":t.recv=t.recv?Math.max(t.recv,e.seq):0|e.seq;break;case"read":t.read=t.read?Math.max(t.read,e.seq):0|e.seq,t.unread=t.seq-t.read;break;case"gone":delete this._contacts[e.src]}this.onContactUpdate&&this.onContactUpdate(e.what,t)}else if("acs"==e.what){var n=new T(e.dacs);if(!n||n.mode==T._INVALID)return void this._tinode.logger("Invalid access mode update",e.src,e.dacs);if(n.mode==T._NONE)return void this._tinode.logger("Removing non-existent subscription",e.src,e.dacs);this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build()),this._contacts[e.src]={topic:e.src,online:!1,acs:n}}this.onPres&&this.onPres(e)},enumerable:!0,configurable:!0,writable:!1},publish:{value:function(){return Promise.reject(new Error("Publishing to 'me' is not supported"))},enumerable:!0,configurable:!0,writable:!1},contacts:{value:function(e,t){var n=e||this.onMetaSub;if(n)for(var s in this._contacts)n.call(t,this._contacts[s],s,this._contacts)},enumerable:!0,configurable:!0,writable:!0},setMsgReadRecv:{value:function(e,t,n,s){var i,r=this._contacts[e],o=!1;r&&(n|=0,"recv"===t?(i=r.recv,r.recv=r.recv?Math.max(r.recv,n):n,o=i!=r.recv):"read"===t?(i=r.read,r.read=r.read?Math.max(r.read,n):n,r.unread=r.seq-r.read,o=i!=r.read,r.recv0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))},enumerable:!0,configurable:!0,writable:!1},publish:{value:function(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))},enumerable:!0,configurable:!0,writable:!1},setMeta:{value:function(e){var t=this;return Object.getPrototypeOf(E.prototype).setMeta.call(this,e).then(function(){Object.keys(t._contacts).length>0&&(t._contacts={},t.onSubsUpdated&&t.onSubsUpdated([]))})},enumerable:!0,configurable:!0,writable:!1},contacts:{value:function(e,t){var n=e||this.onMetaSub;if(n)for(var s in this._contacts)n.call(t,this._contacts[s],s,this._contacts)},enumerable:!0,configurable:!0,writable:!0}}),E.prototype.constructor=E;var x=function(e){this._tinode=e,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this._msgId=e.getNextUniqueId(),this.xhr=_(),this.toResolve=null,this.toReject=null,this.onProgress=null,this.onSuccess=null,this.onFailure=null};x.prototype={upload:function(e,t,n,s){var i=this;if(!this._authToken)throw new Error("Must authenticate first");var r=this;this.xhr.open("POST","/v"+h+"/file/u/",!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token);var o=new Promise(function(e,t){i.toResolve=e,i.toReject=t});this.onProgress=t,this.onSuccess=n,this.onFailure=s,this.xhr.upload.onprogress=function(e){e.lengthComputable&&r.onProgress&&r.onProgress(e.loaded/e.total)},this.xhr.onload=function(){var e;try{e=JSON.parse(this.response,v)}catch(e){r._tinode.logger("Invalid server response in LargeFileHelper",this.response)}this.status>=200&&this.status<300?(r.toResolve&&r.toResolve(e.ctrl.params.url),r.onSuccess&&r.onSuccess(e.ctrl)):this.status>=400?(r.toReject&&r.toReject(new Error(e.ctrl.text+" ("+e.ctrl.code+")")),r.onFailure&&r.onFailure(e.ctrl)):r._tinode.logger("Unexpected server response status",this.status,this.response)},this.xhr.onerror=function(e){r.toReject&&r.toReject(new Error("failed")),r.onFailure&&r.onFailure(null)},this.xhr.onabort=function(e){r.toReject&&r.toReject(new Error("upload cancelled by user")),r.onFailure&&r.onFailure(null)};try{var a=new FormData;a.append("file",e),a.set("id",this._msgId),this.xhr.send(a)}catch(e){this.toReject&&this.toReject(e),this.onFailure&&this.onFailure(null)}return o},download:function(e,t,n,s){var i=this;if(/^(?:(?:[a-z]+:)?\/\/)/i.test(e))throw new Error("The URL '"+e+"' must be relative, not absolute");if(!this._authToken)throw new Error("Must authenticate first");var r=this;this.xhr.open("GET",e,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),this.xhr.responseType="blob",this.onProgress=s,this.xhr.onprogress=function(e){r.onProgress&&r.onProgress(e.loaded)};var o=new Promise(function(e,t){i.toResolve=e,i.toReject=t});this.xhr.onload=function(){if(200==this.status){var e=document.createElement("a");e.href=window.URL.createObjectURL(new Blob([this.response],{type:n})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),r.toResolve&&r.toResolve()}else if(this.status>=400&&r.toReject){var s=new FileReader;s.onload=function(){try{var e=JSON.parse(this.result,v);r.toReject(new Error(e.ctrl.text+" ("+e.ctrl.code+")"))}catch(e){r._tinode.logger("Invalid server response in LargeFileHelper",this.result),r.toReject(e)}},s.readAsText(this.response)}},this.xhr.onerror=function(e){r.toReject&&r.toReject(new Error("failed"))},this.xhr.onabort=function(){r.toReject&&r.toReject(null)};try{this.xhr.send()}catch(e){this.toReject&&this.toReject(e)}return o},cancel:function(){this.xhr&&this.xhr.readyState<4&&this.xhr.abort()},getId:function(){return this._msgId}};var R=function e(t,n){this.status=e.STATUS_NONE,this.topic=t,this.content=n};return R.STATUS_NONE=0,R.STATUS_QUEUED=1,R.STATUS_SENDING=2,R.STATUS_SENT=3,R.STATUS_RECEIVED=4,R.STATUS_READ=5,R.STATUS_TO_ME=6,(R.prototype={toJSON:function(){},fromJSON:function(e){}}).constructor=R,(a=M).Drafty=e,a}); +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Tinode=e()}}(function(){var e={},t=[{name:"ST",start:/(?:^|\W)(\*)[^\s*]/,end:/[^\s*](\*)(?=$|\W)/},{name:"EM",start:/(?:^|[\W_])(_)[^\s_]/,end:/[^\s_](_)(?=$|[\W_])/},{name:"DL",start:/(?:^|\W)(~)[^\s~]/,end:/[^\s~](~)(?=$|\W)/},{name:"CO",start:/(?:^|\W)(`)[^`]/,end:/[^`](`)(?=$|\W)/}],n=[{name:"LN",dataName:"url",pack:function(e){return/^[a-z]+:\/\//i.test(e)||(e="http://"+e),{url:e}},re:/(https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b(?:[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/g},{name:"MN",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B@(\w\w+)/g},{name:"HT",dataName:"val",pack:function(e){return{val:e.slice(1)}},re:/\B#(\w\w+)/g}],s={ST:{name:"b",isVoid:!1},EM:{name:"i",isVoid:!1},DL:{name:"del",isVoid:!1},CO:{name:"tt",isVoid:!1},BR:{name:"br",isVoid:!0},LN:{name:"a",isVoid:!1},MN:{name:"a",isVoid:!1},HT:{name:"a",isVoid:!1},IM:{name:"img",isVoid:!0}};function i(e,t){var n;try{n=atob(e)}catch(e){console.log("Drafty: failed to decode base64-encoded object",e.message),n=atob("")}for(var s=n.length,i=new ArrayBuffer(s),r=new Uint8Array(i),o=0;o"},close:function(){return""}},EM:{open:function(){return""},close:function(){return""}},DL:{open:function(){return""},close:function(){return""}},CO:{open:function(){return""},close:function(){return""}},BR:{open:function(){return""},close:function(){return"
"}},LN:{open:function(e){return''},close:function(e){return""},props:function(e){return{href:e.url,target:"_blank"}}},MN:{open:function(e){return''},close:function(e){return""},props:function(e){return{name:e.val}}},HT:{open:function(e){return''},close:function(e){return""},props:function(e){return{name:e.val}}},IM:{open:function(e){var t=i(e.val,e.mime),n=e.ref?e.ref:t,s=(e.name?'':"")+'';return console.log("open: "+s),s},close:function(e){return e.name?"":""},props:function(e){return{src:i(e.val,e.mime),title:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":.75*e.val.length|0,"data-mime":e.mime}}}},o=function(){};o.parse=function(e){if("string"!=typeof e)return null;var s=e.split(/\r?\n/),i=[],r={},o=[];s.map(function(e){var s,a,c=[];if(t.map(function(t){c=c.concat(function(e,t,n,s){for(var i=[],r=0,o=e.slice(0);o.length>0;){var a=t.exec(o);if(null==a)break;var c=a.index+a[0].lastIndexOf(a[1]);o=o.slice(c+1),r=(c+=r)+1;var u=n?n.exec(o):null;if(null==u)break;var h=u.index+u[0].indexOf(u[1]);o=o.slice(h+1),r=(h+=r)+1,i.push({text:e.slice(c+1,h),children:[],start:c,end:h,type:s})}return i}(e,t.start,t.end,t.name))}),0==c.length)a={txt:e};else{c.sort(function(e,t){return e.start-t.start}),c=function e(t){if(0==t.length)return[];for(var n=[t[0]],s=t[0],i=1;is.end?(n.push(t[i]),s=t[i]):t[i].endn&&r.push({text:t.slice(n,a.start)});var c={type:a.type},u=e(t,a.start+1,a.end-1,a.children);u.length>0?c.children=u:c.text=a.text,r.push(c),n=a.end+1}return ni;return i=e.offset+e.len,t})}(a.txt)).length>0){var h=[];for(var l in s){var d=s[l],f=r[d.unique];f||(f=i.length,r[d.unique]=f,i.push({tp:d.type,data:d.data})),h.push({at:d.offset,len:d.len,key:f})}a.ent=h}o.push(a)});var a={txt:""};if(o.length>0){a.txt=o[0].txt,a.fmt=(o[0].fmt||[]).concat(o[0].ent||[]);for(var c=1;c0&&(a.ent=i)}return a},o.insertImage=function(e,t,n,s,i,r,o,a,c){return(e=e||{txt:" "}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:t,len:1,key:e.ent.length}),e.ent.push({tp:"IM",data:{mime:n,val:s,width:i,height:r,name:o,ref:c,size:0|a}}),e},o.attachFile=function(e,t,n,s,i,r){(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length});var o={tp:"EX",data:{mime:t,val:n,name:s,ref:r,size:0|i}};return r instanceof Promise&&(o.data.ref=r.then(function(e){o.data.ref=e},function(e){})),e.ent.push(o),e},o.UNSAFE_toHTML=function(e){var t,n,s,i=e.txt,o=e.fmt,a=e.ent,c=[];if(o)for(var u in o){var h,l=o[u],d=l.tp;if(!d){var f=a[l.key];f&&(d=f.tp,h=f.data)}r[d]&&(c.push({idx:l.at+l.len,what:r[d].close(h)}),c.push({idx:l.at,what:r[d].open(h)}))}for(var u in c.sort(function(e,t){return t.idx-e.idx}),c)c[u].what&&(t=i,n=c[u].idx,s=c[u].what,i=t.slice(0,n)+s+t.slice(n));return i},o.format=function(e,t,n){var i=e.txt,r=e.fmt,o=e.ent;if(i=i||"",!r)return[i];var a=[].concat(r);return a.map(function(e){e.at=e.at||0,e.len=e.len||0}),a.sort(function(e,t){return e.at-t.at==0?t.len-e.len:e.at-t.at}),a=a.map(function(e){var t,n=e.tp;return n||(e.key=e.key||0,t=o[e.key].data,n=o[e.key].tp),{tp:n,data:t,at:e.at,len:e.len}}),function e(t,n,i,r,o,a){for(var c=[],u=0;u0)for(var t in e.ent)if("EX"==e.ent[t].tp)return!0;return!1},o.attachments=function(e,t,n){if(e.ent&&e.ent.length>0)for(var s in e.ent)"EX"==e.ent[s].tp&&t.call(n,e.ent[s].data,s)},o.getDownloadUrl=function(e){var t=null;return e.val?t=i(e.val,e.mime):"string"==typeof e.ref&&(t=e.ref),t},o.isUploading=function(e){return e.ref instanceof Promise},o.getPreviewUrl=function(e){return e.val?i(e.val,e.mime):null},o.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},o.getEntityMimeType=function(e){return e.mime||"text/plain"},o.tagName=function(e){return s[e]?s[e].name:void 0},o.attrValue=function(e,t){if(t&&r[e])return r[e].props(t)},o.getContentType=function(){return"text/x-drafty"},e=o;var a="0.15.7-rc5",c={};return function(t){"use strict";function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}if("function"==typeof require)var s=a;var i;"undefined"!=typeof WebSocket&&(i=WebSocket),"undefined"==typeof btoa&&(t.btoa=function(){for(var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n="",s=0,i=0,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.charAt(0|i)||(r="=",i%1);n+=r.charAt(63&s>>8-i%1*8)){if((e=t.charCodeAt(i+=.75))>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");s=s<<8|e}return n}),"undefined"==typeof atob&&(t.atob=function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").replace(/=+$/,""),t="";if(e.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,s=0,i=0,r=0;n=e.charAt(r++);~n&&(i=s%4?64*i+n:n,s++%4)?t+=String.fromCharCode(255&i>>(-2*s&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return t}),"undefined"==typeof window&&(t.window={WebSocket:i,URL:{createObjectURL:function(){throw new Error("Unable to use window.URL in a non browser application")}}});var r="0",o=s||"0.15",u="tinodejs/"+o,h=503,l="Connection failed";function d(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)}))}function f(e,t,s){if(null==t)return e;if("object"!==n(t))return t||e;if(t instanceof Date)return t;if(t instanceof M)return new M(t);if(t instanceof Array)return t.length>0?t:e;for(var i in e||(e=t.constructor()),t)!t.hasOwnProperty(i)||!t[i]&&!1!==t[i]||s&&s[i]||"_generated"==i||(e[i]=f(e[i],t[i]));return e}function p(e,t,n,s){return e[t]=f(e[t],n,s),e[t]}function g(){var e=null;if("withCredentials"in new XMLHttpRequest)e=new XMLHttpRequest;else{if("undefined"==typeof XDomainRequest)throw new Error("browser not supported");e=new XDomainRequest}return e}function _(e,t){if("ts"===e&&"string"==typeof t&&t.length>=20&&t.length<=24){var s=new Date(t);if(s)return s}else if("acs"===e&&"object"===n(t))return new M(t);return t}function v(e,t){return"string"==typeof t&&t.length>128?"<"+t.length+", bytes: "+t.substring(0,12)+"..."+t.substring(t.length-12)+">":function(e,t){if(t instanceof Date)t=function(e){if(e&&0!=e.getTime()){var t=e.getUTCMilliseconds();return e.getUTCFullYear()+"-"+n(e.getUTCMonth()+1)+"-"+n(e.getUTCDate())+"T"+n(e.getUTCHours())+":"+n(e.getUTCMinutes())+":"+n(e.getUTCSeconds())+(t?"."+n(t,3):"")+"Z"}function n(e,t){return"0".repeat((t=t||2)-(""+e).length)+e}}(t);else if(null==t||!1===t||Array.isArray(t)&&0==t.length||"object"===n(t)&&0===Object.keys(t).length)return;return t}(0,t)}function m(e,t,n){var s=null;return"http"!==t&&"https"!==t&&"ws"!==t&&"wss"!==t||(s=t+"://","/"!==(s+=e).charAt(s.length-1)&&(s+="/"),s+="v"+r+"/channels","http"!==t&&"https"!==t||(s+="/lp"),s+="?apikey="+n),s}var b=function(e,t,s,r,o){var a=this,c=e,u=r,d=t,f=o,p=2e3,v=10,b=.3,w=null,S=0,M=!1,T=function(e){a.logger&&a.logger(e)};function y(e){var t=null;e.connect=function(n){return t&&1===t.readyState?Promise.resolve():(n&&(c=n),new Promise(function(n,s){var r=m(c,u?"wss":"ws",d);T("Connecting to: "+r);var o=new i(r);o.onopen=function(t){M=!1,e.onOpen&&e.onOpen(),n(),f&&(clearTimeout(w),w=null,S=0)},o.onclose=function(n){t=null,e.onDisconnect&&e.onDisconnect(null),!M&&f&&function(){var e=this;clearTimeout(w);var t=p*(Math.pow(2,S)*(1+b*Math.random()));S=S>=v?S:S+1,w=setTimeout(function(){T("Reconnecting, iter="+S+", timeout="+t),M||e.connect().catch(function(){})},t)}.call(e)},o.onerror=function(e){s(e)},o.onmessage=function(t){e.onMessage&&e.onMessage(t.data)},t=o}))},e.disconnect=function(){t&&(M=!0,t.close()),t=null},e.sendText=function(e){if(!t||t.readyState!=t.OPEN)throw new Error("Websocket is not connected");t.send(e)},e.isConnected=function(){return t&&1===t.readyState},e.transport=function(){return"ws"}}function D(e){var t=null,n=null,s=null;e.connect=function(s){return n?Promise.resolve():(s&&(c=s),new Promise(function(s,i){var r=m(c,u?"https":"http",d);T("Connecting to: "+r),(n=function n(s,i,r){var o=g();return o.onreadystatechange=function(a){if(4==o.readyState)if(201==o.status){var c=JSON.parse(o.responseText,_);o.responseText,t=s+"&sid="+c.ctrl.params.sid,(o=n(t)).send(null),e.onOpen&&e.onOpen(),i&&i()}else if(200==o.status)e.onMessage&&e.onMessage(o.responseText),(o=n(t)).send(null);else if(r&&r(o.responseText),e.onMessage&&o.responseText&&e.onMessage(o.responseText),e.onDisconnect){var u=o.status||h,d=o.responseText||l;e.onDisconnect(new Error(d+"("+u+")"))}},o.open("GET",s,!0),o}(r,s,i)).send(null)}).catch(function(){}))},e.disconnect=function(){s&&(s.onreadystatechange=void 0,s.abort(),s=null),n&&(n.onreadystatechange=void 0,n.abort(),n=null),e.onDisconnect&&e.onDisconnect(null),t=null},e.sendText=function(e){var n,i;if(n=t,(i=g()).onreadystatechange=function(e){if(4==i.readyState&&i.status>=400)throw new Error("LP sender failed, "+i.status)},i.open("POST",n,!0),!(s=i)||1!=s.readyState)throw new Error("Long poller failed to connect");s.send(e)},e.isConnected=function(){return n&&!0},e.transport=function(){return"lp"}}"lp"===s?D(this):"ws"===s?y(this):"object"==("undefined"==typeof window?"undefined":n(window))&&window.WebSocket?y(this):D(this),this.onMessage=void 0,this.onDisconnect=void 0,this.onOpen=void 0,this.logger=void 0},w=function(e,t,s,i,r){var a=this;this._appName=e||"Undefined",this._apiKey=s,this._browser="",this._platform="undefined",this._humanLanguage="xx","undefined"!=typeof navigator&&(this._browser=function(e){var t,n=(e=(e||"").replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(n){for(var s=["chrome","safari","mobile","version"],i=e.substr(n.index+n[0].length).split(" "),r=[],o=0;o0?r[0][0]+"/"+r[0][1]:n[1]}else t=/trident/i.test(e)?(n=/(?:\brv[ :]+([.\d]+))|(?:\bMSIE ([.\d]+))/g.exec(e))?"MSIE/"+(n[1]||n[2]):"MSIE/?":/firefox/i.test(e)?(n=/Firefox\/([.\d]+)/g.exec(e))?"Firefox/"+n[1]:"Firefox/?":/presto/i.test(e)?(n=/Opera\/([.\d]+)/g.exec(e))?"Opera/"+n[1]:"Opera/?":(n=/([\w.]+)\/([.\d]+)/.exec(e))?n[1]+"/"+n[2]:(n=e.split(" "))[0];if((n=t.split("/")).length>1){var c=n[1].split(".");t=n[0]+"/"+c[0]+(c[1]?"."+c[1]:"")}return t}(navigator.userAgent),this._platform=navigator.platform,this._humanLanguage=navigator.language||"en-US"),this._loggingEnabled=!1,this._trimLongStrings=!1,this._myUID=null,this._authenticated=!1,this._login=null,this._authToken=null,this._inPacketCount=0,this._messageId=Math.floor(65535*Math.random()+65535),this._serverInfo=null,this._deviceToken=null,this._pendingPromises={},this._connection=new b(t,s,i,r,!0),this.logger=function(e){if(a._loggingEnabled){var t=new Date,n=("0"+t.getUTCHours()).slice(-2)+":"+("0"+t.getUTCMinutes()).slice(-2)+":"+("0"+t.getUTCSeconds()).slice(-2)+":"+("0"+t.getUTCMilliseconds()).slice(-3);console.log("["+n+"] "+e)}},this._connection.logger=this.logger,this._cache={};var c=this.cachePut=function(e,t,n){a._cache[e+":"+t]=n},l=this.cacheGet=function(e,t){return a._cache[e+":"+t]},d=this.cacheDel=function(e,t){delete a._cache[e+":"+t]},p=this.cacheMap=function(e,t){for(var n in a._cache)if(e(a._cache[n],n,t))break};this.attachCacheToTopic=function(e){e._tinode=a,e._cacheGetUser=function(e){var t=l("user",e);if(t)return{user:e,public:f({},t)}},e._cachePutUser=function(e,t){return c("user",e,f({},t.public))},e._cacheDelUser=function(e){return d("user",e)},e._cachePutSelf=function(){return c("topic",e.name,e)},e._cacheDelSelf=function(){return d("topic",e.name)}};var g=function(e,t,n,s){var i=a._pendingPromises[e];i&&(delete a._pendingPromises[e],t>=200&&t<400?i.resolve&&i.resolve(n):i.reject&&i.reject(new Error("Error: "+s+" ("+t+")")))},m=this.getNextUniqueId=function(){return 0!=a._messageId?""+a._messageId++:void 0};this.initPacket=function(e,t){switch(e){case"hi":return{hi:{id:m(),ver:o,ua:a._appName+" ("+(a._browser?a._browser+"; ":"")+a._platform+"); "+u,dev:a._deviceToken,lang:a._humanLanguage}};case"acc":return{acc:{id:m(),user:null,scheme:null,secret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:m(),scheme:null,secret:null}};case"sub":return{sub:{id:m(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:m(),topic:t,unsub:!1}};case"pub":return{pub:{id:m(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:m(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:m(),topic:t,desc:{},sub:{},tags:[]}};case"del":return{del:{id:m(),topic:t,what:null,delseq:null,user:null,hard:!1}};case"note":return{note:{topic:t,what:null,seq:void 0}};default:throw new Error("Unknown packet type requested: "+e)}},this.send=function(e,t){var s;t&&(s=function(e){var t=null;return e&&(t=new Promise(function(t,n){a._pendingPromises[e]={resolve:t,reject:n}})),t}(t)),e=function e(t){return Object.keys(t).forEach(function(s){"_"==s[0]?delete t[s]:t[s]?Array.isArray(t[s])&&0==t[s].length?delete t[s]:t[s]?"object"!=n(t[s])||t[s]instanceof Date||(e(t[s]),0==Object.getOwnPropertyNames(t[s]).length&&delete t[s]):delete t[s]:delete t[s]}),t}(e);var i=JSON.stringify(e);a.logger("out: "+(a._trimLongStrings?JSON.stringify(e,v):i));try{a._connection.sendText(i)}catch(e){if(!t)throw e;g(t,h,null,e.message)}return s},this.loginSuccessful=function(e){e.params&&e.params.user&&(a._myUID=e.params.user,a._authenticated=e&&e.code>=200&&e.code<300,e.params&&e.params.token&&e.params.expires?a._authToken={token:e.params.token,expires:new Date(e.params.expires)}:a._authToken=null,a.onLogin&&a.onLogin(e.code,e.text))},this._connection.onMessage=function(e){if(e){a._inPacketCount++,a.onRawMessage&&a.onRawMessage(e);var t=JSON.parse(e,_);if(t)if(a.logger("in: "+(a._trimLongStrings?JSON.stringify(t,v):e)),a.onMessage&&a.onMessage(t),t.ctrl)a.onCtrlMessage&&a.onCtrlMessage(t.ctrl),t.ctrl.id&&g(t.ctrl.id,t.ctrl.code,t.ctrl,t.ctrl.text),t.ctrl.params&&"data"==t.ctrl.params.what&&(n=l("topic",t.ctrl.topic))&&n._allMessagesReceived(t.ctrl.params.count);else if(t.meta)(n=l("topic",t.meta.topic))&&n._routeMeta(t.meta),a.onMetaMessage&&a.onMetaMessage(t.meta);else if(t.data)(n=l("topic",t.data.topic))&&n._routeData(t.data),a.onDataMessage&&a.onDataMessage(t.data);else if(t.pres)(n=l("topic",t.pres.topic))&&n._routePres(t.pres),a.onPresMessage&&a.onPresMessage(t.pres);else if(t.info){var n;(n=l("topic",t.info.topic))&&n._routeInfo(t.info),a.onInfoMessage&&a.onInfoMessage(t.info)}else a.logger("ERROR: Unknown packet received.");else a.logger("in: "+e),a.logger("ERROR: failed to parse data")}},this._connection.onOpen=function(){a.hello()},this._connection.onDisconnect=function(e){a._inPacketCount=0,a._serverInfo=null,a._authenticated=!1,p(function(e,t){0===t.lastIndexOf("topic:",0)&&e._resetSub()}),a.onDisconnect&&a.onDisconnect(e)}};w.credential=function(e,t,s,i){if("object"==n(e)){var r=e;t=r.val,s=r.params,i=r.resp,e=r.meth}return e&&(t||i)?[{meth:e,val:t,resp:i,params:s}]:null},w.topicType=function(e){return{me:"me",fnd:"fnd",grp:"grp",new:"grp",usr:"p2p"}["string"==typeof e?e.substring(0,3):"xxx"]},w.isNewGroupTopicName=function(e){return"string"==typeof e&&"new"==e.substring(0,3)},w.getVersion=function(){return o},w.setWebSocketProvider=function(e){i=e},w.getLibrary=function(){return u},w.MESSAGE_STATUS_NONE=0,w.MESSAGE_STATUS_QUEUED=1,w.MESSAGE_STATUS_SENDING=2,w.MESSAGE_STATUS_FAILED=3,w.MESSAGE_STATUS_SENT=4,w.MESSAGE_STATUS_RECEIVED=5,w.MESSAGE_STATUS_READ=6,w.MESSAGE_STATUS_TO_ME=7,w.DEL_CHAR="\u2421",w.prototype={connect:function(e){return this._connection.connect(e)},disconnect:function(){this._connection&&this._connection.disconnect()},isConnected:function(){return this._connection&&this._connection.isConnected()},isAuthenticated:function(){return this._authenticated},account:function(e,t,n,s,i){var r=this.initPacket("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=n,r.acc.login=s,i&&(r.acc.desc.defacs=i.defacs,r.acc.desc.public=i.public,r.acc.desc.private=i.private,r.acc.tags=i.tags,r.acc.cred=i.cred,r.acc.token=i.token),this.send(r,r.acc.id)},createAccount:function(e,t,n,s){var i=this,r=this.account("new",e,t,n,s);return n&&(r=r.then(function(e){return i.loginSuccessful(e),e})),r},createAccountBasic:function(e,t,n){return e=e||"",t=t||"",this.createAccount("basic",d(e+":"+t),!0,n)},updateAccountBasic:function(e,t,n,s){return t=t||"",n=n||"",this.account(e,"basic",d(t+":"+n),!1,s)},hello:function(){var e=this,t=this.initPacket("hi");return this.send(t,t.hi.id).then(function(t){return t.params&&(e._serverInfo=t.params),e.onConnect&&e.onConnect(),t}).catch(function(t){e.onDisconnect&&e.onDisconnect(t)})},setDeviceToken:function(e,t){var n=!1;return e&&e!=this._deviceToken&&(this._deviceToken=e,t&&this.isConnected()&&this.isAuthenticated()&&(this.send({hi:{dev:e}}),n=!0)),n},login:function(e,t,n){var s=this,i=this.initPacket("login");return i.login.scheme=e,i.login.secret=t,i.login.cred=n,this.send(i,i.login.id).then(function(e){return s.loginSuccessful(e),e})},loginBasic:function(e,t,n){var s=this;return this.login("basic",d(e+":"+t),n).then(function(t){return s._login=e,t})},loginToken:function(e,t){return this.login("token",e,t)},requestResetAuthSecret:function(e,t,n){return this.login("reset",d(e+":"+t+":"+n))},getAuthToken:function(){return this._authToken&&this._authToken.expires.getTime()>Date.now()?this._authToken:(this._authToken=null,null)},setAuthToken:function(e){this._authToken=e},subscribe:function(e,t,n){var s=this.initPacket("sub",e);return e||(e="new"),s.sub.get=t,n&&(n.sub&&(s.sub.set.sub=n.sub),w.isNewGroupTopicName(e)&&n.desc&&(s.sub.set.desc=n.desc),n.tags&&(s.sub.set.tags=n.tags)),this.send(s,s.sub.id)},leave:function(e,t){var n=this.initPacket("leave",e);return n.leave.unsub=t,this.send(n,n.leave.id)},createMessage:function(t,n,s){var i=this.initPacket("pub",t),r="string"==typeof n?e.parse(n):n;return r&&!e.isPlainText(r)&&(i.pub.head={mime:e.getContentType()},n=r),i.pub.noecho=s,i.pub.content=n,i.pub},publish:function(e,t,n){return this.publishMessage(this.createMessage(e,t,n))},publishMessage:function(e){return(e=Object.assign({},e)).seq=void 0,e.from=void 0,e.ts=void 0,this.send({pub:e},e.id)},getMeta:function(e,t){var n=this.initPacket("get",e);return n.get=f(n.get,t),this.send(n,n.get.id)},setMeta:function(e,t){var n=this.initPacket("set",e),s=[];return t&&["desc","sub","tags"].map(function(e){t.hasOwnProperty(e)&&(s.push(e),n.set[e]=t[e])}),0==s.length?Promise.reject(new Error("Invalid {set} parameters")):this.send(n,n.set.id)},delMessages:function(e,t,n){var s=this.initPacket("del",e);return s.del.what="msg",s.del.delseq=t,s.del.hard=n,this.send(s,s.del.id)},delTopic:function(e){var t=this,n=this.initPacket("del",e);return n.del.what="topic",this.send(n,n.del.id).then(function(n){return t.cacheDel("topic",e),t.ctrl})},delSubscription:function(e,t){var n=this.initPacket("del",e);return n.del.what="sub",n.del.user=t,this.send(n,n.del.id)},note:function(e,t,n){if(n<=0||n>=268435455)throw new Error("Invalid message id "+n);var s=this.initPacket("note",e);s.note.what=t,s.note.seq=n,this.send(s)},noteKeyPress:function(e){var t=this.initPacket("note",e);t.note.what="kp",this.send(t)},getTopic:function(e){var t=this.cacheGet("topic",e);return!t&&e&&(t="me"==e?new y:"fnd"==e?new D:new T(e),this.cachePut("topic",e,t),this.attachCacheToTopic(t)),t},newTopic:function(e){var t=new T("new",e);return this.attachCacheToTopic(t),t},newGroupTopicName:function(){return"new"+this.getNextUniqueId()},newTopicWith:function(e,t){var n=new T(e,t);return this.attachCacheToTopic(n),n},getMeTopic:function(){return this.getTopic("me")},getFndTopic:function(){return this.getTopic("fnd")},getLargeFileHelper:function(){return new E(this)},getCurrentUserID:function(){return this._myUID},getCurrentLogin:function(){return this._login},getServerInfo:function(){return this._serverInfo},enableLogging:function(e,t){this._loggingEnabled=e,this._trimLongStrings=e&&t},isTopicOnline:function(e){var t=this.getMeTopic(),n=t&&t.getContact(e);return n&&n.online},wantAkn:function(e){this._messageId=e?Math.floor(16777215*Math.random()+16777215):0},onWebsocketOpen:void 0,onConnect:void 0,onDisconnect:void 0,onLogin:void 0,onCtrlMessage:void 0,onDataMessage:void 0,onPresMessage:void 0,onMessage:void 0,onRawMessage:void 0};var S=function(e){this.topic=e;var t=e._tinode.getMeTopic();this.contact=t&&t.getContact(e.name),this.what={}};S.prototype={_get_ims:function(){var e=this.contact&&this.contact.updated,t=this.topic._lastDescUpdate||0;return e>t?e:t},withData:function(e,t,n){return this.what.data={since:e,before:t,limit:n},this},withLaterData:function(e){return this.withData(this.topic._maxSeq>0?this.topic._maxSeq+1:void 0,void 0,e)},withEarlierData:function(e){return this.withData(void 0,this.topic._minSeq>0?this.topic._minSeq:void 0,e)},withDesc:function(e){return this.what.desc={ims:e},this},withLaterDesc:function(){return this.withDesc(this._get_ims())},withSub:function(e,t,n){var s={ims:e,limit:t};return"me"==this.topic.getType()?s.topic=n:s.user=n,this.what.sub=s,this},withOneSub:function(e,t){return this.withSub(e,void 0,t)},withLaterOneSub:function(e){return this.withOneSub(this.topic._lastSubsUpdate,e)},withLaterSub:function(e){return this.withSub("p2p"==this.topic.getType()?this._get_ims():this.topic._lastSubsUpdate,e)},withTags:function(){return this.what.tags=!0,this},withDel:function(e,t){return(e||t)&&(this.what.del={since:e,limit:t}),this},withLaterDel:function(e){return this.withDel(this.topic._maxSeq>0?this.topic._maxDel+1:void 0,e)},build:function(){var e={},t=[],n=this;return["data","sub","desc","tags","del"].map(function(s){n.what.hasOwnProperty(s)&&(t.push(s),Object.getOwnPropertyNames(n.what[s]).length>0&&(e[s]=n.what[s]))}),t.length>0?e.what=t.join(" "):e=void 0,e}};var M=function e(t){t&&(this.given="number"==typeof t.given?t.given:e.decode(t.given),this.want="number"==typeof t.want?t.want:e.decode(t.want),this.mode=t.mode?"number"==typeof t.mode?t.mode:e.decode(t.mode):this.given&this.want)};M._NONE=0,M._JOIN=1,M._READ=2,M._WRITE=4,M._PRES=8,M._APPROVE=16,M._SHARE=32,M._DELETE=64,M._OWNER=128,M._BITMASK=M._JOIN|M._READ|M._WRITE|M._PRES|M._APPROVE|M._SHARE|M._DELETE|M._OWNER,M._INVALID=1048576,M.decode=function(e){if(!e)return null;if("number"==typeof e)return e&M._BITMASK;if("N"===e||"n"===e)return M._NONE;for(var t={J:M._JOIN,R:M._READ,W:M._WRITE,P:M._PRES,A:M._APPROVE,S:M._SHARE,D:M._DELETE,O:M._OWNER},n=M._NONE,s=0;s0)){c=!0;break}r=o-1}return c?o:s?-1:a<0?o+1:o}function s(e,t){var s=n(e,t,!1);return t.splice(s,0,e),t}return e=e||function(e,t){return e===t?0:e0)return n[0]},delRange:function(e,n){return t.splice(e,n-e)},size:function(){return t.length},reset:function(e){t=[]},forEach:function(e,n,s,i){n|=0,s=s||t.length;for(var r=n;r=300)return e;if(n._subscribed=!0,n.acs=e.params&&e.params.acs?e.params.acs:n.acs,n._new){n._new=!1,n.name=e.topic,n.created=e.ts,n.updated=e.ts,n.touched=e.ts,n._cachePutSelf();var s=n._tinode.getMeTopic();s&&s._processMetaSub([{_generated:!0,topic:n.name,created:e.ts,updated:e.ts,touched:e.ts,acs:n.acs}]),t&&t.desc&&(t.desc._generated=!0,n._processMetaDesc(t.desc))}return e})},createMessage:function(e,t){return this._tinode.createMessage(this.name,e,t)},publish:function(e,t){return this.publishMessage(this.createMessage(e,t))},publishMessage:function(t){var n=this;if(!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));if(e.hasAttachments(t.content)&&!t.head.attachments){var s=[];e.attachments(t.content,function(e){s.push(e.ref)}),t.head.attachments=s}return t._sending=!0,this._tinode.publishMessage(t).then(function(e){return t._sending=!1,t.seq=e.params.seq,t.ts=e.ts,n._routeData(t),e}).catch(function(e){t._sending=!1,t._failed=!0})},publishDraft:function(e,t){var n=this;if(!t&&!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));var s=e.seq||this._getQueuedSeqId();return e._generated||(e._generated=!0,e.seq=s,e.ts=new Date,e.from=this._tinode.getCurrentUserID(),e.noecho=!0,this._messages.put(e),this.onData&&this.onData(e)),(t||Promise.resolve()).then(function(){return e._cancelled?{code:300,text:"cancelled"}:n.publishMessage(e)},function(t){e._sending=!1,n._messages.delAt(n._messages.find(e)),n.onData&&n.onData()})},leave:function(e){var t=this;return this._subscribed||e?this._tinode.leave(this.name,e).then(function(n){return t._resetSub(),e&&t._gone(),n}):Promise.reject(new Error("Cannot leave inactive topic"))},getMeta:function(e){return this._subscribed?this._tinode.getMeta(this.name,e):Promise.reject(new Error("Cannot query inactive topic"))},getMessagesPage:function(e,t){var n=this,s=this.startMetaQuery();t?s.withLaterData(e):s.withEarlierData(e);var i=this.getMeta(s.build());return t||(i=i.then(function(e){e&&e.params&&!e.params.count&&(n._noEarlierMsgs=!0)})),i},setMeta:function(e){var t=this;return this._subscribed?(e.tags&&(e.tags=function(e){var t=[];if(Array.isArray(e)){for(var n=0,s=e.length;n1&&t.push(i)}t.sort().filter(function(e,t,n){return!t||e!=n[t-1]})}return 0==t.length&&t.push(w.DEL_CHAR),t}(e.tags)),this._tinode.setMeta(this.name,e).then(function(n){return n&&n.code>=300?n:(e.sub&&(n.params&&n.params.acs&&(e.sub.acs=n.params.acs,e.sub.updated=n.ts),e.sub.user||(e.sub.user=t._tinode.getCurrentUserID(),e.desc||(e.desc={})),e.sub._generated=!0,t._processMetaSub([e.sub])),e.desc&&(n.params&&n.params.acs&&(e.desc.acs=n.params.acs,e.desc.updated=n.ts),t._processMetaDesc(e.desc)),e.tags&&t._processMetaTags(e.tags),n)})):Promise.reject(new Error("Cannot update inactive topic"))},invite:function(e,t){return this.setMeta({sub:{user:e,mode:t}})},delMessages:function(e,t){var n=this;if(!this._subscribed)return Promise.reject(new Error("Cannot delete messages in inactive topic"));e.sort(function(e,t){return e.low=t.hi)});var s=e.reduce(function(e,t){return t.low<268435455&&(!t.hi||t.hi<268435455?e.push(t):e.push({low:t.low,hi:n._maxSeq+1})),e},[]);return(e.length>0?this._tinode.delMessages(this.name,s,t):Promise.resolve({params:{del:0}})).then(function(t){return t.params.del>n._maxDel&&(n._maxDel=t.params.del),e.map(function(e){e.hi?n.flushMessageRange(e.low,e.hi):n.flushMessage(e.low)}),n.onData&&n.onData(),t})},delMessagesAll:function(e){return this.delMessages([{low:1,hi:this._maxSeq+1,_all:!0}],e)},delMessagesList:function(e,t){e.sort(function(e,t){return e-t});var n=e.reduce(function(e,t){if(0==e.length)e.push({low:t});else{var n=e[e.length-1];!n.hi&&t!=n.low+1||t>n.hi?e.push({low:t}):n.hi=n.hi?Math.max(n.hi,t+1):t+1}return e},[]);return this.delMessages(n,t)},delTopic:function(){var e=this;return this._tinode.delTopic(this.name).then(function(t){return e._resetSub(),e._gone(),t})},delSubscription:function(e){var t=this;return this._subscribed?this._tinode.delSubscription(this.name,e).then(function(n){return delete t._users[e],t.onSubsUpdated&&t.onSubsUpdated(Object.keys(t._users)),n}):Promise.reject(new Error("Cannot delete subscription in inactive topic"))},note:function(e,t){var n=this._users[this._tinode.getCurrentUserID()];n?((!n[e]||n[e]0)for(var i in this._users){var r=this._users[i];r.user!==s&&r[e]>=t&&n++}return n},msgReadCount:function(e){return this.msgReceiptCount("read",e)},msgRecvCount:function(e){return this.msgReceiptCount("recv",e)},msgHasMoreMessages:function(e){return e?this.seq>this._maxSeq:this._minSeq>1&&!this._noEarlierMsgs},isNewMessage:function(e){return this._maxSeq<=e},flushMessage:function(e){var t=this._messages.find({seq:e});return t>=0?this._messages.delAt(t):void 0},flushMessageRange:function(e,t){var n=this._messages.find({seq:e});return n>=0?this._messages.delRange(n,this._messages.find({seq:t},!0)):[]},cancelSend:function(e){var t=this._messages.find({seq:e});if(t>=0){var n=this._messages.getAt(t);if(1==this.msgStatus(n))return n._cancelled=!0,this._messages.delAt(t),!0}return!1},getType:function(){return w.topicType(this.name)},getAccessMode:function(){return this.acs},getDefaultAccess:function(){return this.defacs},startMetaQuery:function(){return new S(this)},msgStatus:function(e){var t=0;return e.from==this._tinode.getCurrentUserID()?e._sending?t=2:e._failed?t=3:e.seq>=268435455?t=1:this.msgReadCount(e.seq)>0?t=6:this.msgRecvCount(e.seq)>0?t=5:e.seq>0&&(t=4):t=7,t},_routeData:function(e){e.content&&((!this.touched||this.touchedthis._maxSeq&&(this._maxSeq=e.seq),(e.seq0&&(this._lastSubsUpdate=e.ts,this._processMetaSub(e.sub)),e.del&&this._processDelMessages(e.del.clear,e.del.delseq),e.tags&&this._processMetaTags(e.tags),this.onMeta&&this.onMeta(e)},_routePres:function(e){var t;switch(e.what){case"del":this._processDelMessages(e.clear,e.delseq);break;case"on":case"off":(t=this._users[e.src])?t.online="on"==e.what:this._tinode.logger("Presence update for an unknown user",this.name,e.src);break;case"acs":var n="me"==e.src?this._tinode.getCurrentUserID():e.src;if(t=this._users[n])t.acs.updateAll(e.dacs),n==this._tinode.getCurrentUserID()&&this.acs.updateAll(e.dacs),t.acs&&t.acs.mode!=M._NONE||("p2p"==this.getType()&&this.leave(),this._processMetaSub([{user:n,deleted:new Date,_generated:!0}]));else{var s=(new M).updateAll(e.dacs);s&&s.mode!=M._NONE&&((t=this._cacheGetUser(n))?t.acs=s:(t={user:n,acs:s},this.getMeta(this.startMetaQuery().withOneSub(void 0,n).build())),t._generated=!0,t.updated=new Date,this._processMetaSub([t]))}break;default:this._tinode.logger("Ignored presence update",e.what)}this.onPres&&this.onPres(e)},_routeInfo:function(e){if("kp"!==e.what){var t=this._users[e.from];t&&(t[e.what]=e.seq)}this.onInfo&&this.onInfo(e)},_processMetaDesc:function(e,t){if(f(this,e),"string"==typeof this.created&&(this.created=new Date(this.created)),"string"==typeof this.updated&&(this.updated=new Date(this.updated)),"string"==typeof this.touched&&(this.touched=new Date(this.touched)),"me"!==this.name&&!t&&!e._generated){var n=this._tinode.getMeTopic();n&&n._processMetaSub([{_generated:!0,topic:this.name,updated:this.updated,touched:this.touched,acs:this.acs,public:this.public,private:this.private}])}this.onMetaDesc&&this.onMetaDesc(this)},_processMetaSub:function(e){var t=void 0;for(var n in e){var s=e[n];if(s.user){s.updated=new Date(s.updated),s.deleted=s.deleted?new Date(s.deleted):null;var i=null;s.deleted?(delete this._users[s.user],i=s):((i=this._users[s.user])||(i=this._cacheGetUser(s.user)),i=this._updateCachedUser(s.user,s,s._generated)),this.onMetaSub&&this.onMetaSub(i)}else s._generated||(t=s)}t&&this.onMetaDesc&&this.onMetaDesc(t),this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users))},_processMetaTags:function(e){1==e.length&&e[0]==w.DEL_CHAR&&(e=[]),this._tags=e,this.onTagsUpdated&&this.onTagsUpdated(e)},_processDelMessages:function(e,t){this._maxDel=Math.max(e,this._maxDel),this.clear=Math.max(e,this.clear);var n=this,s=0;Array.isArray(t)&&t.map(function(e){if(e.hi)for(var t=e.low;t0&&this.onData&&this.onData()},_allMessagesReceived:function(e){this.onAllMessagesReceived&&this.onAllMessagesReceived(e)},_resetSub:function(){this._subscribed=!1},_gone:function(){this._messages.reset(),this._users={},this.acs=new M(null),this.private=null,this.public=null,this._maxSeq=0,this._minSeq=0,this._subscribed=!1;var e=this._tinode.getMeTopic();e&&e._routePres({_generated:!0,what:"gone",topic:"me",src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()},_updateCachedUser:function(e,t,n){var s=this._cacheGetUser(e);return s?s=f(s,t):(n&&this.getMeta(this.startMetaQuery().withLaterOneSub(e).build()),s=f({},t)),this._cachePutUser(e,s),p(this._users,e,s)},_getQueuedSeqId:function(){return this._queuedSeqId++}};var y=function(e){T.call(this,"me",e),this._contacts={},e&&(this.onContactUpdate=e.onContactUpdate)};y.prototype=Object.create(T.prototype,{_processMetaSub:{value:function(e){var t=0;for(var n in e){var s=e[n],i=s.topic;if("fnd"!=i&&"me"!=i){s.updated=new Date(s.updated),s.touched=s.touched?new Date(s.touched):null,s.deleted=s.deleted?new Date(s.deleted):null,s.seq=0|s.seq,s.recv=0|s.recv,s.read=0|s.read,s.unread=s.seq-s.read;var r=null;if(s.deleted)r=s,delete this._contacts[i];else if(s.seen&&s.seen.when&&(s.seen.when=new Date(s.seen.when)),r=p(this._contacts,i,s),"p2p"==w.topicType(i)&&this._cachePutUser(i,r),!s._generated){var o=this._tinode.getTopic(i);o&&o._processMetaDesc(s,!0)}t++,this.onMetaSub&&this.onMetaSub(r)}}t>0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))},enumerable:!0,configurable:!0,writable:!1},_routePres:{value:function(e){var t=this._contacts[e.src];if(t){switch(e.what){case"on":t.online=!0;break;case"off":t.online&&(t.online=!1,t.seen?t.seen.when=new Date:t.seen={when:new Date});break;case"msg":t.touched=new Date,t.seq=0|e.seq,t.unread=t.seq-t.read;break;case"upd":this.getMeta(this.startMetaQuery().withLaterOneSub(e.src).build());break;case"acs":t.acs?t.acs.updateAll(e.dacs):t.acs=(new M).updateAll(e.dacs);break;case"ua":t.seen={when:new Date,ua:e.ua};break;case"recv":t.recv=t.recv?Math.max(t.recv,e.seq):0|e.seq;break;case"read":t.read=t.read?Math.max(t.read,e.seq):0|e.seq,t.unread=t.seq-t.read;break;case"gone":delete this._contacts[e.src]}this.onContactUpdate&&this.onContactUpdate(e.what,t)}else if("acs"==e.what){var n=new M(e.dacs);if(!n||n.mode==M._INVALID)return void this._tinode.logger("Invalid access mode update",e.src,e.dacs);if(n.mode==M._NONE)return void this._tinode.logger("Removing non-existent subscription",e.src,e.dacs);this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build()),this._contacts[e.src]={topic:e.src,online:!1,acs:n}}this.onPres&&this.onPres(e)},enumerable:!0,configurable:!0,writable:!1},publish:{value:function(){return Promise.reject(new Error("Publishing to 'me' is not supported"))},enumerable:!0,configurable:!0,writable:!1},contacts:{value:function(e,t){var n=e||this.onMetaSub;if(n)for(var s in this._contacts)n.call(t,this._contacts[s],s,this._contacts)},enumerable:!0,configurable:!0,writable:!0},setMsgReadRecv:{value:function(e,t,n,s){var i,r=this._contacts[e],o=!1;r&&(n|=0,"recv"===t?(i=r.recv,r.recv=r.recv?Math.max(r.recv,n):n,o=i!=r.recv):"read"===t?(i=r.read,r.read=r.read?Math.max(r.read,n):n,r.unread=r.seq-r.read,o=i!=r.read,r.recv0&&this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts))},enumerable:!0,configurable:!0,writable:!1},publish:{value:function(){return Promise.reject(new Error("Publishing to 'fnd' is not supported"))},enumerable:!0,configurable:!0,writable:!1},setMeta:{value:function(e){var t=this;return Object.getPrototypeOf(D.prototype).setMeta.call(this,e).then(function(){Object.keys(t._contacts).length>0&&(t._contacts={},t.onSubsUpdated&&t.onSubsUpdated([]))})},enumerable:!0,configurable:!0,writable:!1},contacts:{value:function(e,t){var n=e||this.onMetaSub;if(n)for(var s in this._contacts)n.call(t,this._contacts[s],s,this._contacts)},enumerable:!0,configurable:!0,writable:!0}}),D.prototype.constructor=D;var E=function(e){this._tinode=e,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this._msgId=e.getNextUniqueId(),this.xhr=g(),this.toResolve=null,this.toReject=null,this.onProgress=null,this.onSuccess=null,this.onFailure=null};E.prototype={upload:function(e,t,n,s){var i=this;if(!this._authToken)throw new Error("Must authenticate first");var o=this;this.xhr.open("POST","/v"+r+"/file/u/",!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token);var a=new Promise(function(e,t){i.toResolve=e,i.toReject=t});this.onProgress=t,this.onSuccess=n,this.onFailure=s,this.xhr.upload.onprogress=function(e){e.lengthComputable&&o.onProgress&&o.onProgress(e.loaded/e.total)},this.xhr.onload=function(){var e;try{e=JSON.parse(this.response,_)}catch(e){o._tinode.logger("Invalid server response in LargeFileHelper",this.response)}this.status>=200&&this.status<300?(o.toResolve&&o.toResolve(e.ctrl.params.url),o.onSuccess&&o.onSuccess(e.ctrl)):this.status>=400?(o.toReject&&o.toReject(new Error(e.ctrl.text+" ("+e.ctrl.code+")")),o.onFailure&&o.onFailure(e.ctrl)):o._tinode.logger("Unexpected server response status",this.status,this.response)},this.xhr.onerror=function(e){o.toReject&&o.toReject(new Error("failed")),o.onFailure&&o.onFailure(null)},this.xhr.onabort=function(e){o.toReject&&o.toReject(new Error("upload cancelled by user")),o.onFailure&&o.onFailure(null)};try{var c=new FormData;c.append("file",e),c.set("id",this._msgId),this.xhr.send(c)}catch(e){this.toReject&&this.toReject(e),this.onFailure&&this.onFailure(null)}return a},download:function(e,t,n,s){var i=this;if(/^(?:(?:[a-z]+:)?\/\/)/i.test(e))throw new Error("The URL '"+e+"' must be relative, not absolute");if(!this._authToken)throw new Error("Must authenticate first");var r=this;this.xhr.open("GET",e,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token),this.xhr.responseType="blob",this.onProgress=s,this.xhr.onprogress=function(e){r.onProgress&&r.onProgress(e.loaded)};var o=new Promise(function(e,t){i.toResolve=e,i.toReject=t});this.xhr.onload=function(){if(200==this.status){var e=document.createElement("a");e.href=window.URL.createObjectURL(new Blob([this.response],{type:n})),e.style.display="none",e.setAttribute("download",t),document.body.appendChild(e),e.click(),document.body.removeChild(e),window.URL.revokeObjectURL(e.href),r.toResolve&&r.toResolve()}else if(this.status>=400&&r.toReject){var s=new FileReader;s.onload=function(){try{var e=JSON.parse(this.result,_);r.toReject(new Error(e.ctrl.text+" ("+e.ctrl.code+")"))}catch(e){r._tinode.logger("Invalid server response in LargeFileHelper",this.result),r.toReject(e)}},s.readAsText(this.response)}},this.xhr.onerror=function(e){r.toReject&&r.toReject(new Error("failed"))},this.xhr.onabort=function(){r.toReject&&r.toReject(null)};try{this.xhr.send()}catch(e){this.toReject&&this.toReject(e)}return o},cancel:function(){this.xhr&&this.xhr.readyState<4&&this.xhr.abort()},getId:function(){return this._msgId}};var x=function e(t,n){this.status=e.STATUS_NONE,this.topic=t,this.content=n};x.STATUS_NONE=0,x.STATUS_QUEUED=1,x.STATUS_SENDING=2,x.STATUS_FAILED=3,x.STATUS_SENT=4,x.STATUS_RECEIVED=5,x.STATUS_READ=6,x.STATUS_TO_ME=7,(x.prototype={toJSON:function(){},fromJSON:function(e){}}).constructor=x,(c=w).Drafty=e}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),c}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],24:[function(require,module,exports){ (function (global){ @@ -28244,7 +28244,7 @@ function base64ReEncode(str) { try { str = btoa(atob(str)); } catch (err) { - console.log("failed to base64 re-decode string"); + console.log("Failed to base64 re-decode string"); str = null; } } @@ -28650,7 +28650,7 @@ var ContextMenu = function (_React$Component) { // We don't know if the message is still pending (e.g. attachment is being uploaded), // so try cancelling first. No harm if we can't cancel. if (topic.cancelSend(params.seq)) { - return new Promise.resolve(); + return Promise.resolve(); } // Can't cancel. Delete instead. var promise = all ? topic.delMessagesAll(hard) : topic.delMessagesList([params.seq], hard); @@ -32885,7 +32885,14 @@ var ReceivedMarker = function (_React$PureComponent22) { _createClass(ReceivedMarker, [{ key: 'render', value: function render() { - var timestamp = this.props.received <= Tinode.MESSAGE_STATUS_SENDING ? "sending ..." : shortDateFormat(this.props.timestamp); + var timestamp = void 0; + if (this.props.received <= Tinode.MESSAGE_STATUS_SENDING) { + timestamp = "sending ..."; + } else if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) { + timestamp = "failed"; + } else { + timestamp = shortDateFormat(this.props.timestamp); + } var marker = null; if (this.props.received <= Tinode.MESSAGE_STATUS_SENDING) { @@ -32894,6 +32901,12 @@ var ReceivedMarker = function (_React$PureComponent22) { { className: 'material-icons small' }, 'access_time' ); // watch face + } else if (this.props.received == Tinode.MESSAGE_STATUS_FAILED) { + marker = React.createElement( + 'i', + { className: 'material-icons small red' }, + 'error_outline' + ); // icon (!) } else if (this.props.received == Tinode.MESSAGE_STATUS_SENT) { marker = React.createElement( 'i', @@ -32911,7 +32924,7 @@ var ReceivedMarker = function (_React$PureComponent22) { 'i', { className: 'material-icons small blue' }, 'done_all' - ); // open eye + ); // blue double checkmark } return React.createElement( @@ -33238,16 +33251,21 @@ var MessagesView = function (_React$Component19) { }); if (!topic.isSubscribed() && tryToResubscribe) { - var getQuery = topic.startMetaQuery().withLaterDesc().withLaterSub().withLaterData(MESSAGES_PAGE).withLaterDel(); - var setQuery = newGroupTopic ? props.newGroupTopicParams : undefined; // Don't request the tags. They are useless unless the user // is the owner and is editing the topic. - // getQuery = topic.getType() == 'grp' ? getQuery.withTags() : getQuery; + var getQuery = topic.startMetaQuery().withLaterDesc().withLaterSub().withLaterData(MESSAGES_PAGE).withLaterDel(); + var setQuery = newGroupTopic ? props.newGroupTopicParams : undefined; // Show "loading" spinner. this.setState({ fetchingMessages: true }); topic.subscribe(getQuery.build(), setQuery).then(function (ctrl) { _this51.setState({ topic: ctrl.topic }); _this51.props.onNewTopicCreated(props.topic, ctrl.topic); + // If there are unsent messages, try sending them now. + topic.queuedMessages(function (pub) { + if (!pub._sending && topic.isSubscribed()) { + topic.publishMessage(pub); + } + }); }).catch(function (err) { _this51.props.onError(err.message, "err"); _this51.setState({ @@ -33255,7 +33273,11 @@ var MessagesView = function (_React$Component19) { avatar: null, readOnly: true, writeOnly: true, - fetchingMessages: false + fetchingMessages: false, + messages: [], + onlineSubs: [], + typingIndicator: false, + imagePreview: null }); }); } @@ -33373,7 +33395,7 @@ var MessagesView = function (_React$Component19) { newState.scrollPosition = 0; } - // Aknowledge all messages, including own messges. + // Aknowledge all messages, including own messages. var status = topic.msgStatus(msg); if (status >= Tinode.MESSAGE_STATUS_SENT) { this.props.readTimerHandler(function () { @@ -34196,6 +34218,8 @@ var TinodeWeb = function (_React$Component20) { this.setState({ viewportWidth: document.documentElement.clientWidth }); this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, this.state.transport); + this.tinode.onConnect = this.handleConnected; + this.tinode.onDisconnect = this.handleDisconnect; // Initialize desktop alerts. if (this.state.desktopAlertsEnabled) { @@ -34223,10 +34247,6 @@ var TinodeWeb = function (_React$Component20) { } } - this.tinode.enableLogging(true, true); - this.tinode.onConnect = this.handleConnected; - this.tinode.onDisconnect = this.handleDisconnect; - var token = localStorage.getObject("keep-logged-in") ? localStorage.getObject("auth-token") : undefined; var parsedNav = parseUrlHash(window.location.hash); @@ -34578,7 +34598,7 @@ var TinodeWeb = function (_React$Component20) { var _this67 = this; var topic = this.tinode.getTopic(data.topic); - if (topic.msgStatus(data) > Tinode.MESSAGE_STATUS_SENDING) { + if (topic.msgStatus(data) >= Tinode.MESSAGE_STATUS_SENT) { clearTimeout(this.receivedTimer); this.receivedTimer = setTimeout(function () { _this67.receivedTimer = undefined; @@ -34784,11 +34804,17 @@ var TinodeWeb = function (_React$Component20) { value: function handleGlobalSettings(settings) { var serverAddress = settings.serverAddress || this.state.serverAddress; var transport = settings.transport || this.state.transport; + if (this.tinode) { + this.tinode.onDisconnect = undefined; + this.tinode.disconnect(); + } + this.tinode = TinodeWeb.tnSetup(serverAddress, transport); + this.tinode.onConnect = this.handleConnected; + this.tinode.onDisconnect = this.handleDisconnect; this.setState({ serverAddress: serverAddress, - transport: transport, - tinode: TinodeWeb.tnSetup(serverAddress, transport) + transport: transport }); localStorage.setObject("settings", { serverAddress: serverAddress, @@ -34995,6 +35021,8 @@ var TinodeWeb = function (_React$Component20) { } this.setState(this.getBlankState()); this.tinode = TinodeWeb.tnSetup(this.state.serverAddress, this.state.transport); + this.tinode.onConnect = this.handleConnected; + this.tinode.onDisconnect = this.handleDisconnect; navigateTo(""); } }, { @@ -35251,7 +35279,9 @@ var TinodeWeb = function (_React$Component20) { }], [{ key: 'tnSetup', value: function tnSetup(serverAddress, transport) { - return new Tinode(APP_NAME, serverAddress, API_KEY, transport, isSecureConnection()); + var tinode = new Tinode(APP_NAME, serverAddress, API_KEY, transport, isSecureConnection()); + tinode.enableLogging(true, true); + return tinode; } }, { key: 'prepareSearchableContacts', @@ -35334,7 +35364,7 @@ var TinodeWeb = function (_React$Component20) { module.exports = TinodeWeb; },{"../version.json":27,"firebase/app":6,"firebase/messaging":7,"react":16,"react-dom":13,"tinode-sdk":23}],27:[function(require,module,exports){ -module.exports={"version": "0.15.7-rc4"} +module.exports={"version": "0.15.7-rc5"} },{}],28:[function(require,module,exports){ // shim for using process in browser diff --git a/umd/index.prod.js b/umd/index.prod.js index f5daaf88..36065fda 100644 --- a/umd/index.prod.js +++ b/umd/index.prod.js @@ -1 +1 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Webapp=e()}}(function(){return function(){return function e(t,n,r){function i(o,s){if(!n[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[o]={exports:{}};t[o][0].call(c.exports,function(e){return i(t[o][1][e]||e)},c,c.exports,e,t,n,r)}return n[o].exports}for(var a="function"==typeof require&&require,o=0;oo&&console.warn("This browser only supports "+o+" actions.The remaining actions will not be displayed."),[2,i.showNotification(r,n)];case 3:return this.bgMessageHandler?[4,this.bgMessageHandler(t)]:[3,5];case 4:return s.sent(),[2];case 5:return[2]}})})},t.prototype.onSubChange_=function(e){return l.__awaiter(this,void 0,void 0,function(){var e,t,n,r;return l.__generator(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.getSWRegistration_()];case 1:return e=i.sent(),[3,3];case 2:throw t=i.sent(),p.create(c.UNABLE_TO_RESUBSCRIBE,{message:t});case 3:return i.trys.push([3,5,,8]),[4,e.pushManager.getSubscription()];case 4:return i.sent(),[3,8];case 5:return n=i.sent(),[4,this.getTokenDetailsModel().getTokenDetailsFromSWScope(e.scope)];case 6:if(!(r=i.sent()))throw n;return[4,this.deleteToken(r.fcmToken)];case 7:throw i.sent(),n;case 8:return[2]}})})},t.prototype.onNotificationClick_=function(e){return l.__awaiter(this,void 0,void 0,function(){var t,n,r,i;return l.__generator(this,function(a){switch(a.label){case 0:return e.notification&&e.notification.data&&e.notification.data.FCM_MSG?e.action?[2]:(e.stopImmediatePropagation(),e.notification.close(),(t=e.notification.data.FCM_MSG).notification&&(n=t.fcmOptions&&t.fcmOptions.link||t.notification.click_action)?[4,this.getWindowClient_(n)]:[2]):[2];case 1:return(r=a.sent())?[3,3]:[4,self.clients.openWindow(n)];case 2:return r=a.sent(),[3,5];case 3:return[4,r.focus()];case 4:r=a.sent(),a.label=5;case 5:return r?(delete t.notification,delete t.fcmOptions,i=O(o.NOTIFICATION_CLICKED,t),[2,this.attemptToMessageClient_(r,i)]):[2]}})})},t.prototype.getNotificationData_=function(e){if(e&&"object"==typeof e.notification){var t,n=l.__assign({},e.notification);return n.data=l.__assign({},e.notification.data,((t={}).FCM_MSG=e,t)),n}},t.prototype.setBackgroundMessageHandler=function(e){if(!e||"function"!=typeof e)throw p.create(c.BG_HANDLER_FUNCTION_EXPECTED);this.bgMessageHandler=e},t.prototype.getWindowClient_=function(e){return l.__awaiter(this,void 0,void 0,function(){var t,n,r,i;return l.__generator(this,function(a){switch(a.label){case 0:return t=new URL(e,self.location.href).href,[4,N()];case 1:for(n=a.sent(),r=null,i=0;i0?V:z)(e)},K=Math.min,H=function(e){return e>0?K(q(e),9007199254740991):0},G=Array.isArray||function(e){return"Array"==L(e)},$=f["__core-js_shared__"]||(f["__core-js_shared__"]={}),Y=function(e){return $[e]||($[e]={})},Q=p(function(e){var t=Y("wks"),n=f.Symbol,r="function"==typeof n;(e.exports=function(e){return t[e]||(t[e]=r&&n[e]||(r?n:M)("Symbol."+e))}).store=t}),X=Q("species"),J=function(e,t){return new(function(e){var t;return G(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!G(t.prototype)||(t=void 0),m(t)&&null===(t=t[X])&&(t=void 0)),void 0===t?Array:t}(e))(t)},Z=function(e,t){var n=1==e,r=2==e,i=3==e,a=4==e,o=6==e,s=5==e||o,l=t||J;return function(t,u,c){for(var d,p,f=B(t),h=j(f),m=R(u,c,3),v=H(h.length),g=0,y=n?l(t,v):r?l(t,0):void 0;v>g;g++)if((s||g in h)&&(p=m(d=h[g],g,f),e))if(n)y[g]=p;else if(p)switch(e){case 3:return!0;case 5:return d;case 6:return g;case 2:y.push(d)}else if(a)return!1;return o?-1:i||a?a:y}},ee=Q("unscopables"),te=Array.prototype;void 0==te[ee]&&x(te,ee,{});var ne=function(e){te[ee][e]=!0},re=Z(5),ie=!0;"find"in[]&&Array(1).find(function(){ie=!1}),U(U.P+U.F*ie,"Array",{find:function(e){return re(this,e,arguments.length>1?arguments[1]:void 0)}}),ne("find");h.Array.find;var ae=Z(6),oe=!0;"findIndex"in[]&&Array(1).findIndex(function(){oe=!1}),U(U.P+U.F*oe,"Array",{findIndex:function(e){return ae(this,e,arguments.length>1?arguments[1]:void 0)}}),ne("findIndex");h.Array.findIndex;var se,le=function(e){return j(W(e))},ue=Math.max,ce=Math.min,de=Y("keys"),pe=function(e){return de[e]||(de[e]=M(e))},fe=(se=!1,function(e,t,n){var r,i=le(e),a=H(i.length),o=function(e,t){return(e=q(e))<0?ue(e+t,0):ce(e,t)}(n,a);if(se&&t!=t){for(;a>o;)if((r=i[o++])!=r)return!0}else for(;a>o;o++)if((se||o in i)&&i[o]===t)return se||o||0;return!se&&-1}),he=pe("IE_PROTO"),me=function(e,t){var n,r=le(e),i=0,a=[];for(n in r)n!=he&&N(r,n)&&a.push(n);for(;t.length>i;)N(r,n=t[i++])&&(~fe(a,n)||a.push(n));return a},ve="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),ge=Object.keys||function(e){return me(e,ve)},ye={f:Object.getOwnPropertySymbols},be={f:{}.propertyIsEnumerable},we=Object.assign,_e=!we||g(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=we({},e)[n]||Object.keys(we({},t)).join("")!=r})?function(e,t){for(var n=B(e),r=arguments.length,i=1,a=ye.f,o=be.f;r>i;)for(var s,l=j(arguments[i++]),u=a?ge(l).concat(a(l)):ge(l),c=u.length,d=0;c>d;)o.call(l,s=u[d++])&&(n[s]=l[s]);return n}:we;U(U.S+U.F,"Object",{assign:_e});h.Object.assign;var ke=Q("match"),Ee=function(e,t,n){if(m(r=t)&&(void 0!==(i=r[ke])?i:"RegExp"==L(r)))throw TypeError("String#"+n+" doesn't accept regex!");var r,i;return String(W(e))},Se=Q("match"),Te="".startsWith;U(U.P+U.F*function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[Se]=!1,!"/./"[e](t)}catch(e){}}return!0}("startsWith"),"String",{startsWith:function(e){var t=Ee(this,e,"startsWith"),n=H(Math.min(arguments.length>1?arguments[1]:void 0,t.length)),r=String(e);return Te?Te.call(t,r,n):t.slice(n,n+r.length)===r}});h.String.startsWith;U(U.P,"String",{repeat:function(e){var t=String(W(this)),n="",r=q(e);if(r<0||r==1/0)throw RangeError("Count can't be negative");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(n+=t);return n}});h.String.repeat;var Ce=p(function(e){var t=M("meta"),n=T.f,r=0,i=Object.isExtensible||function(){return!0},a=!g(function(){return i(Object.preventExtensions({}))}),o=function(e){n(e,t,{value:{i:"O"+ ++r,w:{}}})},s=e.exports={KEY:t,NEED:!1,fastKey:function(e,n){if(!m(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!N(e,t)){if(!i(e))return"F";if(!n)return"E";o(e)}return e[t].i},getWeak:function(e,n){if(!N(e,t)){if(!i(e))return!0;if(!n)return!1;o(e)}return e[t].w},onFreeze:function(e){return a&&s.NEED&&i(e)&&!N(e,t)&&o(e),e}}}),xe=(Ce.KEY,Ce.NEED,Ce.fastKey,Ce.getWeak,Ce.onFreeze,T.f),Pe=Q("toStringTag"),Ne=function(e,t,n){e&&!N(e=n?e:e.prototype,Pe)&&xe(e,Pe,{configurable:!0,value:t})},Oe={f:Q},De=T.f,Me=function(e){var t=h.Symbol||(h.Symbol=f.Symbol||{});"_"==e.charAt(0)||e in t||De(t,e,{value:Oe.f(e)})},Ae=y?Object.defineProperties:function(e,t){v(e);for(var n,r=ge(t),i=r.length,a=0;i>a;)T.f(e,n=r[a++],t[n]);return e},Re=f.document,Ie=Re&&Re.documentElement,Ue=pe("IE_PROTO"),Fe=function(){},Le=function(){var e,t=_("iframe"),n=ve.length;for(t.style.display="none",Ie.appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("