mirror of
https://github.com/unraid/webgui.git
synced 2026-01-14 13:39:58 -06:00
2 lines
14 KiB
JavaScript
2 lines
14 KiB
JavaScript
/* NchanSubscriber */
|
|
!function(t,e,s){"use strict";var i=function(t,e){var s={};function i(t){return t?function(t){for(var e in i.prototype)t[e]=i.prototype[e];return t}(t):void 0}(function(){var i=["responseType","withCredentials","timeout","onprogress"];function r(t,e,s){t[e]=t[e]||s}s.ajax=function(s,n){var a=s.headers||{},o=s.body,h=s.method||(o?"POST":"GET"),c=!1,l=function(e){if(e&&t.XDomainRequest&&!/MSIE 1/.test(navigator.userAgent))return new XDomainRequest;if(t.XMLHttpRequest)return new XMLHttpRequest}(s.cors);function d(t,s){return function(){c||(n(l.status===e?t:l.status,0===l.status?"Error":l.response||l.responseText||s,l),c=!0)}}l.open(h,s.url,!0);var u=l.onload=d(200);l.onreadystatechange=function(){4===l.readyState&&u()},l.onerror=d(null,"Error"),l.ontimeout=d(null,"Timeout"),l.onabort=d(null,"Abort"),o&&(r(a,"X-Requested-With","XMLHttpRequest"),t.FormData&&o instanceof t.FormData||r(a,"Content-Type","application/x-www-form-urlencoded"));for(var p=0,m=i.length;p<m;p++)s[f=i[p]]!==e&&(l[f]=s[f]);for(var f in a)l.setRequestHeader(f,a[f]);return l.send(o),l}})(),i.prototype.on=i.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},i.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},i.prototype.off=i.prototype.removeListener=i.prototype.removeAllListeners=i.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s=this._callbacks["$"+t];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i,r=0;r<s.length;r++)if((i=s[r])===e||i.fn===e){s.splice(r,1);break}return this},i.prototype.emit=function(t){this._callbacks=this._callbacks||{};var e=[].slice.call(arguments,1),s=this._callbacks["$"+t];if(s){s=s.slice(0);for(var i=0,r=s.length;r>i;++i)s[i].apply(this,e)}return this},i.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},i.prototype.hasListeners=function(t){return!!this.listeners(t).length};var r,n=Function.prototype.bind?function(t,e){return t.bind(e)}:function(t,e){return function(){t.apply(e,arguments)}},a={};function o(e,s){if("undefined"!=typeof window&&this===window)throw"use 'new NchanSubscriber(...)' to initialize";if(this.url=e,"string"==typeof(s=s||{})&&(s={subscriber:s}),s.transport&&!s.subscriber&&(s.subscriber=s.transport),"string"==typeof s.subscriber&&(s.subscriber=[s.subscriber]),this.desiredTransport=s.subscriber,s.shared){if(!("localStorage"in t))throw"localStorage unavailable for use in shared NchanSubscriber";var i="NchanSubscriber:"+this.url+":shared:",r=function(t){return i+t},a=t.localStorage;this.shared={id:""+Math.random()+Math.random(),key:r,get:function(t){return a.getItem(r(t))},set:function(t,e){return a.setItem(r(t),e)},setWithId:n(function(t,e){return this.shared.set(t,"##"+this.shared.id+":"+e)},this),getWithId:n(function(t){return this.shared.stripIdFromVal(this.shared.get(t))},this),stripIdFromVal:function(t){if(!t)return t;var e=t.indexOf(":");return t[0]==t[1]&&"#"==t[0]&&e?t.substring(e+1,t.length):t},remove:function(t){return a.removeItem(r(t))},matchEventKey:n(function(t,e){return(!t.storageArea||t.storageArea==a)&&t.key==r(e)},this),matchEventKeyWithId:n(function(t,e){if(this.shared.matchEventKey(t,e)){var s=t.newValue,i=s.indexOf(":");if(s[0]!=s[1]||"#"!=s[0]||!i)return!0;var r=s.substring(2,i);return r!=this.shared.id}return!1},this),setRole:n(function(t){if("master"==t&&"master"!=this.shared.role){var e=(new Date).getTime()/1e3;this.shared.setWithId("master:created",e),this.shared.setWithId("master:lastSeen",e)}return"slave"!=t||this.lastMessageId||(this.lastMessageId=this.shared.get("msg:id")),this.shared.role=t,this},this),demoteToSlave:n(function(){if("master"!=this.shared.role)throw"can't demote non-master to slave";this.running?(this.stop(),this.shared.setRole("slave"),this.initializeTransport(),this.start()):this.initializeTransport()},this),maybePromoteToMaster:n(function(){if(!this.running&&!this.starting)return this;if(!this.shared.maybePromotingToMaster){var e;this.shared.maybePromotingToMaster=!0;var s,i=0,r=Math.random(),a=r,o=n(function(t){var s=parseFloat(this.shared.getWithId("lotteryTime")),i=parseFloat(this.shared.getWithId("lottery")),r=!s||s>(new Date).getTime()-4e3;r&&i&&(!a||i>a)&&(a=i),t||e()},this);o(!0),this.shared.setWithId("lottery",r),this.shared.setWithId("lotteryTime",(new Date).getTime()/1e3);var h=n(function(t){if(this.shared.matchEventKeyWithId(t,"lottery")&&t.newValue){i+=1;var e=parseFloat(this.shared.stripIdFromVal(t.newValue)),s=parseFloat(this.shared.stripIdFromVal(t.oldValue));s>e&&this.shared.setWithId("lottery",s),(!a||e>=a)&&(a=e)}},this);t.addEventListener("storage",h);var c=n(function(){this.shared.maybePromotingToMaster=!1,t.removeEventListener("storage",h),s&&clearInterval(s),this.shared&&"master"==this.shared.role&&(this.shared.remove("lottery"),this.shared.remove("lotteryTime")),this.running?(this.stop(),this.initializeTransport(),this.start()):(this.initializeTransport(),this.starting&&this.start())},this);e=n(function(){r<a?(this.shared.setRole("slave"),c()):r>=a&&(0==i?(this.shared.setRole("master"),c()):i=0)},this),s=t.setInterval(o,2e3)}},this),masterCheckInterval:1e4}}var o;if(this.lastMessageId=s.id||s.msgId,this.reconnect=void 0===s.reconnect||s.reconnect,this.reconnectTimeout=s.reconnectTimeout||1e3,s.reconnect){var h,c="NchanSubscriber:"+e+":lastMessageId";if("persist"==s.reconnect){if(!(h="localStorage"in t&&t.localStorage))throw"can't use reconnect: 'persist' option: localStorage not available"}else{if("session"!=s.reconnect)throw"invalid 'reconnect' option value "+s.reconnect;if(!(h="sessionStorage"in t&&t.sessionStorage))throw"can't use reconnect: 'session' option: sessionStorage not available"}o=n(function(t){this.shared&&"slave"==this.shared.role||h.setItem(c,t)},this),this.lastMessageId=h.getItem(c)}else o=function(){};var l,d,u=n(function(){this.running&&this.stop(),this.shared&&"master"==this.shared.role&&this.shared.setWithId("status","disconnected")},this);t.addEventListener("beforeunload",u,!1),t.addEventListener("DOMContentLoaded",function(){t.removeEventListener("beforeunload",u,!1),t.addEventListener("unload",u,!1)},!1),l=this.shared?n(function(t,e){"master"==this.shared.role&&("message"==t?(this.shared.set("msg:id",e[1]&&e[1].id||""),this.shared.set("msg:content-type",e[1]&&e[1]["content-type"]||""),this.shared.set("msg",e[0])):"error"==t||("connecting"==t?this.shared.setWithId("status","connecting"):"connect"==t?this.shared.setWithId("status","connected"):"reconnect"==t?this.shared.setWithId("status","reconnecting"):"disconnect"==t&&this.shared.setWithId("status","disconnected")))},this):function(){};var p=n(function(){d||!this.running||!this.reconnect||this.transport.reconnecting||this.transport.doNotReconnect?l("disconnect"):(l("reconnect"),d=t.setTimeout(n(function(){d=null,this.stop(),this.start()},this),this.reconnectTimeout))},this);this.on("message",function(t,e){this.lastMessageId=e.id,e.id&&o(e.id),l("message",[t,e])}),this.on("error",function(t,e){p(t,e),l("error",[t,e])}),this.on("connect",function(){this.connected=!0,l("connect")}),this.on("__disconnect",function(t,e){this.connected=!1,this.emit("disconnect",t,e),p(t,e)})}function h(t,e){if(e){var s=t.match(/(\?.*)$/);t+=(s?"&":"?")+"last_event_id="+encodeURIComponent(e)}return t}return i(o.prototype),o.prototype.initializeTransport=function(t){if(t&&(this.desiredTransport=t),this.shared&&"slave"==this.shared.role)this.transport=new this.SubscriberClass.__slave(n(this.emit,this));else{var e,s=n(function(t){if(!this.SubscriberClass[t])throw"unknown subscriber type "+t;try{return this.transport=new this.SubscriberClass[t](n(this.emit,this)),this.transport}catch(t){}},this);if(this.desiredTransport)for(e=0;e<this.desiredTransport.length&&!s(this.desiredTransport[e]);e++);else for(e in this.SubscriberClass)if(this.SubscriberClass.hasOwnProperty(e)&&"_"!=e[0]&&s(e))break}if(!this.transport)throw"can't use any transport type"},o.prototype.start=function(){if(this.running)throw"Can't start NchanSubscriber, it's already started.";if(this.starting=!0,this.shared){if(a[this.url]&&a[this.url]!=this)throw"Only 1 shared subscriber allowed per url per window/tab.";if(a[this.url]=this,!this.shared.role){var e=this.shared.getWithId("status");r=n(function(t){this.shared.matchEventKeyWithId(t,"status")?"disconnected"==this.shared.stripIdFromVal(t.newValue)&&("slave"==this.shared.role?this.shared.maybePromoteToMaster():this.shared.role):"master"==this.shared.role&&this.shared.matchEventKeyWithId(t,"master:created")&&t.newValue&&this.shared.demoteToSlave()},this),t.addEventListener("storage",r),"disconnected"==e?this.shared.maybePromoteToMaster():(this.shared.setRole(e?"slave":"master"),this.initializeTransport())}"master"==this.shared.role?(this.shared.setWithId("status","connecting"),this.transport.listen(this.url,this.lastMessageId),this.running=!0,delete this.starting,this.shared.masterIntervalCheckID=t.setInterval(n(function(){this.shared.setWithId("master:lastSeen",(new Date).getTime()/1e3)},this),.8*this.shared.masterCheckInterval)):"slave"==this.shared.role&&(this.transport.listen(this.url,this.shared),this.running=!0,delete this.starting,this.shared.masterIntervalCheckID=t.setInterval(n(function(){var t=parseFloat(this.shared.getWithId("master:lastSeen"));(!t||t<(new Date).getTime()/1e3-this.shared.masterCheckInterval/1e3)&&this.shared.maybePromoteToMaster()},this),this.shared.masterCheckInterval))}else this.transport||this.initializeTransport(),this.transport.listen(this.url,this.lastMessageId),this.running=!0,delete this.starting;return this},o.prototype.stop=function(){if(!this.running)throw"Can't stop NchanSubscriber, it's not running.";return this.running=!1,r&&t.removeEventListener("storage",r),this.transport.cancel(),this.shared&&(delete a[this.url],this.shared.masterIntervalCheckID&&(clearInterval(this.shared.masterIntervalCheckID),delete this.shared.masterIntervalCheckID)),this},o.prototype.SubscriberClass={eventsource:function(){function t(t){EventSource,this.emit=t}return t.prototype.listen=function(t,e){if(t=h(t,e),this.listener)throw"there's a ES listener running already";this.listener=new EventSource(t);var s=this.listener;s.onmessage=n(function(t){this.emit("message",t.data,{id:t.lastEventId})},this),s.onopen=n(function(t){this.reconnecting=!1,this.emit("connect",t)},this),s.onerror=n(function(t){this.listener.readyState!=EventSource.CONNECTING||this.reconnecting?this.emit("__disconnect",t):this.reconnecting||(this.reconnecting=!0,this.emit("__disconnect",t))},this)},t.prototype.cancel=function(){this.listener&&(this.listener.close(),delete this.listener)},t}(),websocket:function(){function t(t){WebSocket,this.emit=t}return t.prototype.websocketizeURL=function(t){var e,s=t.match(/^((\w+:)?\/\/([^/]+))?(\/)?(.*)/),i=s[2],r=s[3],n=s[4],a=s[5];return"object"==typeof window?e=window.location:"object"==typeof document&&(e=document.location),!i&&e&&(i=e.protocol),i="https:"==i?"wss:":"http:"==i?"ws:":"wss:",!r&&e&&(r=e.host),i+"//"+r+(a=n?"/"+a:e?e.pathname.match(/(.*\/)[^/]*/)[1]+a:"/"+a)},t.prototype.listen=function(t,e){if(t=h(t=this.websocketizeURL(t),e),this.listener)throw"websocket already listening";this.listener=new WebSocket(t,"ws+meta.nchan");var s=this.listener;s.onmessage=n(function(t){var e=t.data.match(/^id: (.*)\n(content-type: (.*)\n)?\n/m);this.emit("message",t.data.substr(e[0].length),{id:e[1],"content-type":e[3]})},this),s.onopen=n(function(t){this.emit("connect",t)},this),s.onerror=n(function(t){this.emit("error",t,s),delete this.listener},this),s.onclose=n(function(t){this.emit("__disconnect",t),delete this.listener},this)},t.prototype.cancel=function(){this.listener&&(this.listener.close(),delete this.listener)},t}(),longpoll:function(){function t(t){this.headers={},this.longPollStartTime=null,this.maxLongPollTime=3e5,this.emit=t}return t.prototype.listen=function(t,e){if(this.req)throw"already listening";t&&(this.url=t);var i,r=n(function(t,e){t&&(this.headers[e]=t)},this);return e&&(this.headers={Etag:e}),this.reqStartTime=(new Date).getTime(),i=n(function(t,e,n){if(r(n.getResponseHeader("Last-Modified"),"If-Modified-Since"),r(n.getResponseHeader("Etag"),"If-None-Match"),t>=200&&t<=210){var a=n.getResponseHeader("Content-Type");this.parseMultipartMixedMessage(a,e,n)||this.emit("message",e||"",{"content-type":a,id:this.msgIdFromResponseHeaders(n)}),this.reqStartTime=(new Date).getTime(),this.req=s.ajax({url:this.url,headers:this.headers},i)}else 0==t&&"Error"==e&&4==n.readyState||null===t&&"Abort"!=e?(this.emit("__disconnect",t||0,e),delete this.req):null!==t?(this.emit("error",t,e),delete this.req):(delete this.req,this.emit("__disconnect"))},this),this.reqStartTime=(new Date).getTime(),this.req=s.ajax({url:this.url,headers:this.headers},i),this.emit("connect"),this},t.prototype.parseMultipartMixedMessage=function(t,e,s){var i=t&&t.match(/^multipart\/mixed;\s+boundary=(.*)$/);if(!i)return!1;var r=i[1],n=e.split("--"+r);if(""!=n[0]||!n[n.length-1].match(/--\r?\n/))throw"weird multipart/mixed split";for(var a in n=n.slice(1,-1)){var o=(i=n[a].match(/^(.*)\r?\n\r?\n([\s\S]*)\r?\n$/m))[1].split("\n"),h={};for(var c in o){var l=o[c].match(/^([^:]+):\s+(.*)/);l&&"Content-Type"==l[1]&&(h["content-type"]=l[2])}a==n.length-1&&(h.id=this.msgIdFromResponseHeaders(s)),this.emit("message",i[2],h)}return!0},t.prototype.msgIdFromResponseHeaders=function(t){var e,s;return e=t.getResponseHeader("Last-Modified"),s=t.getResponseHeader("Etag"),e?Date.parse(e)/1e3+":"+(s||"0"):s||null},t.prototype.cancel=function(){return this.req&&(this.req.abort(),delete this.req),this},t}(),__slave:function(){function s(t){this.emit=t,this.doNotReconnect=!0}return s.prototype.listen=function(s,i){this.shared=i,this.statusChangeChecker=n(function(t){if(this.shared.matchEventKey(t,"msg")){var s=this.shared.get("msg:id"),i=this.shared.get("msg:content-type"),r=this.shared.get("msg");this.emit("message",r,{id:""==s?e:s,"content-type":""==i?e:i})}},this),t.addEventListener("storage",this.statusChangeChecker)},s.prototype.cancel=function(){t.removeEventListener("storage",this.statusChangeChecker)},s}()},o}(t);"object"==typeof module&&null!=module&&module.exports?module.exports=i:"function"==typeof define&&define.amd?define(function(){return i}):t.NchanSubscriber=i}("undefined"!=typeof window?window:this); |