1 line
56 KiB
JavaScript
1 line
56 KiB
JavaScript
!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=function(e){var t;return function(n){return t||e(t={exports:{},parent:n},t.exports),t.exports}},t=e(function(e,t){e.exports={version:"0.16.3-rc4"}}),n=e(function(e,t){"use strict";var n=[{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)/}],i=[{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},FM:{name:"div",isVoid:!1},RW:{name:"div",isVoid:!1},BN:{name:"button",isVoid:!1},HD:{name:"",isVoid:!1}};function r(e,t){var n;try{for(var i=(n=atob(e)).length,s=new ArrayBuffer(i),r=new Uint8Array(s),o=0;o<i;o++)r[o]=n.charCodeAt(o);return URL.createObjectURL(new Blob([s],{type:t}))}catch(a){console.log("Drafty: failed to convert object.",a.message)}return null}var o={ST:{open:function(){return"<b>"},close:function(){return"</b>"}},EM:{open:function(){return"<i>"},close:function(){return"</i>"}},DL:{open:function(){return"<del>"},close:function(){return"</del>"}},CO:{open:function(){return"<tt>"},close:function(){return"</tt>"}},BR:{open:function(){return"<br/>"},close:function(){return""}},HD:{open:function(){return""},close:function(){return""}},LN:{open:function(e){return'<a href="'+e.url+'">'},close:function(e){return"</a>"},props:function(e){return e?{href:e.url,target:"_blank"}:null}},MN:{open:function(e){return'<a href="#'+e.val+'">'},close:function(e){return"</a>"},props:function(e){return e?{name:e.val}:null}},HT:{open:function(e){return'<a href="#'+e.val+'">'},close:function(e){return"</a>"},props:function(e){return e?{name:e.val}:null}},BN:{open:function(e){return"<button>"},close:function(e){return"</button>"},props:function(e){return e?{"data-act":e.act,"data-val":e.val,"data-name":e.name,"data-ref":e.ref}:null}},IM:{open:function(e){var t=r(e.val,e.mime),n=e.ref?e.ref:t;return(e.name?'<a href="'+n+'" download="'+e.name+'">':"")+'<img src="'+t+'"'+(e.width?' width="'+e.width+'"':"")+(e.height?' height="'+e.height+'"':"")+' border="0" />'},close:function(e){return e.name?"</a>":""},props:function(e){return e?{src:r(e.val,e.mime),title:e.name,"data-width":e.width,"data-height":e.height,"data-name":e.name,"data-size":e.val?.75*e.val.length|0:0,"data-mime":e.mime}:null}},FM:{open:function(e){return"<div>"},close:function(e){return"</div>"}},RW:{open:function(e){return"<div>"},close:function(e){return"</div>"}}},a=function(){};a.parse=function(e){if("string"!=typeof e)return null;var t=e.split(/\r?\n/),s=[],r={},o=[];t.map(function(e){var t,a,c=[];if(n.map(function(t){c=c.concat(function(e,t,n,i){for(var s=[],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,s.push({text:e.slice(c+1,h),children:[],start:c,end:h,type:i})}return s}(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]],i=t[0],s=1;s<t.length;s++)t[s].start>i.end?(n.push(t[s]),i=t[s]):t[s].end<i.end&&i.children.push(t[s]);for(var s in n)n[s].children=e(n[s].children);return n}(c);var u=function e(t,n){var i="",s=[];for(var r in t){var o=t[r];if(!o.text){var a=e(o.children,i.length+n);o.text=a.txt,s=s.concat(a.fmt)}o.type&&s.push({at:i.length+n,len:o.text.length,tp:o.type}),i+=o.text}return{txt:i,fmt:s}}(function e(t,n,i,s){var r=[];if(0==s.length)return[];for(var o in s){var a=s[o];a.start>n&&r.push({text:t.slice(n,a.start)});var c={type:a.type},u=e(t,a.start+1,a.end,a.children);u.length>0?c.children=u:c.text=a.text,r.push(c),n=a.end+1}return n<i&&r.push({text:t.slice(n,i)}),r}(e,0,e.length,c),0);a={txt:u.txt,fmt:u.fmt}}if((t=function(e){var t,n=[];if(i.map(function(i){for(;null!==(t=i.re.exec(e));)n.push({offset:t.index,len:t[0].length,unique:t[0],data:i.pack(t[0]),type:i.name})}),0==n.length)return n;n.sort(function(e,t){return e.offset-t.offset});var s=-1;return n=n.filter(function(e){var t=e.offset>s;return s=e.offset+e.len,t})}(a.txt)).length>0){var h=[];for(var l in t){var d=t[l],f=r[d.unique];f||(f=s.length,r[d.unique]=f,s.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;c<o.length;c++){var u=o[c],h=a.txt.length+1;a.fmt.push({tp:"BR",len:1,at:h-1}),a.txt+=" "+u.txt,u.fmt&&(a.fmt=a.fmt.concat(u.fmt.map(function(e){return e.at+=h,e}))),u.ent&&(a.fmt=a.fmt.concat(u.ent.map(function(e){return e.at+=h,e})))}0==a.fmt.length&&delete a.fmt,s.length>0&&(a.ent=s)}return a},a.insertImage=function(e,t,n,i,s,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:i,width:s,height:r,name:o,ref:c,size:0|a}}),e},a.appendImage=function(e,t,n,i,s,r,o,c){return(e=e||{txt:""}).txt+=" ",a.insertImage(e,e.txt.length-1,t,n,i,s,r,o,c)},a.attachFile=function(e,t,n,i,s,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:i,ref:r,size:0|s}};return r instanceof Promise&&(o.data.ref=r.then(function(e){o.data.ref=e},function(e){})),e.ent.push(o),e},a.wrapAsForm=function(e,t,n){return"string"==typeof e&&(e={txt:e}),e.fmt=e.fmt||[],e.fmt.push({at:t,len:n,tp:"FM"}),e},a.insertButton=function(e,t,n,i,s,r,o){return"string"==typeof e&&(e={txt:e}),!e||!e.txt||e.txt.length<t+n?null:n<=0||-1==["url","pub"].indexOf(s)?null:"url"!=s||o?(o=""+o,e.ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:t,len:n,key:e.ent.length}),e.ent.push({tp:"BN",data:{act:s,val:r,ref:o,name:i}}),e):null},a.appendButton=function(e,t,n,i,s,r){var o=(e=e||{txt:""}).txt.length;return e.txt+=t,a.insertButton(e,o,t.length,n,i,s,r)},a.attachJSON=function(e,t){return(e=e||{txt:""}).ent=e.ent||[],e.fmt=e.fmt||[],e.fmt.push({at:-1,len:0,key:e.ent.length}),e.ent.push({tp:"EX",data:{mime:"application/json",val:t}}),e},a.appendLineBreak=function(e){return(e=e||{txt:""}).fmt=e.fmt||[],e.fmt.push({at:e.txt.length,len:1,tp:"BR"}),e.txt+=" ",e},a.UNSAFE_toHTML=function(e){var t,n,i,s=e.txt,r=e.fmt,a=e.ent,c=[];if(r)for(var u in r){var h=r[u],l=h.tp,d=void 0;if(!l){var f=a[0|h.key];f&&(l=f.tp,d=f.data)}o[l]&&(c.push({idx:h.at+h.len,len:-h.len,what:o[l].close(d)}),c.push({idx:h.at,len:h.len,what:o[l].open(d)}))}for(var p in c.sort(function(e,t){return t.idx==e.idx?t.len-e.len:t.idx-e.idx}),c)c[p].what&&(t=s,n=c[p].idx,i=c[p].what,s=t.slice(0,n)+i+t.slice(n));return s},a.format=function(e,t,n){var i=e.txt,r=e.fmt,o=e.ent;if(i=i||"",Array.isArray(o)||(o=[]),!Array.isArray(r)){if(1!=o.length)return[i];r=[{at:0,len:0,key:0}]}var a=[].concat(r);return a.map(function(e){e.at=e.at||0,e.len=e.len||0,e.len<0&&(e.len=0),e.at<-1&&(e.at=-1)}),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,o[e.key]&&(t=o[e.key].data,n=o[e.key].tp)),{tp:n=n||"HD",data:t,at:e.at,len:e.len}}),function e(t,n,i,r,o,a){for(var c=[],u=0;u<r.length;u++){var h=r[u];if(!(h.at<0)){n<h.at&&(c.push(o.call(a,null,void 0,t.slice(n,h.at),c.length)),n=h.at);for(var l=[],d=u+1;d<r.length&&r[d].at<h.at+h.len;d++)l.push(r[d]),u=d;var f=s[h.tp]||{};c.push(o.call(a,h.tp,h.data,f.isVoid?null:e(t,n,h.at+h.len,l,o,a),c.length)),n=h.at+h.len}}return n<i&&c.push(o.call(a,null,void 0,t.slice(n,i),c.length)),c}(i,0,i.length,a,t,n)},a.toPlainText=function(e){return"string"==typeof e?e:e.txt},a.isPlainText=function(e){return"string"==typeof e||!(e.fmt||e.ent)},a.hasAttachments=function(e){if(e.ent&&e.ent.length>0)for(var t in e.ent)if(e.ent[t]&&"EX"==e.ent[t].tp)return!0;return!1},a.attachments=function(e,t,n){if(e.ent&&e.ent.length>0)for(var i in e.ent)e.ent[i]&&"EX"==e.ent[i].tp&&t.call(n,e.ent[i].data,i)},a.getDownloadUrl=function(e){var t=null;return"application/json"!=e.mime&&e.val?t=r(e.val,e.mime):"string"==typeof e.ref&&(t=e.ref),t},a.isUploading=function(e){return e.ref instanceof Promise},a.getPreviewUrl=function(e){return e.val?r(e.val,e.mime):null},a.getEntitySize=function(e){return e.size?e.size:e.val?.75*e.val.length|0:0},a.getEntityMimeType=function(e){return e.mime||"text/plain"},a.tagName=function(e){return s[e]?s[e].name:void 0},a.attrValue=function(e,t){if(t&&o[e])return o[e].props(t)},a.getContentType=function(){return"text/x-drafty"},void 0!==e&&(e.exports=a)}),i={exports:{}};return function(e){"use strict";function s(e){return(s="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(void 0===r)var r=n({});var o,a=t({}).version;"undefined"!=typeof WebSocket&&(o=WebSocket),"undefined"==typeof btoa&&(e.btoa=function(){for(var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n="",i=0,s=0,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.charAt(0|s)||(r="=",s%1);n+=r.charAt(63&i>>8-s%1*8)){if((e=t.charCodeAt(s+=.75))>255)throw new Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");i=i<<8|e}return n}),"undefined"==typeof atob&&(e.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,i=0,s=0,r=0;n=e.charAt(r++);~n&&(s=i%4?64*s+n:n,i++%4)?t+=String.fromCharCode(255&s>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return t}),"undefined"==typeof window&&(e.window={WebSocket:o,URL:{createObjectURL:function(){throw new Error("Unable to use window.URL in a non browser application")}}});var c="0",u=a||"0.16",h="tinodejs/"+u,l=503,d="Connection failed",f=418,p="Disconnected by client";function g(e){return btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)}))}function v(e,t,n){if("object"!=s(t)){if(t===y.DEL_CHAR)return;return void 0===t?e:t}if(null===t)return t;if(t instanceof Date)return e&&e instanceof Date&&!(e<t)?e:t;if(t instanceof T)return new T(t);if(t instanceof Array)return t;for(var i in e&&e!==y.DEL_CHAR||(e=t.constructor()),t)!t.hasOwnProperty(i)||n&&n[i]||"_noForwarding"==i||(e[i]=v(e[i],t[i]));return e}function _(e,t,n,i){return e[t]=v(e[t],n,i),e[t]}function m(){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 b(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"===s(t))return new T(t);return t}function w(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(t instanceof T)t=t.jsonHelper();else if(null==t||!1===t||Array.isArray(t)&&0==t.length||"object"==s(t)&&0==Object.keys(t).length)return;return t}(0,t)}function M(e,t,n){var i=null;return"http"!==t&&"https"!==t&&"ws"!==t&&"wss"!==t||(i=t+"://","/"!==(i+=e).charAt(i.length-1)&&(i+="/"),i+="v"+c+"/channels","http"!==t&&"https"!==t||(i+="/lp"),i+="?apikey="+n),i}var S=function(e,t,n,i,r){var a=this,c=e,u=i,h=t,g=r,v=2e3,_=10,w=.3,S=null,y=0,x=!1,T=function(e){if(a.logger){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];a.logger.apply(a,[e].concat(n))}};function D(){var e=this;clearTimeout(S);var t=v*(Math.pow(2,y)*(1+w*Math.random()));y=y>=_?y:y+1,this.onAutoreconnectIteration&&this.onAutoreconnectIteration(t),S=setTimeout(function(){if(T("Reconnecting, iter="+y+", timeout="+t),x)e.onAutoreconnectIteration&&e.onAutoreconnectIteration(-1);else{var n=e.connect();e.onAutoreconnectIteration?e.onAutoreconnectIteration(0,n):n.catch(function(){})}},t)}function E(){clearTimeout(S),S=null}function R(e){var t=null;e.connect=function(n,i){if(x=!1,t&&t.readyState==t.OPEN){if(!i)return Promise.resolve();t.close(),t=null}return n&&(c=n),new Promise(function(n,i){var s=M(c,u?"wss":"ws",h);T("Connecting to: ",s);var r=new o(s);r.onopen=function(t){g&&E(),e.onOpen&&e.onOpen(),n()},r.onclose=function(n){if(t=null,e.onDisconnect){var i=x?f:l;e.onDisconnect(new Error(x?p:d+" ("+i+")"),i)}!x&&g&&D.call(e)},r.onerror=function(e){i(e)},r.onmessage=function(t){e.onMessage&&e.onMessage(t.data)},t=r})},e.reconnect=function(t){E(),e.connect(null,t)},e.disconnect=function(){x=!0,t&&(E(),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&&t.readyState==t.OPEN},e.transport=function(){return"ws"},e.probe=function(){e.sendText("1")}}function A(e){var t=null,n=null,i=null;e.connect=function(i,s){if(x=!1,n){if(!s)return Promise.resolve();n.onreadystatechange=void 0,n.abort(),n=null}return i&&(c=i),new Promise(function(i,s){var r=M(c,u?"https":"http",h);T("Connecting to: ",r),(n=function n(i,s,r){var o=m(),a=!1;return o.onreadystatechange=function(c){if(4==o.readyState)if(201==o.status){var u=JSON.parse(o.responseText,b);t=i+"&sid="+u.ctrl.params.sid,(o=n(t)).send(null),e.onOpen&&e.onOpen(),s&&(a=!0,s()),g&&E()}else if(o.status<400)e.onMessage&&e.onMessage(o.responseText),(o=n(t)).send(null);else{if(r&&!a&&(a=!0,r(o.responseText)),e.onMessage&&o.responseText&&e.onMessage(o.responseText),e.onDisconnect){var h=o.status||(x?f:l),v=o.responseText||(x?p:d);e.onDisconnect(new Error(v+" ("+h+")"),h)}o=null,!x&&g&&D.call(e)}},o.open("GET",i,!0),o}(r,i,s)).send(null)}).catch(function(){})},e.reconnect=function(t){E(),e.connect(null,t)},e.disconnect=function(){x=!0,E(),i&&(i.onreadystatechange=void 0,i.abort(),i=null),n&&(n.onreadystatechange=void 0,n.abort(),n=null),e.onDisconnect&&e.onDisconnect(new Error(p+" ("+f+")"),f),t=null},e.sendText=function(e){var n,s;if(n=t,(s=m()).onreadystatechange=function(e){if(4==s.readyState&&s.status>=400)throw new Error("LP sender failed, "+s.status)},s.open("POST",n,!0),!(i=s)||1!=i.readyState)throw new Error("Long poller failed to connect");i.send(e)},e.isConnected=function(){return n&&!0},e.transport=function(){return"lp"},e.probe=function(){e.sendText("1")}}"lp"===n?A(this):"ws"===n?R(this):"object"==("undefined"==typeof window?"undefined":s(window))&&window.WebSocket?R(this):A(this),this.backoffReset=function(){y=0},this.onMessage=void 0,this.onDisconnect=void 0,this.onOpen=void 0,this.onAutoreconnectIteration=void 0,this.logger=void 0},y=function(e,t,n,i,r,o){var a=this;this._appName=e||"Undefined",this._apiKey=n,this._browser="",this._platform=o,this._hwos="undefined",this._humanLanguage="xx","undefined"!=typeof navigator&&(this._browser=function(e,t){e=e||"";var n="";/reactnative/i.test(t)&&(n="ReactNative; ");var i,s=(e=e.replace(" (KHTML, like Gecko)","")).match(/(AppleWebKit\/[.\d]+)/i);if(s){for(var r=["chrome","safari","mobile","version"],o=e.substr(s.index+s[0].length).split(" "),a=[],c=function(e){var t=/([\w.]+)[\/]([\.\d]+)/.exec(o[e]);t&&a.push([t[1],t[2],r.findIndex(function(e){return e==t[1].toLowerCase()})])},u=0;u<o.length;u++)c(u);a.sort(function(e,t){var n=e[2]-t[2];return 0!=n?n:t[0].length-e[0].length}),i=a.length>0?a[0][0]+"/"+a[0][1]:s[1]}else i=/trident/i.test(e)?(s=/(?:\brv[ :]+([.\d]+))|(?:\bMSIE ([.\d]+))/g.exec(e))?"MSIE/"+(s[1]||s[2]):"MSIE/?":/firefox/i.test(e)?(s=/Firefox\/([.\d]+)/g.exec(e))?"Firefox/"+s[1]:"Firefox/?":/presto/i.test(e)?(s=/Opera\/([.\d]+)/g.exec(e))?"Opera/"+s[1]:"Opera/?":(s=/([\w.]+)\/([.\d]+)/.exec(e))?s[1]+"/"+s[2]:(s=e.split(" "))[0];if((s=i.split("/")).length>1){var h=s[1].split(".");i=s[0]+"/"+h[0]+(h[1]?"."+h[1]:"")}return n+i}(navigator.userAgent,navigator.product),this._hwos=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 S(t,n,i,r,!0),this.logger=function(e){if(a._loggingEnabled){for(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),i=arguments.length,s=new Array(i>1?i-1:0),r=1;r<i;r++)s[r-1]=arguments[r];console.log("["+n+"]",e,s.join(" "))}},this._connection.logger=this.logger,this._cache={};var c=this.cachePut=function(e,t,n){a._cache[e+":"+t]=n},d=this.cacheGet=function(e,t){return a._cache[e+":"+t]},f=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=d("user",e);if(t)return{user:e,public:v({},t)}},e._cachePutUser=function(e,t){return c("user",e,v({},t.public))},e._cacheDelUser=function(e){return f("user",e)},e._cachePutSelf=function(){return c("topic",e.name,e)},e._cacheDelSelf=function(){return f("topic",e.name)}};var g=function(e,t,n,i){var s=a._pendingPromises[e];s&&(delete a._pendingPromises[e],t>=200&&t<400?s.resolve&&s.resolve(n):s.reject&&s.reject(new Error(i+" ("+t+")")))},_=(setInterval(function(){var e=new Error("Timeout (504)"),t=new Date((new Date).getTime()-5e3);for(var n in a._pendingPromises){var i=a._pendingPromises[n];i&&i.ts<t&&(a.logger("Promise expired",n),delete a._pendingPromises[n],i.reject&&i.reject(e))}},1e3),this.getNextUniqueId=function(){return 0!=a._messageId?""+a._messageId++:void 0});this.initPacket=function(e,t){switch(e){case"hi":return{hi:{id:_(),ver:u,ua:a._appName+" ("+(a._browser?a._browser+"; ":"")+a._hwos+"); "+h,dev:a._deviceToken,lang:a._humanLanguage,platf:a._platform}};case"acc":return{acc:{id:_(),user:null,scheme:null,secret:null,login:!1,tags:null,desc:{},cred:{}}};case"login":return{login:{id:_(),scheme:null,secret:null}};case"sub":return{sub:{id:_(),topic:t,set:{},get:{}}};case"leave":return{leave:{id:_(),topic:t,unsub:!1}};case"pub":return{pub:{id:_(),topic:t,noecho:!1,head:null,content:{}}};case"get":return{get:{id:_(),topic:t,what:null,desc:{},sub:{},data:{}}};case"set":return{set:{id:_(),topic:t,desc:{},sub:{},tags:[]}};case"del":return{del:{id:_(),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){a._pendingPromises[e]={resolve:t,reject:n,ts:new Date}})),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"!=s(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 i=JSON.stringify(e);a.logger("out: "+(a._trimLongStrings?JSON.stringify(e,w):i));try{a._connection.sendText(i)}catch(r){if(!t)throw r;g(t,l,null,r.message)}return n},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)if(a._inPacketCount++,a.onRawMessage&&a.onRawMessage(e),"0"!==e){var t=JSON.parse(e,b);t?(a.logger("in: "+(a._trimLongStrings?JSON.stringify(t,w):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),setTimeout(function(){if(205==t.ctrl.code&&"evicted"==t.ctrl.text){var e=d("topic",t.ctrl.topic);e&&e._resetSub()}else if(t.ctrl.params&&"data"==t.ctrl.params.what){var n=d("topic",t.ctrl.topic);n&&n._allMessagesReceived(t.ctrl.params.count)}else if(t.ctrl.params&&"sub"==t.ctrl.params.what){var i=d("topic",t.ctrl.topic);i&&i._processMetaSub([])}},0)):setTimeout(function(){if(t.meta){var e=d("topic",t.meta.topic);e&&e._routeMeta(t.meta),t.meta.id&&g(t.meta.id,200,t.meta,"META"),a.onMetaMessage&&a.onMetaMessage(t.meta)}else if(t.data){var n=d("topic",t.data.topic);n&&n._routeData(t.data),a.onDataMessage&&a.onDataMessage(t.data)}else if(t.pres){var i=d("topic",t.pres.topic);i&&i._routePres(t.pres),a.onPresMessage&&a.onPresMessage(t.pres)}else if(t.info){var s=d("topic",t.info.topic);s&&s._routeInfo(t.info),a.onInfoMessage&&a.onInfoMessage(t.info)}else a.logger("ERROR: Unknown packet received.")},0)):(a.logger("in: "+e),a.logger("ERROR: failed to parse data"))}else a.onNetworkProbe&&a.onNetworkProbe()},this._connection.onOpen=function(){a.hello()},this._connection.onAutoreconnectIteration=function(e,t){a.onAutoreconnectIteration&&a.onAutoreconnectIteration(e,t)},this._connection.onDisconnect=function(e,t){for(var n in a._inPacketCount=0,a._serverInfo=null,a._authenticated=!1,p(function(e,t){0===t.lastIndexOf("topic:",0)&&e._resetSub()}),a._pendingPromises){var i=a._pendingPromises[n];i&&i.reject&&i.reject(e)}a._pendingPromises={},a.onDisconnect&&a.onDisconnect(e)}};y.credential=function(e,t,n,i){if("object"==s(e)){var r=e;t=r.val,n=r.params,i=r.resp,e=r.meth}return e&&(t||i)?[{meth:e,val:t,resp:i,params:n}]:null},y.topicType=function(e){return{me:"me",fnd:"fnd",grp:"grp",new:"grp",usr:"p2p",sys:"sys"}["string"==typeof e?e.substring(0,3):"xxx"]},y.isNewGroupTopicName=function(e){return"string"==typeof e&&"new"==e.substring(0,3)},y.getVersion=function(){return u},y.setWebSocketProvider=function(e){o=e},y.getLibrary=function(){return h},y.MESSAGE_STATUS_NONE=0,y.MESSAGE_STATUS_QUEUED=1,y.MESSAGE_STATUS_SENDING=2,y.MESSAGE_STATUS_FAILED=3,y.MESSAGE_STATUS_SENT=4,y.MESSAGE_STATUS_RECEIVED=5,y.MESSAGE_STATUS_READ=6,y.MESSAGE_STATUS_TO_ME=7,y.DEL_CHAR="\u2421",y.isNullValue=function(e){return e===y.DEL_CHAR},y.prototype={connect:function(e){return this._connection.connect(e)},reconnect:function(e){this._connection.reconnect(e)},disconnect:function(){this._connection.disconnect()},networkProbe:function(){this._connection.probe()},isConnected:function(){return this._connection.isConnected()},isAuthenticated:function(){return this._authenticated},account:function(e,t,n,i,s){var r=this.initPacket("acc");return r.acc.user=e,r.acc.scheme=t,r.acc.secret=n,r.acc.login=i,s&&(r.acc.desc.defacs=s.defacs,r.acc.desc.public=s.public,r.acc.desc.private=s.private,r.acc.tags=s.tags,r.acc.cred=s.cred,r.acc.token=s.token),this.send(r,r.acc.id)},createAccount:function(e,t,n,i){var s=this,r=this.account("new",e,t,n,i);return n&&(r=r.then(function(e){return s.loginSuccessful(e),e})),r},createAccountBasic:function(e,t,n){return e=e||"",t=t||"",this.createAccount("basic",g(e+":"+t),!0,n)},updateAccountBasic:function(e,t,n,i){return t=t||"",n=n||"",this.account(e,"basic",g(t+":"+n),!1,i)},hello:function(){var e=this,t=this.initPacket("hi");return this.send(t,t.hi.id).then(function(t){return e._connection.backoffReset(),t.params&&(e._serverInfo=t.params),e.onConnect&&e.onConnect(),t}).catch(function(t){e._connection.reconnect(!0),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 i=this,s=this.initPacket("login");return s.login.scheme=e,s.login.secret=t,s.login.cred=n,this.send(s,s.login.id).then(function(e){return i.loginSuccessful(e),e})},loginBasic:function(e,t,n){var i=this;return this.login("basic",g(e+":"+t),n).then(function(t){return i._login=e,t})},loginToken:function(e,t){return this.login("token",e,t)},requestResetAuthSecret:function(e,t,n){return this.login("reset",g(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 i=this.initPacket("sub",e);return e||(e="new"),i.sub.get=t,n&&(n.sub&&(i.sub.set.sub=n.sub),n.desc&&(y.isNewGroupTopicName(e)?i.sub.set.desc=n.desc:"p2p"==y.topicType(e)&&n.desc.defacs&&(i.sub.set.desc={defacs:n.desc.defacs})),n.tags&&(i.sub.set.tags=n.tags)),this.send(i,i.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(e,t,n){var i=this.initPacket("pub",e),s="string"==typeof t?r.parse(t):t;return s&&!r.isPlainText(s)&&(i.pub.head={mime:r.getContentType()},t=s),i.pub.noecho=n,i.pub.content=t,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=v(n.get,t),this.send(n,n.get.id)},setMeta:function(e,t){var n=this.initPacket("set",e),i=[];return t&&["desc","sub","tags","cred"].map(function(e){t.hasOwnProperty(e)&&(i.push(e),n.set[e]=t[e])}),0==i.length?Promise.reject(new Error("Invalid {set} parameters")):this.send(n,n.set.id)},delMessages:function(e,t,n){var i=this.initPacket("del",e);return i.del.what="msg",i.del.delseq=t,i.del.hard=n,this.send(i,i.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)},delCredential:function(e,t,n){if("me"!=e)throw new Error("Invalid topic for deleting credentials '"+e+"'");var i=this.initPacket("del",e);return i.del.what="cred",i.del.cred={meth:t,val:n},this.send(i,i.del.id)},note:function(e,t,n){if(n<=0||n>=268435455)throw new Error("Invalid message id "+n);var i=this.initPacket("note",e);i.note.what=t,i.note.seq=n,this.send(i)},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 E:"fnd"==e?new R:new D(e),this.cachePut("topic",e,t),this.attachCacheToTopic(t)),t},newTopic:function(e){var t=new D("new",e);return this.attachCacheToTopic(t),t},newGroupTopicName:function(){return"new"+this.getNextUniqueId()},newTopicWith:function(e,t){var n=new D(e,t);return this.attachCacheToTopic(n),n},getMeTopic:function(){return this.getTopic("me")},getFndTopic:function(){return this.getTopic("fnd")},getLargeFileHelper:function(){return new A(this)},getCurrentUserID:function(){return this._myUID},isMe:function(e){return this._myUID===e},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,onNetworkProbe:void 0,onAutoreconnectIteration:void 0};var x=function(e){this.topic=e;var t=e._tinode.getMeTopic();this.contact=t&&t.getContact(e.name),this.what={}};x.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 i={ims:e,limit:t};return"me"==this.topic.getType()?i.topic=n:i.user=n,this.what.sub=i,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},withCred:function(){return"me"==this.topic.getType()?this.what.cred=!0:this.topic._tinode.logger("ERROR: Invalid topic type for MetaGetBuilder:withCreds",this.topic.getType()),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=this,n={};return["data","sub","desc","tags","cred","del"].map(function(i){t.what.hasOwnProperty(i)&&(e.push(i),Object.getOwnPropertyNames(t.what[i]).length>0&&(n[i]=t.what[i]))}),e.length>0?n.what=e.join(" "):n=void 0,n}};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._checkFlag=function(e,t,n){if(["given","want","mode"].includes(t=t||"mode"))return 0!=(e[t]&n);throw new Error("Invalid AccessMode component '"+t+"'")},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,i=0;i<e.length;i++){var s=t[e.charAt(i).toUpperCase()];s&&(n|=s)}return n},T.encode=function(e){if(null===e||e===T._INVALID)return null;if(e===T._NONE)return"N";for(var t=["J","R","W","P","A","S","D","O"],n="",i=0;i<t.length;i++)0!=(e&1<<i)&&(n+=t[i]);return n},T.update=function(e,t){if(!t||"string"!=typeof t)return e;var n=t.charAt(0);if("+"==n||"-"==n){for(var i=e,s=t.split(/([-+])/),r=1;r<s.length-1;r+=2){n=s[r];var o=T.decode(s[r+1]);if(o==T._INVALID)return e;null!=o&&("+"===n?i|=o:"-"===n&&(i&=~o))}e=i}else{var a=T.decode(t);a!=T._INVALID&&(e=a)}return e},T.prototype={toString:function(){return'{"mode": "'+T.encode(this.mode)+'", "given": "'+T.encode(this.given)+'", "want": "'+T.encode(this.want)+'"}'},jsonHelper:function(){return{mode:T.encode(this.mode),given:T.encode(this.given),want:T.encode(this.want)}},setMode:function(e){return this.mode=T.decode(e),this},updateMode:function(e){return this.mode=T.update(this.mode,e),this},getMode:function(){return T.encode(this.mode)},setGiven:function(e){return this.given=T.decode(e),this},updateGiven:function(e){return this.given=T.update(this.given,e),this},getGiven:function(){return T.encode(this.given)},setWant:function(e){return this.want=T.decode(e),this},updateWant:function(e){return this.want=T.update(this.want,e),this},getWant:function(){return T.encode(this.want)},getMissing:function(){return T.encode(this.want&~this.given)},getExcessive:function(){return T.encode(this.given&~this.want)},updateAll:function(e){return e&&(this.updateGiven(e.given),this.updateWant(e.want),this.mode=this.given&this.want),this},isOwner:function(e){return T._checkFlag(this,e,T._OWNER)},isPresencer:function(e){return T._checkFlag(this,e,T._PRES)},isMuted:function(e){return!this.isPresencer(e)},isJoiner:function(e){return T._checkFlag(this,e,T._JOIN)},isReader:function(e){return T._checkFlag(this,e,T._READ)},isWriter:function(e){return T._checkFlag(this,e,T._WRITE)},isApprover:function(e){return T._checkFlag(this,e,T._APPROVE)},isAdmin:function(e){return this.isOwner(e)||this.isApprover(e)},isSharer:function(e){return this.isAdmin(e)||T._checkFlag(this,e,T._SHARE)},isDeleter:function(e){return T._checkFlag(this,e,T._DELETE)}};var D=function(e,t){this._tinode=null,this.name=e,this.created=null,this.updated=null,this.touched=null,this.acs=new T(null),this.private=null,this.public=null,this._users={},this._queuedSeqId=268435455,this._maxSeq=0,this._minSeq=0,this._noEarlierMsgs=!1,this._maxDel=0,this._tags=[],this._credentials=[],this._messages=function(e,t){var n=[];function i(t,n,i){for(var s=0,r=n.length-1,o=0,a=0,c=!1;s<=r;)if((a=e(n[o=(s+r)/2|0],t))<0)s=o+1;else{if(!(a>0)){c=!0;break}r=o-1}return c?{idx:o,exact:!0}:i?{idx:-1}:{idx:a<0?o+1:o}}return e=e||function(e,t){return e===t?0:e<t?-1:1},{getAt:function(e){return n[e]},getLast:function(){return n.length>0?n[n.length-1]:void 0},put:function(){var e,t,s,r,o;for(var a in e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments)void 0,void 0,o=(r=i(t=e[a],s=n,!1)).exact?1:0,s.splice(r.idx,o,t)},delAt:function(e){var t=n.splice(e,1);if(t&&t.length>0)return t[0]},delRange:function(e,t){return n.splice(e,t-e)},contains:function(){return n.length},reset:function(){n=[]},forEach:function(e,t,i,s){t|=0,i=i||n.length;for(var r=t;r<i;r++)e.call(s,n[r],r)},find:function(e,t){return i(e,n,!t).idx}}}(function(e,t){return e.seq-t.seq}),this._subscribed=!1,this._lastDescUpdate=null,this._lastSubsUpdate=null,this._new=!0,t&&(this.onData=t.onData,this.onMeta=t.onMeta,this.onPres=t.onPres,this.onInfo=t.onInfo,this.onMetaDesc=t.onMetaDesc,this.onMetaSub=t.onMetaSub,this.onSubsUpdated=t.onSubsUpdated,this.onTagsUpdated=t.onTagsUpdated,this.onCredsUpdated=callbacls.onCredsUpdated,this.onDeleteTopic=t.onDeleteTopic,this.onAllMessagesReceived=t.onAllMessagesReceived)};D.prototype={isSubscribed:function(){return this._subscribed},subscribe:function(e,t){var n=this;return this._subscribed?Promise.resolve(this):this._tinode.subscribe(this.name||"new",e,t).then(function(e){if(e.code>=300)return e;if(n._subscribed=!0,n.acs=e.params&&e.params.acs?e.params.acs:n.acs,n._new){if(n._new=!1,n.name=e.topic,n.created=e.ts,n.updated=e.ts,n._cachePutSelf(),"me"!=n.name&&"fnd"!=n.name){var i=n._tinode.getMeTopic();i&&i._processMetaSub([{_noForwarding:!0,topic:n.name,created:e.ts,updated:e.ts,acs:n.acs}])}t&&t.desc&&(t.desc._noForwarding=!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(e){var t=this;if(!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));if(r.hasAttachments(e.content)&&!e.head.attachments){var n=[];r.attachments(e.content,function(e){n.push(e.ref)}),e.head.attachments=n}return e._sending=!0,e._failed=!1,this._tinode.publishMessage(e).then(function(n){return e._sending=!1,e.seq=n.params.seq,e.ts=n.ts,t._routeData(e),n}).catch(function(n){t._tinode.logger("WARNING: Message rejected by the server",n),e._sending=!1,e._failed=!0,t.onData&&t.onData()})},publishDraft:function(e,t){var n=this;if(!t&&!this._subscribed)return Promise.reject(new Error("Cannot publish on inactive topic"));var i=e.seq||this._getQueuedSeqId();return e._noForwarding||(e._noForwarding=!0,e.seq=i,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){n._tinode.logger("WARNING: Message draft rejected by the server",t),e._sending=!1,e._failed=!0,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._tinode.getMeta(this.name,e)},getMessagesPage:function(e,t){var n=this,i=this.startMetaQuery();t?i.withLaterData(e):i.withEarlierData(e);var s=this.getMeta(i.build());return t||(s=s.then(function(e){e&&e.params&&!e.params.count&&(n._noEarlierMsgs=!0)})),s},setMeta:function(e){var t=this;return e.tags&&(e.tags=function(e){var t=[];if(Array.isArray(e)){for(var n=0,i=e.length;n<i;n++){var s=e[n];s&&(s=s.trim().toLowerCase()).length>1&&t.push(s)}t.sort().filter(function(e,t,n){return!t||e!=n[t-1]})}return 0==t.length&&t.push(y.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._noForwarding=!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),e.cred&&t._processMetaCreds([e.cred],!0),n)})},updateMode:function(e,t){var n,i=e?(function(e){throw new Error('"user" is read-only')}(),i=this.subscriber(e)):null;return n=i?i.acs.updateGiven(t).getGiven():topic.getAccessMode().updateWant(t).getWant(),topic.setMeta({sub:{user:e,mode:n}})},invite:function(e,t){return this.setMeta({sub:{user:e,mode:t}})},archive:function(e){return this.private&&this.private.arch==e?Promise.resolve(e):this.setMeta({desc:{private:{arch:!!e||y.DEL_CHAR}}})},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.low||e.low==t.low&&(!t.hi||e.hi>=t.hi)});var i=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(i.length>0?this._tinode.delMessages(this.name,i,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._updateDeletedRanges(),n.onData&&n.onData(),t})},delMessagesAll:function(e){return!this._maxSeq||this._maxSeq<=0?Promise.resolve():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]<t)&&(this._subscribed?this._tinode.note(this.name,e,t):this._tinode.logger("INFO: Not sending {note} on inactive topic"),n[e]=t):this._tinode.logger("ERROR: note(): user not found "+this._tinode.getCurrentUserID());var i=this._tinode.getMeTopic();i&&i.setMsgReadRecv(this.name,e,t)},noteRecv:function(e){this.note("recv",e)},noteRead:function(e){this.note("read",e)},noteKeyPress:function(){this._subscribed?this._tinode.noteKeyPress(this.name):this._tinode.logger("INFO: Cannot send notification in inactive topic")},userDesc:function(e){var t=this._cacheGetUser(e);if(t)return t},p2pPeerDesc:function(){if("p2p"==this.getType())return this._users[this.name]},subscribers:function(e,t){var n=e||this.onMetaSub;if(n)for(var i in this._users)n.call(t,this._users[i],i,this._users)},tags:function(){return this._tags.slice(0)},subscriber:function(e){return this._users[e]},messages:function(e,t,n,i){var s=e||this.onData;if(s){var r="number"==typeof t?this._messages.find({seq:t}):void 0,o="number"==typeof n?this._messages.find({seq:n},!0):void 0;-1!=r&&-1!=o&&this._messages.forEach(s,r,o,i)}},queuedMessages:function(e,t){if(!e)throw new Error("Callback must be provided");this.messages(e,268435455,void 0,t)},msgReceiptCount:function(e,t){var n=0;if(t>0){var i=this._tinode.getCurrentUserID();for(var s in this._users){var r=this._users[s];r.user!==i&&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},!0);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),i=this.msgStatus(n);if(1==i||3==i)return n._cancelled=!0,this._messages.delAt(t),this.onData&&this.onData(),!0}return!1},getType:function(){return y.topicType(this.name)},getAccessMode:function(){return this.acs},getDefaultAccess:function(){return this.defacs},startMetaQuery:function(){return new x(this)},isArchived:function(){return!(!this.private||!this.private.arch)},msgStatus:function(e){var t=0;return this._tinode.isMe(e.from)?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.touched<e.ts)&&(this.touched=e.ts),e._noForwarding||(this._messages.put(e),this._updateDeletedRanges()),e.seq>this._maxSeq&&(this._maxSeq=e.seq),(e.seq<this._minSeq||0==this._minSeq)&&(this._minSeq=e.seq),this.onData&&this.onData(e);var t=this._tinode.getMeTopic();t&&t.setMsgReadRecv(this.name,!e.from||this._tinode.isMe(e.from)?"read":"msg",e.seq,e.ts)},_routeMeta:function(e){e.desc&&(this._lastDescUpdate=e.ts,this._processMetaDesc(e.desc)),e.sub&&e.sub.length>0&&(this._lastSubsUpdate=e.ts,this._processMetaSub(e.sub)),e.del&&this._processDelMessages(e.del.clear,e.del.delseq),e.tags&&this._processMetaTags(e.tags),e.cred&&this._processMetaCreds(e.cred),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("WARNING: Presence update for an unknown user",this.name,e.src);break;case"term":this._resetSub();break;case"acs":if(t=this._users[e.src])t.acs.updateAll(e.dacs),this._processMetaSub([{user:e.src,updated:new Date,acs:t.acs}]);else{var n=(new T).updateAll(e.dacs);n&&n.mode!=T._NONE&&((t=this._cacheGetUser(e.src))?t.acs=n:(t={user:e.src,acs:n},this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build())),t.updated=new Date,this._processMetaSub([t]))}break;default:this._tinode.logger("INFO: Ignored presence update",e.what)}this.onPres&&this.onPres(e)},_routeInfo:function(e){if("kp"!==e.what){var t=this._users[e.from];if(t&&(t[e.what]=e.seq,t.recv<t.read&&(t.recv=t.read)),this._tinode.isMe(e.from)){var n=this._tinode.getMeTopic();n&&n.setMsgReadRecv(e.topic,e.what,e.seq)}}this.onInfo&&this.onInfo(e)},_processMetaDesc:function(e){if("p2p"==this.getType()&&delete e.defacs,v(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&&!e._noForwarding){var t=this._tinode.getMeTopic();t&&t._processMetaSub([{_noForwarding:!0,topic:this.name,updated:this.updated,touched:this.touched,acs:e.acs,seq:e.seq,read:e.read,recv:e.recv,public:e.public,private:e.private}])}this.onMetaDesc&&this.onMetaDesc(this)},_processMetaSub:function(e){for(var t in e){var n=e[t];n.updated=new Date(n.updated),n.deleted=n.deleted?new Date(n.deleted):null;var i=null;n.deleted?(delete this._users[n.user],i=n):(this._tinode.isMe(n.user)&&n.acs&&this._processMetaDesc({updated:n.updated||new Date,touched:n.updated,acs:n.acs}),i=this._updateCachedUser(n.user,n)),this.onMetaSub&&this.onMetaSub(i)}this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._users))},_processMetaTags:function(e){1==e.length&&e[0]==y.DEL_CHAR&&(e=[]),this._tags=e,this.onTagsUpdated&&this.onTagsUpdated(e)},_processMetaCreds:function(e){},_processDelMessages:function(e,t){this._maxDel=Math.max(e,this._maxDel),this.clear=Math.max(e,this.clear);var n=this,i=0;Array.isArray(t)&&t.map(function(e){if(e.hi)for(var t=e.low;t<e.hi;t++)i++,n.flushMessage(t);else i++,n.flushMessage(e.low)}),i>0&&(this._updateDeletedRanges(),this.onData&&this.onData())},_allMessagesReceived:function(e){this._updateDeletedRanges(),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({_noForwarding:!0,what:"gone",topic:"me",src:this.name}),this.onDeleteTopic&&this.onDeleteTopic()},_updateCachedUser:function(e,t){var n=this._cacheGetUser(e);return n=v(n||{},t),this._cachePutUser(e,n),_(this._users,e,n)},_getQueuedSeqId:function(){return this._queuedSeqId++},_updateDeletedRanges:function(){var e=this,t=[],n=null,i=this._messages.getAt(0);i&&this._minSeq>1&&!this._noEarlierMsgs?i.hi?(i.seq>1&&(i.seq=1),i.hi<this._minSeq-1&&(i.hi=this._minSeq-1),n=i):(n={seq:1,hi:this._minSeq-1},t.push(n)):n={seq:0,hi:0},this._messages.forEach(function(e){e.seq!=(n.hi||n.seq)+1?n.hi?n.hi=e.hi||e.seq:(n={seq:(n.hi||n.seq)+1,hi:e.hi||e.seq},t.push(n)):n=e});var s=this._messages.getLast(),r=Math.max(this.seq,this._maxSeq);(!s||s&&(s.hi||s.seq)<r)&&(s&&s.hi?s.hi=r:t.push({seq:s?s.seq+1:1,hi:r})),t.map(function(t){e._messages.put(t)})}};var E=function(e){D.call(this,"me",e),this._contacts={},e&&(this.onContactUpdate=e.onContactUpdate)};E.prototype=Object.create(D.prototype,{_processMetaSub:{value:function(e){var t=0;for(var n in e){var i=e[n],s=i.topic;if("fnd"!=s&&"me"!=s){i.updated=new Date(i.updated),i.touched=i.touched?new Date(i.touched):void 0,i.deleted=i.deleted?new Date(i.deleted):null;var r=null;if(i.deleted)r=i,delete this._contacts[s];else if(i.acs&&!i.acs.isJoiner())(r=i).deleted=new Date,delete this._contacts[s];else if(void 0!==i.seq&&(i.seq=0|i.seq,i.recv=0|i.recv,i.read=0|i.read,i.unread=i.seq-i.read),i.seen&&i.seen.when&&(i.seen.when=new Date(i.seen.when)),r=_(this._contacts,s,i),"p2p"==y.topicType(s)&&this._cachePutUser(s,r),!i._noForwarding){var o=this._tinode.getTopic(s);o&&(i._noForwarding=!0,o._processMetaDesc(i))}t++,this.onMetaSub&&this.onMetaSub(r)}}this.onSubsUpdated&&this.onSubsUpdated(Object.keys(this._contacts),t)},enumerable:!0,configurable:!0,writable:!1},_processMetaCreds:{value:function(e,t){var n=this;1==e.length&&e[0]==y.DEL_CHAR&&(e=[]),t?e.map(function(e){if(e.val){var t=n._credentials.findIndex(function(t){return t.meth==e.meth&&t.val==e.val});t<0?(e.done||(t=n._credentials.findIndex(function(t){return t.meth==e.meth&&!t.done}))>=0&&n._credentials.splice(t,1),n._credentials.push(e)):n._credentials[t].done=e.done}else if(e.resp){var i=n._credentials.findIndex(function(t){return t.meth==e.meth&&!t.done});i>=0&&(n._credentials[i].done=!0)}}):this._credentials=e,this.onCredsUpdated&&this.onCredsUpdated(this._credentials)},enumerable:!0,configurable:!0,writable:!1},_routePres:{value:function(e){if("term"!=e.what)if("upd"!=e.what||"me"!=e.src){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,e.act&&!this._tinode.isMe(e.act)||(t.read=t.read?Math.max(t.read,t.seq):t.seq,t.recv=t.recv?Math.max(t.read,t.recv):t.recv),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),t.touched=new Date;break;case"ua":t.seen={when:new Date,ua:e.ua};break;case"recv":e.seq=0|e.seq,t.recv=t.recv?Math.max(t.recv,e.seq):e.seq;break;case"read":e.seq=0|e.seq,t.read=t.read?Math.max(t.read,e.seq):e.seq,t.recv=t.recv?Math.max(t.read,t.recv):t.recv,t.unread=t.seq-t.read;break;case"gone":delete this._contacts[e.src];break;case"del":break;default:this._tinode.logger("INFO: Unsupported presence update in 'me'",e.what)}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("ERROR: Invalid access mode update",e.src,e.dacs);if(n.mode==T._NONE)return void this._tinode.logger("WARNING: Removing non-existent subscription",e.src,e.dacs);this.getMeta(this.startMetaQuery().withOneSub(void 0,e.src).build()),this._contacts[e.src]={touched:new Date,topic:e.src,online:!1,acs:n}}else"tags"==e.what&&this.getMeta(this.startMetaQuery().withTags().build());this.onPres&&this.onPres(e)}else this.getMeta(this.startMetaQuery().withDesc().build());else this._resetSub()},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},delCredential:{value:function(e,t){var n=this;return this._subscribed?this._tinode.delCredential(this.name,e,t).then(function(i){var s=n._credentials.findIndex(function(n){return n.meth==e&&n.val==t});return s>-1&&n._credentials.splice(s,1),n.onCredsUpdated&&n.onCredsUpdated(n._credentials),i}):Promise.reject(new Error("Cannot delete credential in inactive 'me' topic"))},enumerable:!0,configurable:!0,writable:!1},contacts:{value:function(e,t,n){var i=e||this.onMetaSub;if(i)for(var s in this._contacts)(t||this._contacts[s]&&this._contacts[s].acs&&this._contacts[s].acs.isJoiner())&&i.call(n,this._contacts[s],s,this._contacts)},enumerable:!0,configurable:!0,writable:!0},setMsgReadRecv:{value:function(e,t,n,i){var s,r=this._contacts[e],o=!1;if(r){switch(n|=0,r.seq=0|r.seq,r.read=0|r.read,r.recv=0|r.recv,t){case"recv":s=r.recv,r.recv=Math.max(r.recv,n),o=s!=r.recv;break;case"read":s=r.read,r.read=Math.max(r.read,n),o=s!=r.read;break;case"msg":s=r.seq,r.seq=Math.max(r.seq,n),(!r.touched||r.touched<i)&&(r.touched=i),o=s!=r.seq}r.recv<r.read&&(r.recv=r.read,o=!0),r.seq<r.recv&&(r.seq=r.recv,(!r.touched||r.touched<i)&&(r.touched=i),o=!0),r.unread=r.seq-r.read,!o||r.acs&&r.acs.isMuted()||!this.onContactUpdate||this.onContactUpdate(t,r)}},enumerable:!0,configurable:!0,writable:!0},getContact:{value:function(e){return this._contacts[e]},enumerable:!0,configurable:!0,writable:!0},getAccessMode:{value:function(e){var t=this._contacts[e];return t?t.acs:null},enumerable:!0,configurable:!0,writable:!0},isArchived:{value:function(e){var t=this._contacts[e];return t?!(!t.private||!t.private.arch):null},enumerable:!0,configurable:!0,writable:!0},getCredentials:{value:function(){return this._credentials},enumerable:!0,configurable:!0,writable:!0}}),E.prototype.constructor=E;var R=function(e){D.call(this,"fnd",e),this._contacts={}};R.prototype=Object.create(D.prototype,{_processMetaSub:{value:function(e){var t=Object.getOwnPropertyNames(this._contacts).length;for(var n in this._contacts={},e){var i=e[n],s=i.topic?i.topic:i.user;i.updated=new Date(i.updated),i.seen&&i.seen.when&&(i.seen.when=new Date(i.seen.when)),i=_(this._contacts,s,i),t++,this.onMetaSub&&this.onMetaSub(i)}t>0&&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(R.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 i in this._contacts)n.call(t,this._contacts[i],i,this._contacts)},enumerable:!0,configurable:!0,writable:!0}}),R.prototype.constructor=R;var A=function(e){this._tinode=e,this._apiKey=e._apiKey,this._authToken=e.getAuthToken(),this._msgId=e.getNextUniqueId(),this.xhr=m(),this.toResolve=null,this.toReject=null,this.onProgress=null,this.onSuccess=null,this.onFailure=null};A.prototype={uploadWithBaseUrl:function(e,t,n,i,s){var r=this;if(!this._authToken)throw new Error("Must authenticate first");var o=this,a="/v"+c+"/file/u/";if(e){if(0!=e.indexOf("http://")&&0!=e.indexOf("https://"))throw new Error("Invalid base URL '"+e+"'");a=e+a}this.xhr.open("POST",a,!0),this.xhr.setRequestHeader("X-Tinode-APIKey",this._apiKey),this.xhr.setRequestHeader("X-Tinode-Auth","Token "+this._authToken.token);var u=new Promise(function(e,t){r.toResolve=e,r.toReject=t});this.onProgress=n,this.onSuccess=i,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,b)}catch(t){o._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.response),e={ctrl:{code:this.status,text:this.statusText}}}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("ERROR: 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 h=new FormData;h.append("file",t),h.set("id",this._msgId),this.xhr.send(h)}catch(l){this.toReject&&this.toReject(l),this.onFailure&&this.onFailure(null)}return u},upload:function(e,t,n,i){return this.uploadWithBaseUrl(void 0,e,t,n,i)},download:function(e,t,n,i){var s=this;if(/^\s*([a-z][a-z0-9+.-]*:|\/\/)/im.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=i,this.xhr.onprogress=function(e){r.onProgress&&r.onProgress(e.loaded)};var o=new Promise(function(e,t){s.toResolve=e,s.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 i=new FileReader;i.onload=function(){try{var e=JSON.parse(this.result,b);r.toReject(new Error(e.ctrl.text+" ("+e.ctrl.code+")"))}catch(t){r._tinode.logger("ERROR: Invalid server response in LargeFileHelper",this.result),r.toReject(t)}},i.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(a){this.toReject&&this.toReject(a)}return o},cancel:function(){this.xhr&&this.xhr.readyState<4&&this.xhr.abort()},getId:function(){return this._msgId}};var k=function e(t,n){this.status=e.STATUS_NONE,this.topic=t,this.content=n};k.STATUS_NONE=0,k.STATUS_QUEUED=1,k.STATUS_SENDING=2,k.STATUS_FAILED=3,k.STATUS_SENT=4,k.STATUS_RECEIVED=5,k.STATUS_READ=6,k.STATUS_TO_ME=7,(k.prototype={toJSON:function(){},fromJSON:function(e){}}).constructor=k,i.exports=y,i.exports.Drafty=r}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),i=i.exports}); |