From 37bad29350aa165c8a3682320302da1ada992b83 Mon Sep 17 00:00:00 2001 From: or-else Date: Tue, 16 Oct 2018 10:43:37 +0300 Subject: [PATCH] upgrade, bump version, and rebuild --- package.json | 6 +++--- service-worker.js | 7 ++----- umd/index.dev.js | 4 ++-- umd/index.prod.js | 2 +- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index 02c867f0..8d08d3d0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "tinode-webapp", "description": "Tinode messenger for the web", - "version": "0.15.7-rc6", + "version": "0.15.7", "devDependencies": { "babel-cli": "^6.26.0", "babel-preset-env": "^1.7.0", @@ -66,9 +66,9 @@ "author": "Tinode Authors ", "license": "Apache-2.0", "dependencies": { - "firebase": "^5.5.2", + "firebase": "^5.5.4", "react": "^16.5.2", "react-dom": "^16.5.2", - "tinode-sdk": "^0.15.7-rc6" + "tinode-sdk": "^0.15.7" } } diff --git a/service-worker.js b/service-worker.js index 406ca78e..eea83960 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,6 +1,6 @@ // Must be located at the root. -importScripts("https://unpkg.com/firebase@5.5.2/firebase-app.js"); -importScripts("https://unpkg.com/firebase@5.5.2/firebase-messaging.js"); +importScripts("https://unpkg.com/firebase@5.5.4/firebase-app.js"); +importScripts("https://unpkg.com/firebase@5.5.4/firebase-messaging.js"); importScripts("/firebase-init.js") firebase.initializeApp(FIREBASE_INIT); @@ -24,8 +24,6 @@ firebase.messaging().setBackgroundMessageHandler(function(payload) { // This code handles a click on notification: takes // the user to the browser tab with the chat or opens a new tab. self.addEventListener('notificationclick', function(event) { - console.log('On notification click: ', event.notification); - const notification = event.notification; notification.close(); @@ -39,7 +37,6 @@ self.addEventListener('notificationclick', function(event) { let anyClient = null; for (let i = 0; i < windowClients.length; i++) { const url = new URL(windowClients[i].url); - console.log('found client with URL', url); if (url.hash.includes(notification.data.topic)) { matchingClient = windowClients[i]; break; diff --git a/umd/index.dev.js b/umd/index.dev.js index aab0ddbc..f2a63079 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?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/gi},{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-rc6",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}); +!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?|ftp):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/gi},{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",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){ @@ -35363,7 +35363,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-rc6"} +module.exports={"version": "0.15.7"} },{}],28:[function(require,module,exports){ // shim for using process in browser diff --git a/umd/index.prod.js b/umd/index.prod.js index 520092a1..16a34def 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(a,s){if(!n[a]){if(!t[a]){var l="function"==typeof require&&require;if(!s&&l)return l(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){return i(t[a][1][e]||e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;aa&&console.warn("This browser only supports "+a+" 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(o){switch(o.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=o.sent())?[3,3]:[4,self.clients.openWindow(n)];case 2:return r=o.sent(),[3,5];case 3:return[4,r.focus()];case 4:r=o.sent(),o.label=5;case 5:return r?(delete t.notification,delete t.fcmOptions,i=O(a.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(o){switch(o.label){case 0:return t=new URL(e,self.location.href).href,[4,N()];case 1:for(n=o.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,o=4==e,a=6==e,s=5==e||a,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(o)return!1;return a?-1:i||o?o: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 oe=Z(6),ae=!0;"findIndex"in[]&&Array(1).findIndex(function(){ae=!1}),U(U.P+U.F*ae,"Array",{findIndex:function(e){return oe(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),o=H(i.length),a=function(e,t){return(e=q(e))<0?ue(e+t,0):ce(e,t)}(n,o);if(se&&t!=t){for(;o>a;)if((r=i[a++])!=r)return!0}else for(;o>a;a++)if((se||a in i)&&i[a]===t)return se||a||0;return!se&&-1}),he=pe("IE_PROTO"),me=function(e,t){var n,r=le(e),i=0,o=[];for(n in r)n!=he&&N(r,n)&&o.push(n);for(;t.length>i;)N(r,n=t[i++])&&(~fe(o,n)||o.push(n));return o},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,o=ye.f,a=be.f;r>i;)for(var s,l=j(arguments[i++]),u=o?ge(l).concat(o(l)):ge(l),c=u.length,d=0;c>d;)a.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},o=!g(function(){return i(Object.preventExtensions({}))}),a=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";a(e)}return e[t].i},getWeak:function(e,n){if(!N(e,t)){if(!i(e))return!0;if(!n)return!1;a(e)}return e[t].w},onFreeze:function(e){return o&&s.NEED&&i(e)&&!N(e,t)&&a(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,o=0;i>o;)T.f(e,n=r[o++],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("