17 lines
260 KiB
JavaScript
17 lines
260 KiB
JavaScript
/**
|
||
* skills-service-manager - Skills Services Manager
|
||
* @version v4.0.6
|
||
* @license Copyright (c) 2017, Jibo, Inc. All rights reserved.
|
||
* All use of the Jibo SDK is subject to the Jibo SDK End User License Agreement (EULA)
|
||
* distributed herewith. If you did not receive a copy of the EULA, you may view a
|
||
* copy at https://developers.jibo.com/license.
|
||
*/
|
||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.skillsServiceManager=e()}}(function(){return function e(t,i,n){function s(r,a){if(!i[r]){if(!t[r]){var c="function"==typeof require&&require;if(!a&&c)return c(r,!0);if(o)return o(r,!0);var u=new Error("Cannot find module '"+r+"'");throw u.code="MODULE_NOT_FOUND",u}var l=i[r]={exports:{}};t[r][0].call(l.exports,function(e){var i=t[r][1][e];return s(i?i:e)},l,l.exports,e,t,i,n)}return i[r].exports}for(var o="function"==typeof require&&require,r=0;r<n.length;r++)s(n[r]);return s}({1:[function(e,t,i){"use strict";const n=e("jibo"),s=e("./clients/asr/ASRService"),o=e("jibo-service-framework"),r=e("./clients/BodyClient");class a{static tts(e){return e=>{e()}}static nlu(e){return t=>{n.nlu.init({host:o.RegistryClient.instance.host,port:e.port},t)}}static asr(e){return t=>{let i=s.default.createInstance();i.init({host:o.RegistryClient.instance.host,port:e.port},t)}}static lps(e){return e=>{e()}}static body(e){return t=>{r.default.createInstance("127.0.0.1",e.port),t()}}}a.mapping={tts:a.tts,nlu:a.nlu,asr:a.asr,lps:a.lps,body:a.body},Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"./clients/BodyClient":8,"./clients/asr/ASRService":11,jibo:void 0,"jibo-service-framework":void 0}],2:[function(e,t,i){"use strict";const n=e("async"),s=e("./services/registry-service/RegistryService"),o=e("./services/kb-service/KBService"),r=e("./services/skills-service/SkillsService"),a=e("./services/skills-service/SkillsServiceSim"),c=e("./services/performance-service/PerformanceService"),u=e("./services/service-manager/ServiceManager"),l=e("jibo-service-framework"),d=e("./services/tts-service/TTSService"),h=e("./services/lps-service/LPSService"),f=e("./services/notifications-service/NotificationsService"),p=e("./services/asr-service/ASRService"),m=e("./services/body-service/BodyService"),g=e("./services/listen-service/ListenService"),v=e("./services/nlu-service/NLUService"),_=e("./services/system-manager/SystemManagerService"),S=e("./services/media-service/MediaService"),b=e("./services/media-service/MediaManagerService"),y=e("./services/media-proxy/MediaProxyService"),w=e("./services/system-monitoring-service/SystemMonitoringServiceSim"),k=e("./services/error-service/ErrorService"),E=e("./services/dev-shell/DevShell"),R=e("./services/wifi-service/WifiService"),T=e("./services/scheduler-service/SchedulerService"),O=e("./ClientInitializer"),I=e("orchestrator"),L=e("jibo"),P=e("./utils/Version"),A=e("./background/screen/ScreenScheduler"),C=e("./utils/BackgroundUtilsManager");e("./background");const N=e("find-root"),M=e("path"),J=e("child_process").spawnSync;class j{constructor(e,t,i){this.conf=e,this.rootDir=t;let N={KBService:o.default,SkillsService:r.default,SkillsServiceSim:a.default,ServiceManager:u.default,NLUService:v.default,TTSService:d.default,LPSService:h.default,NotificationsService:f.default,ASRService:p.default,BodyService:m.default,ListenService:g.default,DevShell:E.default,PerformanceService:c.default,MediaService:S.default,MediaManagerService:b.default,MediaProxyService:y.default,SystemManagerService:_.default,WifiService:R.default,ErrorService:k.default,SchedulerService:T.default,SystemMonitoringServiceSim:w.default};Object.keys(this.conf.services).forEach(e=>{let t=this.conf.services[e];N[e].createInstance(t,this.rootDir)}),this.orchestrator=new I,this.orchestrator.add("registry-service",e=>{if(this.conf.RegistryService){let t=this.conf.RegistryService;s.default.createInstance(t,this.rootDir),s.default.instance.init(e)}else e()}),this.orchestrator.add("registry-client",["registry-service"],e=>{let t,i=this.registryHost;if(this.conf.RegistryService)t=s.default.instance.port;else{if(!this.conf.RegistryClient)return e(new Error("Config must specify either RegistryClient or Registry Service"));t=this.conf.RegistryClient.port}l.RegistryClient.createInstance(i,t),e()});let M={ASRService:p.default,TTSService:d.default,LPSService:h.default,BodyService:m.default,NLUService:v.default,MediaService:S.default,MediaManagerService:b.default,SystemMonitoringServiceSim:w.default,SystemManagerService:_.default};Object.keys(M).forEach(e=>{this.orchestrator.add(e,["registry-client"],t=>{if(this.conf.services[e]){let i=this.conf.services[e],n=M[e].createInstance(i,this.rootDir);n.init(t)}else t()})}),this.orchestrator.add("get-records",Object.keys(M),e=>{l.RegistryClient.instance.getRecords((t,i)=>{return t?e(t):(this.records=i,void e())})}),this.orchestrator.add("system-manager",["get-records"],e=>{let t=void 0,i=this.records.length;for(let n=0;n<i;n++)if("system-manager"===this.records[n].name){t=this.records[n];break}return t?void L.systemManager.init({host:l.RegistryClient.instance.host,port:t.port},t=>{t?e(t):P.versionCheck(this.conf.platformVersion,e)}):e(new Error("Could not find system-manager in registry records."))}),this.orchestrator.add("clients",["system-manager"],e=>{let t=[];this.records.forEach(e=>{O.default.mapping[e.name]&&t.push(O.default.mapping[e.name](e))}),n.parallel(t,e)});let J=(e,t,i)=>{this.orchestrator.add(e,t,e=>{i.instance?i.instance.init(t=>{e(t)}):e()})};J("wifi-service",["clients"],R.default),J("dev-shell",["clients"],E.default),J("performance-service",["clients"],c.default),J("kb",["clients"],o.default),J("notifications-service",["clients"],f.default),J("scheduler-service",["clients"],T.default),J("media-proxy",["clients"],y.default),J("error-service",["clients","kb"],k.default),J("listen-service",["clients","kb"],g.default),J("skills-service",["listen-service"],r.default),J("skills-service-sim",["listen-service"],a.default),this.orchestrator.add("end",["wifi-service","dev-shell","performance-service","kb","notifications-service","scheduler-service","media-proxy","error-service","listen-service","skills-service","skills-service-sim"],e=>{i&&i.indexOf("developer")>=0&&A.default.start(),C.default.initAll(i),e()})}get registryHost(){let e="127.0.0.1";if(this.conf.RegistryClient)if(this.conf.RegistryClient.host)e=this.conf.RegistryClient.host;else{const t=M.join(N(__dirname),"bin/utils/get-robot-host.sh");e=J(t).stdout.toString().trim(),console.log(e)}return e}init(e){console.log("INIT"),this.orchestrator.start("end",e)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=j},{"./ClientInitializer":1,"./background":3,"./background/screen/ScreenScheduler":7,"./services/asr-service/ASRService":27,"./services/body-service/BodyService":30,"./services/dev-shell/DevShell":32,"./services/error-service/ErrorService":36,"./services/kb-service/KBService":42,"./services/listen-service/ListenService":51,"./services/lps-service/LPSService":57,"./services/media-proxy/MediaProxyService":59,"./services/media-service/MediaManagerService":60,"./services/media-service/MediaService":61,"./services/nlu-service/NLUService":62,"./services/notifications-service/NotificationsService":64,"./services/performance-service/PerformanceService":65,"./services/registry-service/RegistryService":66,"./services/scheduler-service/SchedulerService":67,"./services/service-manager/ServiceManager":68,"./services/skills-service/SkillsService":72,"./services/skills-service/SkillsServiceSim":73,"./services/system-manager/SystemManagerService":74,"./services/system-monitoring-service/SystemMonitoringServiceSim":75,"./services/tts-service/TTSService":77,"./services/wifi-service/WifiService":79,"./utils/BackgroundUtilsManager":87,"./utils/Version":90,async:void 0,child_process:void 0,"find-root":void 0,jibo:void 0,"jibo-service-framework":void 0,orchestrator:void 0,path:void 0}],3:[function(e,t,i){"use strict";e("./location/LocationManager"),e("./screen/ScreenScheduler")},{"./location/LocationManager":5,"./screen/ScreenScheduler":7}],4:[function(e,t,i){"use strict";function n(){return r().then(e=>{return s(e)})}function s(e){return new Promise((t,i)=>{const n=[];for(let s=0;s<e.length;++s)if(e[s]){const t=e[s].split(/\s+/);n.push({macAddress:t[0],signalStrength:parseInt(t[2])})}const r={wifiAccessPoints:n,considerIp:!0},a=c.stringify({key:l}),u=`https://www.googleapis.com/geolocation/v1/geolocate?${a}`,d=new XMLHttpRequest;d.responseType="json",d.timeout=1e4,d.addEventListener("timeout",()=>{i("XHR Timeout")},!1),d.addEventListener("error",()=>{i("XHR Error")},!1),d.addEventListener("abort",()=>{i("XHR Aborted")},!1),d.addEventListener("load",()=>{if(200===d.status){const e=d.response.location;t(o(e.lat,e.lng))}else i(d.response&&d.response.error?d.response.error.message:"Invalid response")},!1),d.open("POST",u,!0),d.setRequestHeader("Content-Type","application/json;charset=UTF-8"),d.send(JSON.stringify(r))})}function o(e,t){return new Promise((i,n)=>{const s=c.stringify({key:u,latlng:`${e},${t}`}),o=`https://maps.googleapis.com/maps/api/geocode/json?${s}`,r=new XMLHttpRequest;r.responseType="json",r.timeout=1e4,r.addEventListener("timeout",()=>{n("XHR Timeout")},!1),r.addEventListener("error",()=>{n("XHR Error")},!1),r.addEventListener("abort",()=>{n("XHR Aborted")},!1),r.addEventListener("load",()=>{if(200===r.status){let n={lat:e,lng:t};const s=r.response.results;for(let o=0;o<s.length;++o){const e=s[o].types;if(e.indexOf("street_address")!==-1||e.indexOf("political")!==-1){const e=s[o].address_components;for(let t=0;t<e.length;++t){const i=e[t].types;i.indexOf("sublocality")===-1&&i.indexOf("locality")===-1?i.indexOf("administrative_area_level_1")===-1?i.indexOf("country")===-1||(n.country=e[t].long_name,"United States"===n.country&&(n.country="usa")):(n.state=e[t].long_name,n.stateAbbr=e[t].short_name):n.city=e[t].long_name}break}}i(n)}else n(r.response&&r.response.error?r.response.error.message:"Invalid response")},!1),r.open("GET",o,!0),r.send()})}function r(){return new Promise((e,t)=>{a.default.instance.getScanResults((i,n)=>{i?t(i):e(n)})})}const a=e("../../services/wifi-service/WifiService"),c=e("querystring"),u="AIzaSyAq77uInf4VPUr2Kw1rDdPXe_giV_Tyhp8",l="AIzaSyABiyOf9g4j-p7PzZXOFJmsDF6ox6qFC3A";i.getLocation=n},{"../../services/wifi-service/WifiService":79,querystring:void 0}],5:[function(e,t,i){"use strict";const n=e("jibo"),s=e("../../utils/Log"),o=s.createLog("ssm-location-manager"),r=e("./Location"),a=e("./Timezone"),c=e("../../services/kb-service/KBService"),u=e("../../services/wifi-service/WifiService"),l=e("../../clients/SystemManagerClient"),d=e("../../utils/BackgroundUtilsManager"),h="/jibo/location",f=18e5;class p{static get instance(){return p._instance}static init(){const e=p._instance=new p;e.init(()=>{u.default.instance&&u.default.instance.verifyConnection(t=>{t?u.default.instance.on("state-change",e._onWifiConnected):e.getTimezone(!0).then(e=>{})})})}constructor(e=true){this.httpUrl="http://localhost:"+c.default.instance.port,this.enableCloud=e,this._onWifiConnected=this._onWifiConnected.bind(this),this._checkForChangedTimezone=this._checkForChangedTimezone.bind(this)}init(e){this.model=n.kb.createModel(h,this.httpUrl),this._preloadLocationModel(()=>{o.info("KB Model Intialized"),e&&e()})}getTimezone(e=false){return this._getLocation(e).then(e=>{return a.lookUpTimezone(e.lat,e.lng)}).then(e=>{return this._saveTimezone(e)}).catch(e=>{return o.info("error when looking up timezone, not setting system timezone: "+JSON.stringify(e)),null})}_onWifiConnected(e){"CONNECTED"===e.newState&&(u.default.instance.removeListener("state-change",this._onWifiConnected),this.getTimezone(!0).then(e=>{}))}_checkForChangedTimezone(){this.getTimezone().then(()=>{})}_preloadLocationModel(e){this.model.loadRoot((t,i)=>{this.rootNode=i,e()})}_getLocation(e){return this.model.load(this.rootNode.getEdges("home")).then(t=>{return t&&t[0]?e&&Date.now()-t[0].updated>f?this._learnAndSaveLocation(t[0].data):(o.info("Previous location data is considered new enough, is being reused"),t[0].data):this._learnAndSaveLocation()},e=>{return this._learnAndSaveLocation()})}_learnAndSaveLocation(e){return r.getLocation().catch(t=>{return o.info("error while getting location, falling back to previous location or Boston"+JSON.stringify(t)),e?e:{city:"Boston",state:"Massachusetts",stateAbbr:"MA",country:"usa",lat:42.354416,lng:-71.054287}}).then(e=>{return this._saveLocation(e)})}_saveLocation(e){let t;return t=0===this.rootNode.getEdges("location").length?new Promise((t,i)=>{const n=this.model.createNode("location",e);this.rootNode.addEdges(n,"home"),t(n)}):this.model.load(this.rootNode.getEdges("home")).then(t=>{return t[0].data=e,t[0]}),t.then(e=>{return Promise.all([e.save(),this.rootNode.save()])}).then(()=>{return e})}_saveTimezone(e){let t;return t=0===this.rootNode.getEdges("timezone").length?new Promise((e,t)=>{const i=this.model.createNode("timezone",{});this.rootNode.addEdges(i,"timezone"),e(i)}):this.model.load(this.rootNode.getEdges("timezone")).then(e=>{return e[0]}),t.then(t=>{const i=t.data;if(i.offsetUTC!==e.offsetUTC||i.id!==e.id){if(t.data=e,i.id!==e.id)return new Promise(i=>{l.default.instance.setTimeZone(e.id,e=>{e?o.error("Error when setting system timezone: "+JSON.stringify(e)):o.info("successfully set system timezone"),i(t)})});o.info("timezone offset changed, but id did not. Only updating KB")}else o.info("timezone has not changed");return t}).then(e=>{return Promise.all([e.save(),this.rootNode.save()])}).then(()=>{return e})}}d.default.register(()=>{setTimeout(()=>{p.init()},5e3)},"location"),Object.defineProperty(i,"__esModule",{value:!0}),i.default=p},{"../../clients/SystemManagerClient":10,"../../services/kb-service/KBService":42,"../../services/wifi-service/WifiService":79,"../../utils/BackgroundUtilsManager":87,"../../utils/Log":88,"./Location":4,"./Timezone":6,jibo:void 0}],6:[function(e,t,i){"use strict";function n(e,t){return new Promise((i,n)=>{const r=s.stringify({key:o,timestamp:Math.floor(Date.now()/1e3),location:`${e},${t}`}),a=`https://maps.googleapis.com/maps/api/timezone/json?${r}`,c=new XMLHttpRequest;c.responseType="json",c.timeout=1e4,c.addEventListener("timeout",()=>{n("XHR Timeout")},!1),c.addEventListener("error",()=>{n("XHR Error")},!1),c.addEventListener("abort",()=>{n("XHR Aborted")},!1),c.addEventListener("load",()=>{if(200===c.status){const e=c.response,t=1e3*(e.rawOffset+e.dstOffset),n=e.timeZoneName,s=e.timeZoneId,o={offsetUTC:t,name:n,id:s,__type:"Timezone"};i(o)}else n(c.response&&c.response.error?c.response.error.message:"Invalid response")},!1),c.open("GET",a,!0),c.send()})}const s=e("querystring"),o="AIzaSyAWnQ5cuZQzdMNQoc5l84c1hd6OxkO3hyI";i.lookUpTimezone=n},{querystring:void 0}],7:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?s(e.value):new i(function(t){t(e.value)}).then(r,a)}c((n=n.apply(e,t||[])).next())})};const s=e("../../clients/BodyClient"),o=e("../../utils/BackgroundUtilsManager");let r;const a=3e5;class c{static start(){clearTimeout(r),r=setTimeout(()=>{s.default.instance.setScreen("off"),c.headTouchOn()},a)}static stopTimerAndTurnOn(){return n(this,void 0,void 0,function*(){clearTimeout(r),c.headTouchOff(),yield s.default.instance.setScreen("on")})}static headTouchOn(){s.default.instance.once("touched",c.onHeadTouched)}static headTouchOff(){s.default.instance.removeListener("touched",c.onHeadTouched)}static onHeadTouched(){return n(this,void 0,void 0,function*(){yield s.default.instance.setScreen("on"),c.headTouchOff(),c.start()})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=c,o.default.register(e=>{e&&e.indexOf("developer")>=0&&c.start()},"screen")},{"../../clients/BodyClient":8,"../../utils/BackgroundUtilsManager":87}],8:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?s(e.value):new i(function(t){t(e.value)}).then(r,a)}c((n=n.apply(e,t||[])).next())})};const s=e("jibo-service-framework"),o=e("../utils/Async");class r extends s.HTTPClient{constructor(e,t){super(e,t),this.host=e,this.port=t,r._instance=this,this._onTouchMessage=this._onTouchMessage.bind(this),this._clientTouch=new s.WSClient(`ws://127.0.0.1:${t}/touch`),this._clientTouch.on("message",this._onTouchMessage),this._onPowerMessage=this._onPowerMessage.bind(this),this._clientPower=new s.WSClient(`ws://127.0.0.1:${t}/power`),this._clientPower.on("message",this._onPowerMessage),this._clientPower.on("error",()=>{console.error(`Error opening power state socket in SSM`)})}static createInstance(e,t){return new r(e,t)}static get instance(){return r._instance}getScreen(){return n(this,void 0,void 0,function*(){const e=yield o.default.get(e=>this.get("/screen",e));return e})}setScreen(e){return n(this,void 0,void 0,function*(){yield o.default.get(t=>this.postJSON("/screen",{screen:e},t))})}_onTouchMessage(e){if(e.changed.length>0)for(let t=0;t<e.changed.length;t++)if(e.pad_state[e.changed[t]])return void this.emit("touched")}get pluggedIn(){return"EXTERNAL"===this._powerState.source}_onPowerMessage(e){this._powerState=e}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=r},{"../utils/Async":86,"jibo-service-framework":void 0}],9:[function(e,t,i){"use strict";const n=e("jibo-service-framework");class s extends n.HTTPClient{constructor(e,t){super(e,t),this.host=e,this.port=t,s._instance=this}static createInstance(e,t){return new s(e,t)}getJson(e){this.get("/json",(t,i)=>{e(t,i)})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"jibo-service-framework":void 0}],10:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("http");class o{}class r extends n.HTTPClient{constructor(e,t,i){super(t,i),this.host=t,this.port=i,r._instance=this}static createInstance(e,t){return new r(new o,e,t)}static get instance(){return r._instance}get(e,t){let i=s.get("http://"+this.host+":"+this.port+e,e=>{let i="";e.on("data",e=>{i+=e.toString()}),e.on("end",()=>{if(200===e.statusCode)t(null,JSON.parse(i));else{let i="System Manager is unavailable";void 0!==e.statusMessage&&""!==e.statusMessage&&(i=e.statusMessage),t(new Error(i))}})});i.on("error",e=>{t(new Error(`Got error: ${e.message}`))})}sendRequest(e,t,i,n){let o={host:this.host,port:this.port,path:t,method:e,headers:{"Content-Type":"application/json","Content-Length":i.length}},r=s.request(o,e=>{e.setEncoding("utf8");let t="";e.on("data",e=>{t+=e.toString()}),e.on("end",()=>{if(204===e.statusCode)n(null);else if(200===e.statusCode)n(null,JSON.parse(t));else{let t="System Manager is unavailable";void 0!==e.statusMessage&&""!==e.statusMessage&&(t=e.statusMessage),n(new Error(t))}})});r.on("error",e=>{n(new Error("problem with request: "+e.message))}),r.write(i),r.end()}list(e){this.get("/skill/list",(t,i)=>{e(t,i.skills)})}getSkillRecordByName(e,t){this.list((i,n)=>{if(i)return t(i);for(let s=0;s<n.length;s++)if(n[s].name===e)return t(null,n[s]);return t(new Error(`Could not find skill with name ${e}`))})}launch(e,t){let i=JSON.stringify({name:e,context:"{}"});this.sendRequest("POST","/skill/launch",i,t)}terminate(e,t){let i=JSON.stringify({name:e});this.sendRequest("POST","/skill/terminate",i,t)}getMode(e){this.get("/mode",(t,i)=>{return t?e(t):void e(null,i.mode)})}syncTime(e){this.sendRequest("POST","/time/synchronize","",e)}setTimeZone(e,t){if(!e)return void t("No zone given");let i="";try{i=JSON.stringify({timezone:e})}catch(e){return void t("Timezone request is not valid JSON")}this.sendRequest("POST","/time/zone",i,t)}getCredentials(e){this.get("/credentials",(t,i)=>{return t?e(t):void e(null,i)})}sendWifiRequest(e,t,i,n){this.sendRequest(e,t,i,(e,t)=>{n(e,t?t.response:null)})}addNetwork(e){let t=JSON.stringify({command:"ADD_NETWORK"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}removeNetwork(e,t){let i=JSON.stringify({command:"REMOVE_NETWORK "+e});this.sendWifiRequest("POST","/wifi/wpa",i,t)}saveConfig(e){let t=JSON.stringify({command:"SAVE_CONFIG"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}disconnect(e){let t=JSON.stringify({command:"DISCONNECT"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}signalPoll(e){let t=JSON.stringify({command:"SIGNAL_POLL"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}setNetwork(e,t){let i=JSON.stringify({command:"SET_NETWORK "+e});this.sendWifiRequest("POST","/wifi/wpa",i,t)}selectNetwork(e,t){let i=JSON.stringify({command:"SELECT_NETWORK "+e});this.sendWifiRequest("POST","/wifi/wpa",i,t)}enableNetwork(e,t){let i=JSON.stringify({command:"ENABLE_NETWORK "+e});this.sendWifiRequest("POST","/wifi/wpa",i,t)}setInterface(e,t){let i=JSON.stringify({interface:e});this.sendWifiRequest("POST","/wifi/interface",i,t)}getInterface(e){this.get("/wifi/interface",(t,i)=>{return t?e(t):void e(null,i.interface)})}listNetworks(e){let t=JSON.stringify({command:"LIST_NETWORKS"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}wifiStatus(e){let t=JSON.stringify({command:"STATUS-VERBOSE"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}scan(e){let t=JSON.stringify({command:"SCAN"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}scanResults(e){let t=JSON.stringify({command:"SCAN_RESULTS"});this.sendWifiRequest("POST","/wifi/wpa",t,e)}}r.NAME="system-manager",Object.defineProperty(i,"__esModule",{value:!0}),i.default=r},{http:void 0,"jibo-service-framework":void 0}],11:[function(e,t,i){"use strict";const n=e("./ASRVariables"),s=e("./AudioAction"),o=e("./SpeakerAction"),r=e("./AudioSource"),a=e("./Recognizer"),c=e("./SpeakerRecognizer"),u=e("./NameRecognizer"),l=e("./NameListener"),d=e("./Listener"),h=e("./Enroller"),f=e("jibo-service-framework"),p=e("events"),m=e("jibo-common-types");var g;!function(e){e[e.STANDARD="STANDARD"]="STANDARD",e[e.OLD="OLD"]="OLD",e[e.PRONUN="PRONUN"]="PRONUN"}(g=i.UrlInterface||(i.UrlInterface={}));class v{constructor(e){this.event_type=e.event_type,this.task_id=e.task_id,this.status=e.status,this.message=e.message||"",this.speaker_id=e.speaker_id?new m.SpeakerId(e.speaker_id):null,this.speaker_id_record=e.speaker_id_record?new m.SpeakerIdRecord(e.speaker_id_record):null,this.utterances=e.utterances||[{utterance:""}],this.timestamp=e.timestamp||"",this.message_id=e.message_id||"",this.request_id=e.request_id||""}}i.ASRData=v;class _ extends p.EventEmitter{constructor(){if(super(),this.BASE="/usr/local/share/asrservice/sharedresources/",this.OLD_BASE="/var/jibo/asr/",this.verbose=!1,_._instance)throw new Error("ASRService is a singleton");_._instance=this,this.isInitialized=!1,this.msgs=[],this.listSpeakerCallbacks=[],this.deleteSpeakerCallbacks=[],this.enrollerId=""}static createInstance(){return new _}static get instance(){return _._instance}get Recognizer(){return a.default}get SpeakerRecognizer(){return c.default}get NameRecognizer(){return u.default}init(e,t){try{this.socketUrl="ws:"+e.host+":"+e.port+"/simple_port",this.socketUrlOld="ws:"+e.host+":"+e.port+"/port",this.audioUrl="http://"+e.host+":"+e.port+"/audio_source",this.asrInterfaceUrl="http://"+e.host+":"+e.port+"/asr_simple_interface",this.speakerInterfaceUrl="http://"+e.host+":"+e.port+"/spkr_id_interface",this.asrPronunUrl="http://"+e.host+":"+e.port+"/pronun_interface",this.asrInterfaceOld="http://"+e.host+":"+e.port+"/asr_interface",this.socket=new f.WSClient(this.socketUrl),this.socketOld=new f.WSClient(this.socketUrlOld),this.loggingEnabled=!1,this.socket.on("error",(e,t)=>{e.startsWith("json")?console.warn(e,t):console.warn("error connecting to server")}),this.socketOld.on("error",(e,t)=>{e.startsWith("json")?(console.warn(e,t),this.processMessage(t)):console.warn("error connecting to old server")}),this.socket.on("reopen",()=>{this.initAlsaSource(e=>{console.log("ALSA SOURCE INIT",e),this.emit("reopen")})}),this.socket.on("close",()=>{this.emit("close")}),this.socket.on("message",e=>{for(e.api="simplified",this.msgs.push(e);!this.paused&&this.msgs.length;)this.processNextMessage()}),this.socketOld.on("message",e=>{for(e.api="old",this.msgs.push(e);!this.paused&&this.msgs.length;)this.processNextMessage()}),this.initAlsaSource(t)}catch(e){console.warn(e)}}initAlsaSource(e){this.alsaSource=new r.default(this.audioUrl),this.alsaSource.init(t=>{t&&console.warn(t),this.isInitialized=!0,e()})}pause(){this.paused=!0}resume(){for(this.paused=!1;this.msgs.length;)this.processNextMessage()}processNextMessage(){this.processMessage(this.msgs.shift())}processMessage(e){const t=n.default.idToAction[e.task_id];if(e.nlu_req_id){const t=e.nlu_json_content;t&&"ERROR"===t.Status&&console.error("NLU ERROR",t.Message.exception,t.Message.info)}if("ERROR"===e.status&&t&&t.emit("error",e.message,e.content),"old"===e.api){if("received"===e.status)return void(t&&t.emit("received"));if(e.final_composite&&t)return void t.emit("finished",t);let i=e.pronunciations;if(i&&i.length>0)return void(e.success&&this.pronunAction?this.pronunAction.emit("got-pronunciations",i):e.pronunciations[0].success&&t?t.emit("got-pronunciations",i[0]):this.pronunAction.emit("pronun-error",i));const s=n.default.idToRecognizer[e.simple_recog_name];if(s)return void s.onResult(e);if("LISTING-SPEAKERS"===e.speaker_idstatus)return void this.listSpeakerCallback(e);if("DELETING-SPEAKER"===e.speaker_idstatus)return void this.deleteSpeakerCallback(e)}if("normal"!==e.status)return void("error"===e.status&&t?(console.warn("ASR Service returned error response. Check ASR debug",e.message),console.warn("Network Initialization Timeouts may be due to poor wifi connectivity"),t.emit("speech_to_text_final",e),t.emit("error",e.message)):t&&t.emit(e.event_type,e.status));if("simplified"===e.api){if(e=new v(e),!t){const t=new s.default(this.asrInterfaceUrl,e.task_id);if(e.task_id.startsWith("DEBUG:"))return;return t.stop(),void console.error("No action found for ASR response",e)}t.emit(e.event_type,e)}}setEnrollerId(e){this.enrollerId=e}createWavSource(e){return this.wavSource=new r.default(this.audioUrl,e),this.wavSource}createWavAction(){let e=new s.default(this.asrInterfaceUrl);return this.wavSource.link(e),e}createAudioAction(e,t){let i;return e&&e!==g.STANDARD?e===g.OLD?i=new s.default(this.asrInterfaceOld,t):e===g.PRONUN&&(i=new s.default(this.asrPronunUrl,t),this.pronunAction=i):i=new s.default(this.asrInterfaceUrl,t),this.alsaSource.link(i),i}createSpeakerAction(){let e=new o.default(this.speakerInterfaceUrl);return this.alsaSource.link(e),e}createSpeakerActionAsync(e){let t=new o.default(this.speakerInterfaceUrl);return this.alsaSource.link(t),e(t)}listEnrolledSpeakers(e){this.listSpeakerCallbacks.push(e),this.createSpeakerActionAsync(e=>{e.listSpeakers()})}listSpeakerCallback(e){this.listSpeakerCallbacks.forEach(t=>{t(e)}),this.listSpeakerCallbacks=[]}deleteSpeaker(e,t="TD+TI",i){this.deleteSpeakerCallbacks.push(i),this.createSpeakerActionAsync(i=>{i.deleteSpeaker(e,t)})}deleteSpeakerCallback(e){this.deleteSpeakerCallbacks.forEach(t=>{t(e)}),this.deleteSpeakerCallbacks=[]}setLogging(e){this.loggingEnabled=e}createListener(e){return new d.default(e)}createEnroller(e,t){return new h.default(e,t)}spoofUtterance(e,t){let i=Object.keys(n.default.idToAction);i.forEach(i=>{let n={event_type:"speech_to_text_final",task_id:i,status:"normal",message:"spoofed",utterances:[{utterance:e,score:1e3}],timestamp:"---",message_id:"",request_id:i,spoofed:!0,api:"simplified"};n.speaker_id=new m.SpeakerId,t&&(n.speaker_id.status="ACCEPTED"),this.processMessage(n)})}createNameListener(e){let t=new l.default(e);return this.alsaSource.link(t),t}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=_},{"./ASRVariables":12,"./AudioAction":13,"./AudioSource":14,"./Enroller":15,"./Listener":16,"./NameListener":17,"./NameRecognizer":18,"./Recognizer":19,"./SpeakerAction":20,"./SpeakerRecognizer":21,events:void 0,"jibo-common-types":void 0,"jibo-service-framework":void 0}],12:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default={idToAction:{},idToAudioSource:{},idToRecognizer:{},numberActiveActions:0}},{}],13:[function(e,t,i){"use strict";const n=e("uuid"),s=e("./ASRVariables"),o=e("events");var r;!function(e){e[e.NOT_STARTED="NOT_STARTED"]="NOT_STARTED",e[e.STARTING="STARTING"]="STARTING",e[e.STARTED="STARTED"]="STARTED",e[e.STOPPING="STOPPING"]="STOPPING",e[e.STOPPED="STOPPED"]="STOPPED",e[e.CLEARING="CLEARING"]="CLEARING",e[e.CLEARED="CLEARED"]="CLEARED"}(r=i.ActionStatus||(i.ActionStatus={}));class a extends o.EventEmitter{constructor(e,t){super(),this.shouldLog=!1,this.httpInterface=e,this.id=t||"action-"+n.v4(),s.default.idToAction[this.id]=this,this.status=r.NOT_STARTED,this.startCallbacks=[],this.stopCallbacks=[],this.clearCallbacks=[]}setAudioSourceId(e){this.audioSourceId=e}setId(e){this.id=e}getId(){return this.id}startAudioTask(e,t){if(this._log({"someone wants to start ":this.id}),this.startCallbacks.push(t),this.status!==r.STARTING){if(this.status===r.STARTED)return void this._callIfExists(t);this.status=r.STARTING;let i={audio_source_id:this.audioSourceId,bargein:e.bargein,command:"start",expected_duration:e.expectedDuration,hotphrase:e.hotphrase,incremental:e.incremental,language:e.language,meta:e.metadata,nbest:e.nbest,request_id:this.id,speaker_id:e.known_speaker_id,speech_to_text:e.speech_to_text,task_id:this.id},n=JSON.stringify(i);this.once("acknowledgement",()=>{this._log({"OFFICIALLY STARTED ":this.id}),this.status=r.STARTED,this.startCallbacks.forEach(e=>{this._callIfExists(e)}),this.startCallbacks=[],s.default.numberActiveActions++,this._log({"Number of active Actions":s.default.numberActiveActions})}),this._log({"starting ":this.id,"task:":i});let o=new XMLHttpRequest;o.open("POST",this.httpInterface,!0),o.send(n)}}startOldTask(e,t){if(this.startCallbacks.push(t),"string"!=typeof e&&(e=JSON.stringify(e)),this.status!==r.STARTING){if(this.status===r.STARTED)return void this._callIfExists(t);this.status=r.STARTING;let i={action:"init_and_start",audio_source_id:this.audioSourceId,request_id:this.id,task:e,task_id:this.id};i=JSON.stringify(i),this.once("received",()=>{this.status=r.STARTED,this.startCallbacks.forEach(e=>{this._callIfExists(e)}),s.default.numberActiveActions++,this.startCallbacks=[]});let n=new XMLHttpRequest;n.open("POST",this.httpInterface,!0),n.send(i),this._log({"Number of active Actions":s.default.numberActiveActions})}}stop(e){if(this._log({"someone wants to stop ":this.id}),this.status!==r.STOPPING){if(this.status===r.STOPPED)return void this._callIfExists(e);if(this.status===r.STARTING)return void this.startCallbacks.push(()=>{this.stop(e)});this.stopCallbacks.push(e),this.status=r.STOPPING;let t={command:"stop",request_id:this.id,task_id:this.id},i=JSON.stringify(t);this.once("acknowledgement",()=>{this._log({"OFFICIALLY STOPPED ":this.id}),this.status=r.STOPPED,this.stopCallbacks.forEach(e=>{this._callIfExists(e)}),this.stopCallbacks=[],s.default.numberActiveActions--,this._log({"Number of active Actions":s.default.numberActiveActions}),delete s.default.idToAction[this.id]});let n=new XMLHttpRequest;this._log({"stopping ":this.id}),n.open("POST",this.httpInterface,!0),n.send(i)}}stopOldTask(e){if(this.status!==r.STOPPING){if(this.status===r.STOPPED||this.status===r.CLEARED||this.status===r.CLEARING)return void this._callIfExists(e);if(this.status===r.STARTING)return void this.startCallbacks.push(()=>{this.stop(e)});this.stopCallbacks.push(e),this.status=r.STOPPING;let t=new XMLHttpRequest,i={action:"stop",audio_source_id:this.audioSourceId,request_id:this.id,task:"",task_id:this.id},n=JSON.stringify(i);this.once("received",()=>{this.status=r.STOPPED,this.stopCallbacks.forEach(e=>{this._callIfExists(e)}),s.default.numberActiveActions--,this.stopCallbacks=[]}),this._log({"stopping old":this.id}),t.open("POST",this.httpInterface,!0),t.send(n)}}clearOldTask(e){if(this.clearCallbacks.push(e),this.status!==r.CLEARING){if(this.status===r.CLEARED)return void this._callIfExists(e);let t=new XMLHttpRequest,i={
|
||
action:"clear",audio_source_id:this.audioSourceId,request_id:this.id,task:"",task_id:this.id};this.once("received",()=>{this.status=r.CLEARED,this.clearCallbacks.forEach(e=>{this._callIfExists(e)}),this.clearCallbacks=[],this._log({"OFFICIALLY CLEARED ":this.id}),delete s.default.idToAction[this.id]});let n=JSON.stringify(i);return this._log({"clearing old ":this.id}),t.open("POST",this.httpInterface,!0),t.send(n),!0}}generateGraphemeToPhoneme(e){let t={action:"g2p",word:e.word,nbest:"10",task_id:this.id,audio_source_id:this.audioSourceId};s.default.idToAction[e.listenerId]=e;let i=JSON.stringify(t),n=new XMLHttpRequest;n.open("POST",this.httpInterface,!0),n.send(i)}_log(e){this.shouldLog&&console.log("AudioAction Debug: ",e)}_callIfExists(e){e&&e()}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"./ASRVariables":12,events:void 0,uuid:void 0}],14:[function(e,t,i){"use strict";const n=e("uuid"),s=e("./ASRVariables");class o{constructor(e,t){let i="alsa";Array.isArray(t)&&t.length>0?i="wav":"string"==typeof t&&(i="wav",t=[t]),this.id="source-"+n.v4(),s.default.idToAudioSource[this.id]=this,this.source=i,this.wavFiles=t||[],this.audioUrl=e}init(e){let t={action:"start",audio_source_id:this.id,audio_source:this.source,wav_files:this.wavFiles};t=JSON.stringify(t);let i=new XMLHttpRequest;i.open("POST",this.audioUrl,!0),i.onreadystatechange=(()=>{4!==i.readyState||204!==i.status&&200!==i.status?4===i.readyState&&0===i.status&&e("Could not create audio channel"):e()}),i.send(t)}destroy(e){let t={action:"stop",audio_source_id:this.id,audio_source:this.source,wav_files:[]};t=JSON.stringify(t);let i=new XMLHttpRequest;i.open("POST",this.audioUrl,!0),i.onreadystatechange=(()=>{4!==i.readyState||204!==i.status&&200!==i.status?4===i.readyState&&0===i.status&&e("Could not destroy audio channel"):e()}),i.send(t)}link(e){e.setAudioSourceId(this.id)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=o},{"./ASRVariables":12,uuid:void 0}],15:[function(e,t,i){"use strict";const n=e("events"),s=e("./ASRService"),o=e("./ASRService");var r;!function(e){e[e.CLEAR_SPEAKERS=0]="CLEAR_SPEAKERS",e[e.SAVE_AUDIO=1]="SAVE_AUDIO",e[e.SAVE_AND_ENROLL=2]="SAVE_AND_ENROLL"}(r||(r={}));class a extends n.EventEmitter{constructor(e,t){super(),this.callback=t,this.speakerName=e.speakerName,this.enrollmentType=e.enrollmentType,this.nSavingAudios=0,this.sendTD="text-dependent"===this.enrollmentType,s.default.instance.isInitialized||console.warn("Running enroller without ASR service")}_emitEnrollmentResult(e){if(console.log("emitting enrollment result",e.status),"SAVING_AUDIO"===e.status||"NOT_USED"===e.status)e.numRequired=++this.nSavingAudios,this.emit("saving-audio",e);else{if("NEED-4-MORE-UTTS"===e.status||"NEED-3-MORE-UTTS"===e.status||"NEED-2-MORE-UTTS"===e.status||"NEED-1-MORE-UTTS"===e.status)return e.numRequired=parseInt(e.status[5]),void this.emit("need-more-data",e);if("ENROLLMENT-STARTED"===e.status)return void this.emit("enrollment-started")}if(e&&"ENROLLMENT-DONE"===e.status)return void this.emit("enrollment-done",e,this.heyJiboResult)}_addHeyJibo(){let e=new s.default.instance.Recognizer({path:"hey_jibo",timeout:0,bargein:!0,nbest:1,delay:300,speakerName:"",incremental:!1,speakerId:!1});return e.on("result",e=>{this.heyJiboResult=e}),`${e.pack()}`}_startCollectionInstance(){this.speakerName||(this.speakerName="NO_NAME_PROVIDED_FOR_ENROLLMENT");let e=new s.default.instance.SpeakerRecognizer({enrollTD:this.sendTD,enrollTI:!this.sendTD,speakerName:this.speakerName,timeout:5e3,bargein:!1,nbest:1,enroll_mode:this.enrollMode,incremental:!1});e.on("result",e=>{this._emitEnrollmentResult(e)});let t=`${e.pack()}`;t=`${this._addHeyJibo()} * ${t}`,this.action=s.default.instance.createAudioAction(o.UrlInterface.OLD),this.action.on("finished",()=>{this.stop(()=>{this.emit("enrollment-event")})}),s.default.instance.setEnrollerId(this.action.id),this.action.startOldTask(t)}collectSample(){console.log("collecting sample"),this.enrollMode=r.SAVE_AUDIO,this._startCollectionInstance()}collectAndEnroll(){console.log("collecting and enrolling"),this.enrollMode=r.SAVE_AND_ENROLL,this._startCollectionInstance()}clearAndEnroll(){console.log("clearing and enrolling"),this.enrollMode=r.CLEAR_SPEAKERS,this._startCollectionInstance()}clearPreviousData(){let e=s.default.instance.createAudioAction(o.UrlInterface.OLD);this.enrollMode=r.CLEAR_SPEAKERS,e.on("finished",()=>{e.stopOldTask(()=>{e.clearOldTask(()=>{this.emit("enrollment-event")})})}),e.startOldTask(this.task)}stop(e){return this.action?void this.action.stopOldTask(()=>{this.action.clearOldTask(()=>{e&&e()})}):void(e&&e())}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"./ASRService":11,events:void 0}],16:[function(e,t,i){"use strict";const n=e("events"),s=e("./AudioAction"),o=e("jibo-common-types"),r=e("./ASRService");class a extends n.EventEmitter{constructor(e){super(),this.task=new o.ASRRequestOptions({}),this.options=e,this.status="INVALID",this.stopCallbacks=[]}start(){let e=this.options;if("IN_PROGRESS"===this.status)return this.emit("error","cannot restart; listener is currently in progress."),!1;this.status="IN_PROGRESS",this.action=r.default.instance.createAudioAction(),this.id=this.action.getId(),this.action.on("speech_to_text_final",e=>{let t=new o.SpeakerId(e.speaker_id),i=new o.ListenResults(e.utterances[0],null,e.utterances);i.result.Input?console.log("ASR returned",i.result.Input):console.log("No utterances in ASR Response"),this.action.stop(()=>{this.emit("cloud",i,t),this.stop()})}),this.action.on("speech_to_text_incremental",e=>{let t=new o.ListenResults(e.utterances[0]);this.emit("incremental",t)}),this.action.on("hotphrase",t=>{this._hasHotphrase=!0,this.emit("embedded",t.utterances,t.speaker_id),this._consolidateResults(e.speech_to_text===!1)}),this.action.on("speaker_id",t=>{this._hasSpeakerId=!0;let i=t.speaker_id_record||t.speaker_id;this.emit("speaker-id",i),this._consolidateResults(e.speech_to_text===!1)}),this.action.on("end_of_speech",()=>{this.emit("end")}),this.action.on("start_of_speech",()=>{this.emit("speech-start")}),this.action.on("error",e=>{this.emit("error",e)});let t=new o.ASRRequestOptions({});return t.bargein=e.bargein,t.hotphrase=e.heyJibo||"hey_jibo"===e.hotphrase?"hey_jibo":"",t.expectedDuration=e.expectedDuration,t.incremental=void 0!==e.incremental&&e.incremental,t.known_speaker_id=e.authenticateSpeaker,t.language=e.language,t.metadata=e.metadata,t.nbest=e.nbest||3,t.speech_to_text=e.speech_to_text,this.task=t,this.action.startAudioTask(t),!0}stop(e){return this.action&&this.action.status!==s.ActionStatus.STOPPED?(this.stopCallbacks.push(e),void(this.action.status!==s.ActionStatus.STOPPING&&this.action.stop(()=>{this.stopCallbacks.forEach(e=>{e&&e()}),this.emit("finished"),this.removeAllListeners(),this.stopCallbacks=[]}))):void(e&&e())}destroy(){this.removeAllListeners(),this.action&&this.action.stop()}_consolidateResults(e){this._hasHotphrase&&this._hasSpeakerId&&(this._hasHotphrase=!1,this._hasSpeakerId=!1,e&&this.stop())}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"./ASRService":11,"./AudioAction":13,events:void 0,"jibo-common-types":void 0}],17:[function(e,t,i){"use strict";const n=e("events"),s=e("./ASRService"),o=e("./ASRService");let r=e("uuid");class a extends n.EventEmitter{constructor(e){super(),this.listenerId=r.v4(),this.word=e.word,this.verbose=e.verbose||!1}setAudioSourceId(e){this.audioSourceId=e}onFinished(){this.nameLearningAction&&this.nameLearningAction.stopOldTask(()=>{this.nameLearningAction.clearOldTask(()=>{this.emit("finished")})})}start(){return this.g2pAction=s.default.instance.createAudioAction(o.UrlInterface.PRONUN,"0"),this.g2pAction.on("error",e=>{this.emit("error",e)}),this.g2pAction.on("got-pronunciations",e=>{this.emit("generated-pronun",e)}),this.g2pAction.on("pronun-error",e=>{this.emit("pronun-error",e)}),this.g2pAction.generateGraphemeToPhoneme(this),!0}collectExample(){let e=new s.default.instance.NameRecognizer(this.word),t=e.pack();this.nameLearningAction=s.default.instance.createAudioAction(o.UrlInterface.OLD),this.nameLearningAction.on("got-pronunciations",e=>{e.success&&this.emit("heard-pronun",e)}),this.nameLearningAction.on("pronun-error",e=>{this.emit("pronun-error",e),this.onFinished()}),this.nameLearningAction.on("finished",()=>{this.onFinished()}),this.nameLearningAction.startOldTask(t)}stop(){this.onFinished()}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"./ASRService":11,events:void 0,uuid:void 0}],18:[function(e,t,i){"use strict";const n=e("./Recognizer"),s=e("./ASRService");class o extends n.default{constructor(e){let t={path:"namelearning",timeout:0};super(t),this.word=e,this.path=s.default.instance.OLD_BASE+"namelearning"}toString(){return this.pack()}pack(){let e={name:"name_learning",path:this.path,timeout:1e5,speaker_name:this.word,bargein:!1,incremental:!1};return JSON.stringify(e)}onResult(e){console.log("name reco onresult"),this.emit("result",e)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=o},{"./ASRService":11,"./Recognizer":19}],19:[function(e,t,i){"use strict";const n=e("uuid"),s=e("./ASRVariables"),o=e("./ASRService"),r=e("events");class a extends r.EventEmitter{constructor(e){super(),this.name=e.name||n.v4(),e=e||{},this.bargein="boolean"!=typeof e.bargein||e.bargein,this.incremental="boolean"==typeof e.incremental&&e.incremental,this.timeout=e.timeout?e.timeout:0,this.speakerName=e.speakerName?e.speakerName:"",this.speakerId="boolean"!=typeof e.speakerId||e.speakerId,this.nbest=e.nbest||1,this.delay=e.delay,e.path?this.path=o.default.instance.OLD_BASE+e.path:this.path=o.default.instance.OLD_BASE+"nuance_curlmulti";let t=this.path.split("/");this.name=t[t.length-1]+"-"+this.name,s.default.idToRecognizer[this.name]=this}setPath(e){this.path=o.default.instance.OLD_BASE+e}toString(){return this.pack()}pack(){return JSON.stringify({name:this.name,path:this.path,bargein:this.bargein,nbest:this.nbest,delay:this.delay,speaker_name:this.speakerName,speaker_id:this.speakerId,incremental:this.incremental,timeout:this.timeout})}onResult(e){if(e.utterances&&e.utterances.length>0){let t={speaker_ids:e.speaker_ids,speaker_idstatus:e.speaker_idstatus};this.emit("result",e.utterances[0],t)}else{let t={speaker_ids:e.speaker_ids,speaker_idstatus:e.speaker_idstatus};this.emit("result","",t)}}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"./ASRService":11,"./ASRVariables":12,events:void 0,uuid:void 0}],20:[function(e,t,i){"use strict";const n=e("uuid"),s=e("./ASRVariables"),o=e("events");class r extends o.EventEmitter{constructor(e){super(),this.httpInterface=e,this.id="spkr-action-"+n.v4(),s.default.idToAction[this.id]=this}setAudioSourceId(e){this.audioSourceId=e}deleteSpeaker(e="",t){let i=new XMLHttpRequest,n={action:"delete",task_id:this.id,spkr_id_type:t,speaker_name:e};const s=JSON.stringify(n);i.open("POST",this.httpInterface,!0),i.send(s)}listSpeakers(e="",t){let i=new XMLHttpRequest,n={action:"list",task_id:this.id,spkr_id_type:t||"TD+TI",speaker_name:e};const s=JSON.stringify(n);i.open("POST",this.httpInterface,!0),i.send(s)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=r},{"./ASRVariables":12,events:void 0,uuid:void 0}],21:[function(e,t,i){"use strict";const n=e("./Recognizer");class s extends n.default{constructor(e={}){e.enrollTD?e.path="sensory_spkr_enroll_td":e.enrollTI?e.path="sensory_spkr_enroll_ti":e.authTD?e.path="sensory_spkr_id_td":e.authTI&&(e.path="sensory_spkr_id_ti"),e.name="Speaker Enroll TD",super(e),this.enroll_mode=e.enroll_mode}toString(){return this.pack()}setEnrollMode(e){this.enroll_mode=e}pack(){let e={name:this.name,path:this.path,bargein:this.bargein,nbest:this.nbest,timeout:this.timeout,speaker_name:this.speakerName,incremental:this.incremental,enroll_mode:void 0===this.enroll_mode?2:this.enroll_mode,audio_tail_length:1};return JSON.stringify(e)}onResult(e){console.warn("SPEAKER ID RECO DATA",e);let t=e.sid_speech_status?e.sid_speech_status[0]:e.speaker_id_record,i={status:t.utt_status,noisy:""!==t.noise_level,loudness:t.loudness_level,badAudio:""!==t.audio_quality,snrValue:t.snr_value};this.emit("result",i)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"./Recognizer":19}],22:[function(e,t,i){"use strict";const n=e("jibo"),s=e("../clients/SystemManagerClient");class o{getConfig(e){console.log("6",Date.now()),s.default.createInstance("127.0.0.1",8585),n.systemManager.httpInterface="http://127.0.0.1:8585",n.systemManager.getMode((t,i)=>{return t?e(t):void e(null,`/usr/local/etc/jibo-ssm/jibo-ssm-${i}.json`,i)})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=o},{"../clients/SystemManagerClient":10,jibo:void 0}],23:[function(e,t,i){"use strict";function n(){return new d}const s=e("path"),o=e("electron"),r=e("find-root"),a=e("events"),c=e("jibo-log"),u=e("../clients/SystemManagerClient");let l=new c("ssm-main-process");l.toSyslog();class d extends a.EventEmitter{constructor(){super(),u.default.createInstance("127.0.0.1",8585),l.debug("SSM Started"),this.onReady=this.onReady.bind(this),this.onCrashed=this.onCrashed.bind(this),this.onShow=this.onShow.bind(this),this.onHide=this.onHide.bind(this),this.onGetPid=this.onGetPid.bind(this),o.app.isReady()?this.onReady():o.app.on("ready",this.onReady),o.ipcMain.on("show",this.onShow),o.ipcMain.on("hide",this.onHide),o.ipcMain.on("get-pid",this.onGetPid),o.ipcMain.on("cleanedup",()=>{o.app.quit()})}onShow(){this.skillWindow.show(),this.skillWindow.focus(),this.skillWindow.setPosition(0,0)}onHide(){this.skillWindow.hide()}onCrashed(){l.error("SSM Renderer Process Crashed"),l.error("Checking for running skills"),u.default.instance.list((e,t)=>{if(e)return l.error("System Manager error. Restarting SSM.",e),this.onReady();for(let i=0;i<t.length;i++)if(t[i].running)return l.error("Terminating ",t[i].name),void u.default.instance.terminate(t[i].name,e=>{l.error("Restarting SSM renderer process"),this.skillWindow.reload()});l.error("No skill to shut down. Restarting SSM renderer process"),this.onReady()})}onReady(){this.skillWindow=new o.BrowserWindow({x:0,y:0,show:!1,width:d.WIDTH,height:d.HEIGHT,backgroundColor:"#000000",frame:!1}),this.skillWindow.on("closed",this.onSkillWindowClosed),this.skillWindow.webContents.on("crashed",this.onCrashed);let e=s.join(r(__dirname),"index.html");console.log("onReady",e),this.skillWindow.loadURL("file://"+e),this.skillWindow.webContents.once("did-finish-load",()=>{this.skillWindow.show()})}onSkillWindowClosed(){this.skillWindow=null}onGetPid(e){e.sender.send("set-pid",process.pid)}}d.WIDTH=1280,d.HEIGHT=720,Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{"../clients/SystemManagerClient":10,electron:void 0,events:void 0,"find-root":void 0,"jibo-log":void 0,path:void 0}],24:[function(e,t,i){"use strict";function n(){return s(this,void 0,void 0,function*(){"--reporter"===process.argv[3]&&(r.default.createInstance({port:10101},"reporter-service"),yield a.default.get(e=>r.default.instance.init(e))),console.log("pre create main"),o.default()})}var s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?s(e.value):new i(function(t){t(e.value)}).then(r,a)}c((n=n.apply(e,t||[])).next())})};const o=e("./MainProcess"),r=e("./reporter/ReporterService"),a=e("../utils/Async");n()},{"../utils/Async":86,"./MainProcess":23,"./reporter/ReporterService":25}],25:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?s(e.value):new i(function(t){t(e.value)}).then(r,a)}c((n=n.apply(e,t||[])).next())})};const s=e("path"),o=e("jibo-service-framework"),r=e("fs"),a=e("../../utils/Async"),c=e("jibo-service-framework"),u=["electron","jibo","pulseaudio"],l="/var/log",d=s.join(l,"monitoring.log");class h extends o.HTTPService{constructor(e,t){super("monitor-reporter",e,t),this.stopped=!1,this.initialized=!1,h._instance=this,this.addReport=this.addReport.bind(this)}static createInstance(e,t){return new h(e,t)}static get instance(){return h._instance}init(e){const t=e=>super[e];return n(this,void 0,void 0,function*(){c.RegistryClient.createInstance("127.0.0.1",8181),yield a.default.get(e=>t("init").call(this,e)),this.client=new o.WSClient(`ws://127.0.0.1:4111/info/process`),this.initialized=!0;const i=s.join(l,`monitoring-${Date.now()}.log`),n=yield a.default.get2(e=>r.exists(d,e));n&&(yield a.default.get(e=>r.rename(d,i,e))),e(),this.start()})}routes(e){super.routes(e),e.post("/report",this.addReport)}addReport(e,t){return n(this,void 0,void 0,function*(){const t=yield this.parseRequest(e);yield a.default.get(e=>r.appendFile(d,JSON.stringify(t)+"\n",e))})}addEvent(e){return n(this,void 0,void 0,function*(){if(this.initialized){const t={type:"event",ts:Date.now(),data:e};yield a.default.get(e=>r.appendFile(d,JSON.stringify(t)+"\n",e))}})}stop(){this.stopped=!0}start(){return n(this,void 0,void 0,function*(){for(;!this.stopped;){const e=yield a.default.get2(e=>this.client.once("message",e)),t={type:"processes",ts:Date.now(),total_cpu_jiffies:e.total_cpu_jiffies,data:[]};for(let i=0;i<e.processes.length;i++){const n=e.processes[i];for(let s=0;s<u.length;s++)n.name.indexOf(u[s])>=0&&t.data.push(n)}yield a.default.get(e=>r.appendFile(d,JSON.stringify(t)+"\n",e))}})}parseRequest(e){return new Promise((t,i)=>{let n="";e.on("data",e=>{n+=e}),e.on("end",()=>{let e;try{e=JSON.parse(n),t(e)}catch(e){i(e)}})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=h},{"../../utils/Async":86,fs:void 0,"jibo-service-framework":void 0,path:void 0}],26:[function(e,t,i){"use strict";const n=e("uuid"),s=e("jibo-common-types");var o;!function(e){e[e.NORMAL="normal"]="NORMAL",e[e.ERROR="error"]="ERROR",e[e.RECEIVED="received"]="RECEIVED"}(o=i.ResponseStatus||(i.ResponseStatus={}));var r;!function(e){e[e.HOTPHRASE="hotphrase"]="HOTPHRASE",e[e.END_OF_SPEECH="end_of_speech"]="END_OF_SPEECH",e[e.START_OF_SPEECH="start_of_speech"]="START_OF_SPEECH",e[e.INCREMENTAL="speech_to_text_incremental"]="INCREMENTAL",e[e.SPEECH_TO_TEXT_FINAL="speech_to_text_final"]="SPEECH_TO_TEXT_FINAL",e[e.SPEAKER_ID="speaker_id"]="SPEAKER_ID",e[e.RECEIVED="received"]="RECEIVED",e[e.ACKNOWLEDGEMENT="acknowledgement"]="ACKNOWLEDGEMENT",e[e.ERROR="error"]="ERROR"}(r=i.EventType||(i.EventType={}));class a{constructor(e){e=Object.assign(this,{task_id:"",status:o.NORMAL,message:"",event_type:r.ERROR,speaker_id:new s.SpeakerId,timestamp:0,utterances:[{utterance:"",score:0}],message_id:"simulated-"+n.v4(),request_id:""},e||{})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"jibo-common-types":void 0,uuid:void 0}],27:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("./ASRResponse"),o=e("jibo-common-types"),r=e("../../utils/Log");let a=r.createLog("ssm-asr-service");class c{}class u extends n.HTTPWSService{constructor(e,t,i){super("asr",t,i),this.messages=[],this.sources=[],this.actions=new Map,u._instance=this,this.parseMessage=this.parseMessage.bind(this),this.connectionHandlers={"/asr_interface":this.onAsrInterface.bind(this),"/asr_simple_interface":this.onAsrSimple.bind(this),"/audio_source":this.onAudioSource.bind(this),"/spkr_id_interface":this.onSpeakerIdInterface.bind(this)},a.info("Initialized")}static get actions(){return u._instance.actions}static createInstance(e,t){return new u(new c,e,t)}static get instance(){return u._instance}init(e){super.init(t=>{e(t)})}onConnection(e){super.onConnection(e),"/simple_port"===e.upgradeReq.url&&(this.socket=e,this.processMessages())}routes(e){super.routes(e),e.post("/asr_interface",this.parseMessage),e.post("/asr_simple_interface",this.parseMessage),e.post("/audio_source",this.parseMessage),e.post("/spkr_id_interface",this.parseMessage)}onMessage(e,t){}onClose(e){this.socket=null,this.messages=[],this.sources=[],this.actions.clear(),this.currentSource=null}onWordsReceived(e){"TEST"===e.message&&console.log(e),this.actions.forEach(t=>{if(t.isActive){if(t.hasBeenAcknowledged||(t.hasBeenAcknowledged=!0,this._sendAcknowledgement(t,e)),"TEST"===e.message&&console.log(t),e.words&&(e.words=e.words.trim()),t.hasMadeFirstResponse||(t.hasMadeFirstResponse=!0,this._sendSpeakerId(t,e)),t.hotphrase&&!t.heardHotphrase){let i=e.words?e.words.indexOf("hey jibo"):-1;if(i===-1)return;if(t.heardHotphrase=!0,this._sendHotphrase(t,e),!e.final)return}e.final?(t.isActive=!1,this._sendEOS(t,e),this._sendSTTFinal(t,e),this._sendAcknowledgement(t,e)):this._sendIncremental(t,e)}})}_sendHotphrase(e,t){let i=this._makeASRRequestFromAction(e,t);i.event_type=s.EventType.HOTPHRASE,i.utterances=[{utterance:"hey jibo",score:1e3}],this.sendOptions(i)}_sendSpeakerId(e,t){let i=this._makeASRRequestFromAction(e,t);i.event_type=s.EventType.SPEAKER_ID,i.utterances=[{utterance:"",score:1e3}],this.sendOptions(i)}_sendIncremental(e,t){if(e.incremental&&e.speech_to_text){let i=this._makeASRRequestFromAction(e,t);t.utterances?i.utterances=t.utterances:i.utterances=[{utterance:t.words,score:1e3}],i.event_type=s.EventType.INCREMENTAL,this.sendOptions(i)}}_sendEOS(e,t){let i=this._makeASRRequestFromAction(e,t);i.event_type=s.EventType.END_OF_SPEECH,this.sendOptions(i)}_sendSTTFinal(e,t){if(e.speech_to_text){let i=this._makeASRRequestFromAction(e,t);t.utterances?i.utterances=t.utterances:i.utterances=[{utterance:t.words,score:1e3}],i.event_type=s.EventType.SPEECH_TO_TEXT_FINAL,this.sendOptions(i)}}_sendAcknowledgement(e,t){let i=this._makeASRRequestFromAction(e,t);i.event_type=s.EventType.ACKNOWLEDGEMENT,this.sendOptions(i)}sendOptions(e){this.socket.send(JSON.stringify(e))}_makeASRRequestFromAction(e,t){let i=new s.default;return i.task_id=e.task_id,i.request_id=e.request_id,i.speaker_id=new o.SpeakerId({status:"NOT-USED",speakers:[]}),t.speaker&&(i.speaker_id.status="ACCEPTED",i.speaker_id.speakers.push(new o.Speaker(t.speaker,1e3))),i}parseMessage(e,t){e.on("data",i=>{let n;try{n=JSON.parse(i),this.messages.push({url:e.url,data:n,res:t})}catch(e){this.socket&&this.sendWsJson(this.socket,{status:"error",message:"ERROR Invalid request. Request body is not valid JSON"}),this.sendJson(t,{Status:"ERROR",Message:"Inavlid request. Request body is not valid JSON"},200)}this.socket&&this.processMessages()})}processMessages(){for(;this.messages.length;){let e=this.messages.shift();this.connectionHandlers[e.url](e.data,e.res)}}onAsrSimple(e,t){let i,n=new s.default({message:"received data request",task_id:e.task_id,status:s.ResponseStatus.NORMAL,event_type:s.EventType.ACKNOWLEDGEMENT}),o="received data request";"start"===e.command?(this.actions.has(e.task_id)?i=this.actions.get(e.task_id):(this.actions.set(e.task_id,e),i=e),i.isActive=!0,this.sendResponse(t,n)):"enroll"===e.command?(this.sendResponse(t,n),n.status=s.ResponseStatus.ERROR,o="ERROR: cannot enroll via simulated ASR"):"stop"===e.command&&(i=this.actions.get(e.task_id),i&&i.isActive?i.isActive=!1:(n.status=s.ResponseStatus.ERROR,o="ERROR: cannot stop action which was not started"+e.task_id),this.sendResponse(t,n))}onAsrInterface(e,t){let i,n=new s.default({message:"received data request",task_id:e.task_id,status:s.ResponseStatus.NORMAL,event_type:s.EventType.RECEIVED}),o="received data request";"start"===e.command?(this.actions.has(e.task_id)?i=this.actions.get(e.task_id):(this.actions.set(e.task_id,e),i=e),i.isActive=!0,this.sendResponse(t,n)):"enroll"===e.command?(this.sendResponse(t,n),n.status=s.ResponseStatus.ERROR,o="ERROR: cannot enroll via simulated ASR"):"stop"===e.command&&(i=this.actions.get(e.task_id),i?i.isActive=!1:(n.status=s.ResponseStatus.ERROR,o="ERROR: cannot stop action which was not started"+e.task_id),this.sendResponse(t,n))}sendResponse(e,t){this.sendJson(e,{Status:"OK",Message:"received ASR request"},200),this.sendWsJson(this.socket,t)}onAudioSource(e,t){let i=new s.default({status:s.ResponseStatus.RECEIVED,task_id:e.task_id});if("start"===e.action)this.sources.push(e.audio_source_id),this.currentSource=e.audio_source_id;else if("clear"===e.action){let t=this.sources.indexOf(e.audio_source_id);this.sources.splice(t,1)}this.sendJson(t,{Status:"OK",Message:"received data request"},204),this.sendWsJson(this.socket,i)}onSpeakerIdInterface(e,t){this.sendJson(t,{Status:"OK",Message:"received data request"},200);let i={status:s.ResponseStatus.RECEIVED,type:"spkrId"};this.sendWsJson(this.socket,i)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=u},{"../../utils/Log":88,"./ASRResponse":26,"jibo-common-types":void 0,"jibo-service-framework":void 0}],28:[function(e,t,i){"use strict";class n{constructor(){this.ts=[0,0],this.pos=0,this.inc_pos=0,this.vel=0,this.cur=0,this.pwm=0,this.status=1,this.vel_limit=10,this.acc_limit=10,this.cur_limit=10,this.mode=4,this.ref=0,this.ticks=0}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{}],29:[function(e,t,i){"use strict";const n=e("animation-utilities");class s{constructor(e,t,i){this.initialPosition=e,this.velocity=t,this.initialTime=i,null!==i&&void 0!==i||(i=n.Clock.currentTime()),this.initialTime=i}getPosition(e){null!==e&&void 0!==e||(e=n.Clock.currentTime());let t=e.subtract(this.initialTime);return this.initialPosition+this.velocity*t}getVelocity(){return this.velocity}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"animation-utilities":void 0}],30:[function(e,t,i){"use strict";const n=e("animation-utilities"),s=e("./BodyState"),o=e("./AxisVelocityControllerSim"),r=e("jibo-service-framework"),a=e("../../utils/Log");let c=a.createLog("ssm-body-service");class u{}class l{constructor(){this.pelvis=new o.default(0,0),this.torso=new o.default(0,0),this.neck=new o.default(0,0)}}class d extends r.HTTPWSService{constructor(e,t,i){super("body",t,i),this.commandSocketList=[],this.ledSocketList=[],this.stateSocketList=[],this.ledState=[0,0,0],this.state=new s.default,this.simControllers=new l,d._instance=this,this.update=this.update.bind(this),c.info("Initialized")}static createInstance(e,t){return new d(new u,e,t)}static get instance(){return d._instance}init(e){super.init(t=>{setImmediate(this.update),e(t)})}reset(){this.state=new s.default,this.simControllers=new l}onMessage(e,t){"/axis_command"===t.upgradeReq.url?this.onAxisCommand(e):"/led_command"===t.upgradeReq.url&&this.onLEDCommand(e)}onClose(e){this.commandSocketList.indexOf(e)>-1?this.commandSocketList.splice(this.commandSocketList.indexOf(e),1):this.ledSocketList.indexOf(e)>-1?this.ledSocketList.splice(this.ledSocketList.indexOf(e),1):this.stateSocketList.indexOf(e)>-1&&this.stateSocketList.splice(this.stateSocketList.indexOf(e),1)}onConnection(e){super.onConnection(e),"/axis_state"===e.upgradeReq.url?this.stateSocketList.push(e):"/axis_command"===e.upgradeReq.url?this.commandSocketList.push(e):"/led_command"===e.upgradeReq.url&&this.ledSocketList.push(e),this.sendState()}onAxisCommand(e){this.lastUpdate=performance.now();let t=n.Clock.currentTime(),i=this.simControllers;for(let s of Object.keys(i))4===e[s].mode?i[s]=new o.default(i[s].getPosition(t),e[s].value[0],t):5===e[s].mode?(i[s]=new n.TrajectoryControllerSim(i[s].getPosition(t),i[s].getVelocity(t),t),i[s].updateCommand(e[s].value[1],e[s].value[0],e[s].value[2],e[s].acc_limit,e[s].vel_limit,t)):7===e[s].mode?(i[s]=new n.PosVelControllerSim(i[s].getPosition(t),i[s].getVelocity(t),t),i[s].updateCommand(e[s].value[1],e[s].value[0],e[s].acc_limit,e[s].vel_limit,t)):i[s]=new o.default(i[s].getPosition(t),0,t);this.updateState(),this.sendState()}onLEDCommand(e){e.color&&Array.isArray(e.color)&&3===e.color.length&&(this.ledState=e.color)}updateState(){let e=n.Clock.currentTime(),t=performance.now()-this.lastUpdate<500;for(let i of Object.keys(this.simControllers))t?this.state[i].vel=this.simControllers[i].getVelocity(e):this.state[i].vel=0,this.state[i].pos=this.simControllers[i].getPosition(e)}sendState(){if(this.stateSocketList.length>0){let e=n.Clock.currentTime()._timestamp;this.state.neck.ts=e,this.state.torso.ts=e,this.state.pelvis.ts=e,this.state.ts=e;for(let t of this.stateSocketList)this.sendWsJson(t,this.state)}}update(){let e={topSection_r:this.state.neck.pos,middleSection_r:this.state.torso.pos,bottomSection_r:this.state.pelvis.pos,lightring_redChannelBn_r:this.ledState[0],lightring_greenChannelBn_r:this.ledState[1],lightring_blueChannelBn_r:this.ledState[2]};this.emit("update",e),setImmediate(this.update)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=d},{"../../utils/Log":88,"./AxisVelocityControllerSim":29,"./BodyState":31,"animation-utilities":void 0,"jibo-service-framework":void 0}],31:[function(e,t,i){"use strict";const n=e("./AxisState");class s{constructor(){this.ts=[0,0],this.pelvis=new n.default,this.torso=new n.default,this.neck=new n.default}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"./AxisState":28}],32:[function(e,t,i){"use strict";function n(e,t){let i=a.createServer({target:{host:"0.0.0.0",port:e}});return i.on("error",e=>{p.info("Debug Proxy socket error: "+e)}),i.on("close",()=>{p.info("Debug Proxy socket closed")}),i.listen(t,e=>{e&&p.info("Error with Debug Proxy: "+e)}),i}const s=e("path"),o=e("ws-without-native"),r=e("jibo-service-framework"),a=e("tcp-proxy"),c=e("jibo-sync"),u=e("../skills-service/SkillsService"),l=e("child_process"),d=e("http"),h=e("jibo"),f=e("../../utils/Log");let p=f.createLog("ssm-dev-shell");i.createProxyServer=n;class m extends r.HTTPWSService{static createInstance(e,t){return new m(e,t)}static get instance(){return m._instance}constructor(e,t){super("dev-shell",e,t),m._instance=this,this._skillDest=e.skillDest,this._sdkDest=e.sdkDest,this._syncPort=e.syncPort,this._otaSocket=null,p.info("Initialized")}init(e){super.init(t=>{this.server.timeout=0,e(t)})}routes(e){super.routes(e),e.post("/sync-skill",this._syncSkill.bind(this)),e.post("/delete-skill",this._deleteSkill.bind(this)),e.post("/run",this._startSkill.bind(this)),e.post("/stop",this._stopSkill.bind(this)),e.post("/diskspace",this._diskSpace.bind(this)),e.post("/reboot",this._reboot.bind(this)),e.post("/poweroff",this._poweroff.bind(this)),e.post("/version",this._getVersion.bind(this)),e.post("/index",this._index.bind(this)),e.post("/setvolume",this._setVolume.bind(this)),e.post("/getvolume",this._getVolume.bind(this)),e.post("/check-update",this._checkForUpdates.bind(this)),e.post("/download-update",this._downloadUpdates.bind(this)),e.post("/install-update",this._installUpdates.bind(this))}onConnection(e){super.onConnection(e),"/download-update"===e.upgradeReq.url&&(console.log("Opening OTA download socket"),this._otaSocket=e)}onClose(e){e===this._otaSocket&&(console.log("Closing OTA download socket"),this._otaSocket=void 0)}onMessage(e,t){}parseRequest(e,t,i){if(e.body)return void i(e.body);let n="";e.on("data",function(e){n+=e}),e.on("end",function(){let e;try{e=JSON.parse(n)}catch(e){this.sendJson(t,{Status:"ERROR",Message:"Invalid request. Request body is not valid JSON"},200),i(null)}i(e)}),e.on("error",function(e){this.sendJson(t,{Status:"ERROR",Message:"Error parsing dev shell request: "+e.message},200),i(null)})}_syncSkill(e,t){p.info("Syncing skill"),this.parseRequest(e,t,e=>{let i=e.dirName,n=this._skillDest+"/"+i,s=!0;c.createServer(this._syncPort,n,s,e=>{e?(t.writeHead(200,{"Content-Type":"text/plain"}),t.write(JSON.stringify({Status:"ERROR",Message:e})),t.end()):(t.writeHead(200,{"Content-Type":"text/plain"}),t.write(JSON.stringify({Status:"OK",Message:"Sync server started successfully"})),t.end())})})}_startSkill(e,t){this.parseRequest(e,t,e=>{this.sendJson(t,{Status:"ERROR",Message:e.command},200);let i=e.dirName;u.default.instance.launch(i,{},e=>{e?this.sendJson(t,{Status:"ERROR",Message:'Error starting "'+i+"\n"+e.message},200):this.sendJson(t,{Status:"OK",Message:'Skill "'+name+'" started successfully'},200)})})}_stopSkill(e,t){
|
||
console.log("Stopping skill"),u.default.instance.terminate(e=>{e?this.sendJson(t,{Status:"ERROR",Message:"Error stopping: "+e},200):this.sendJson(t,{Status:"OK",Message:"Stopped skill successfully."},200)})}_deleteSkill(e,t){p.info("Deleting skill"),this.parseRequest(e,t,e=>{let i=e.dirName,n=this._skillDest+"/"+i,s="rm -rf "+n;l.exec(s,e=>{e?this.sendJson(t,{Status:"ERROR",Message:"Error deleting: "+e},200):this.sendJson(t,{Status:"OK",Message:"Skill deleted successfully."},200)})})}_diskSpace(e,t){p.info("Retrieving disk space");let i=s.join(this.rootDir,this._sdkDest+"disk-space.sh"),n=l.spawn("sh",[`${i}`,`${this._skillDest}`]),o="not found: "+i;n.stdout.on("data",e=>{o=e}),n.on("exit",()=>{this.sendJson(t,{Status:"OK",Message:"Diskspace Usage ["+this._skillDest+"]:\n\n"+o},200)})}_reboot(e,t){p.info("Rebooting"),l.exec("reboot",e=>{e?this.sendJson(t,{Status:"ERROR",Message:"Error trying to reboot: "+e},200):this.sendJson(t,{Status:"OK",Message:"Rebooting..."},200)})}_poweroff(e,t){p.info("Powering off"),l.exec("poweroff",e=>{e?this.sendJson(t,{Status:"ERROR",Message:"Error trying to poweroff: "+e},200):this.sendJson(t,{Status:"OK",Message:"Powering off..."},200)})}_getVersion(e,t){p.info("Retrieving version");let i=!1,n=l.spawn("jibo-version"),s="Not found";n.stdout.on("data",e=>{i||(s=e,this.sendJson(t,{Status:"OK",Message:`${s}`},200)),i=!0,n.kill("SIGTERM")}),n.stderr.on("data",e=>{i||(s=e,this.sendJson(t,{Status:"ERROR",Message:`${s}`},200)),i=!0,n.kill("SIGTERM")})}_index(e,t){p.info("Indexing");let i;r.RegistryClient.instance.getRecords((e,n)=>{function s(e){return void 0===e?null!==d&&!!(1&d.pelvis.status)&&!!(1&d.torso.status)&&!!(1&d.neck.status):!!d.hasOwnProperty(e)&&!!(1&d[e].status)}function r(e,t,i){if(null!==d){let n={mode:e?0:4,value:e?[0]:[-1],vel_limit:d.pelvis.vel_limit,acc_limit:d.pelvis.acc_limit,cur_limit:d.pelvis.cur_limit},s={mode:t?0:4,value:t?[0]:[-1],vel_limit:d.torso.vel_limit,acc_limit:d.torso.acc_limit,cur_limit:d.torso.cur_limit},o={mode:i?0:4,value:i?[0]:[-1],vel_limit:d.neck.vel_limit,acc_limit:d.neck.acc_limit,cur_limit:d.neck.cur_limit},r={ts:[d.ts[0],d.ts[1]],pelvis:n,torso:s,neck:o};return JSON.stringify(r)}}for(let a=0;a<n.length;a++){let e=n[a];if("body"===e.name){i=e;break}}if(!i)return void this.sendJson(t,{Status:"ERROR",Message:"Cannot find body service"},200);let c="ws://"+i.host+":"+i.port,u=new o(c+"/axis_state");u.onerror=(()=>{this.sendJson(t,{Status:"ERROR",Message:"Error opening axis_state socket"},200)});let l=new o(c+"/axis_command");l.onopen=function(){console.log("Axis command socket open!")},l.onmessage=function(e){console.log("Got command message: "+e.data)},l.onclose=function(){console.log("Axis command socket close!")};let d=null,h=300,f=e=>{h--,d=JSON.parse(e);let i=s();if(h<0||i){let e="Robot is "+(i?"":"NOT ")+"indexed.";return h<0&&(e+=" (timed out)"),p.info(e),this.sendJson(t,{Status:i?"OK":"ERROR",Message:e},200),u.removeListener("message",f),l.close(),void u.close()}if(l.readyState===o.OPEN){let e=s("pelvis"),t=s("torso"),i=s("neck"),n=r(e,t,i);l.send(n)}};u.on("message",f)})}_getMixerSettings(e,t){let i=d.get(e,i=>{let n="";i.on("data",e=>{n+=e}),i.on("end",()=>{let i=void 0;try{i=JSON.parse(n)}catch(i){return void t("Cannot retrieve mixer settings from "+e,null)}t(null,i)})});i.on("error",()=>{t("Cannot retrieve mixer settings from "+e,null)})}_getVolume(e,t){p.info("Getting volume"),this.parseRequest(e,t,()=>{let e;r.RegistryClient.instance.getRecords((i,n)=>{for(let s=0;s<n.length;s++){let t=n[s];if("audio"===t.name){e=t;break}}if(!e)return void this.sendJson(t,{Status:"ERROR",Message:"Cannot find audio service"},200);let o="http://"+e.host+":"+e.port+"/mixer";this._getMixerSettings(o,(e,i)=>{if(e)this.sendJson(t,{Status:"ERROR",Message:e},200);else{let e=i.master.playbackVolume;this.sendJson(t,{Status:"OK",Message:e.toFixed(2)+" [0.0-1.0]"},200)}})})})}_setVolume(e,t){p.info("Setting volume"),this.parseRequest(e,t,e=>{let i,n=e.volume;r.RegistryClient.instance.getRecords((e,s)=>{for(let o=0;o<s.length;o++){let e=s[o];if("audio"===e.name){i=e;break}}if(!i)return void this.sendJson(t,{Status:"ERROR",Message:"Cannot find audio service"},200);let r="http://"+i.host+":"+i.port+"/mixer";this._getMixerSettings(r,(e,s)=>{if(e)this.sendJson(t,{Status:"ERROR",Message:e},200);else{let e={hostname:i.host,port:i.port,path:"/mixer",method:"POST",headers:{"Content-Type":"application/json"}},o=d.request(e,e=>{let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{this.sendJson(t,{Status:"OK",Message:n.toFixed(2)},200)})});o.on("error",e=>{this.sendJson(t,{Status:"ERROR",Message:"Cannot set master volume ("+e+")"},200)}),s.master.playbackVolume=n,o.write(JSON.stringify(s)),o.end()}})})})}_checkForUpdates(e,t){this.parseRequest(e,t,e=>{p.info("Checking for updates"),h.systemManager.checkForUpdates((e,i)=>{if(e||!i)return void this.sendJson(t,{Status:"ERROR",Message:e?e:"Service temporarily unavailable."},200);const n=i.length;let s="";for(let o=0;o<n;o++)s+="\n"+i[o].id+": "+i[o].changes,i[o].downloaded&&(s+=" [DOWNLOADED]");let r="Found "+n+" update"+(n>1||0===n?"s":"")+s;this.sendJson(t,{Status:"OK",Message:{msg:r,data:i}},200)},e.filter)})}_downloadUpdates(e,t){this.parseRequest(e,t,e=>{p.info("Downloading updates",e),h.systemManager.downloadUpdates(e,(e,i)=>{if(e||"failed"===i.status){let n=e?e:i.reason;this.sendJson(t,{Status:"ERROR",Message:"Error downloading OTA updates: "+n},200)}else"downloading"===i.status?this._otaSocket&&this.sendWsJson(this._otaSocket,i):this.sendJson(t,{Status:"OK",Message:i},200)})})}_installUpdates(e,t){this.parseRequest(e,t,e=>{p.info("Installing updates",e),h.systemManager.installUpdates(e,e=>{e?this.sendJson(t,{Status:"ERROR",Message:"Error installing OTA updates: "+e},200):this.sendJson(t,{Status:"OK",Message:"Installing OTA updates! Robot will reboot a handful of times in between installations. Go get a snack."},200)})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=m},{"../../utils/Log":88,"../skills-service/SkillsService":72,child_process:void 0,http:void 0,jibo:void 0,"jibo-service-framework":void 0,"jibo-sync":void 0,path:void 0,"tcp-proxy":void 0,"ws-without-native":void 0}],33:[function(e,t,i){"use strict";const n=e("./ErrorServiceUtil");class s{constructor(e,t,i,n){this._errorCodeMap={},this._activeErrorCodes={},this._lastErrorCodes={},this._reportPlatformErrorCallback=null,this._addSSMErrorCallback=null,this._removeSSMErrorCallback=null,this._errorCodeMap=e,this._addSSMErrorCallback=t,this._removeSSMErrorCallback=i,this._reportPlatformErrorCallback=n,setInterval(this._platformErrorTick.bind(this),1e3)}mockErrorRequest(e){this._activeErrorCodes={};for(let t=0;t<e.codes.length;++t){let i=e.codes[t];this._errorCodeMap.hasOwnProperty(i)&&(this._activeErrorCodes[i]=this._errorCodeMap[i])}this._updateSSMErrors(),this._lastErrorCodes=this._activeErrorCodes}_updateSSMErrors(){Object.keys(this._activeErrorCodes).forEach(e=>{this._errorCodeMap.hasOwnProperty(e)&&!this._errorCodeMap[e].platformCode&&this._addSSMErrorCallback(e)});let e=n.default.getNonOccurringElements(this._lastErrorCodes,this._activeErrorCodes);for(let t=0;t<e.length;++t)e[t].platformCode||this._removeSSMErrorCallback(e[t].id)}_platformErrorTick(){let e=[];Object.keys(this._activeErrorCodes).forEach(t=>{this._errorCodeMap.hasOwnProperty(t)&&this._errorCodeMap[t].platformCode&&e.push(this._errorCodeMap[t].platformCode)});let t={codes:e};this._reportPlatformErrorCallback(t)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"./ErrorServiceUtil":37}],34:[function(e,t,i){t.exports={errorCodes:{"WIFI1-Cannot_connect_to_Wi-Fi_network":{code:"WIFI1",description:"Wi-Fi setup failure: Cannot associate with access point",title:"Can't connect to Wi-Fi network.",message:"Go to the app for help and to get a new QR code.\nTap here to connect with your new code...",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:6,repeatTime:2e3},"WIFI1a-Cannot_connect_to_Wi-Fi_network":{code:"WIFI1a",description:"Wi-Fi setup failure: Cannot associate with access point",title:"Can't connect to Wi-Fi network.",message:"Go to support.jibo.com for help,\nand tap the screen to check your Wi-Fi settings.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"<ssa cat='worried'/> Something's up with my WiFi connection.",spokenPromptOnResolution:"",priority:6,repeatTime:2e3},"WIFI2-Cannot_get_IP_address_from_router":{code:"WIFI2",description:"Wi-Fi setup failure: Cannot get IP address",title:"Can't get IP address from router.",message:"Go to the app for help and to get a new QR code.\nTap here to connect with your new code.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:6,repeatTime:5e3},"WIFI2a-Cannot_get_IP_address_from_router":{code:"WIFI2a",description:"Wi-Fi setup failure: Cannot get IP address",title:"Can't get IP address from router.",message:"Go to support.jibo.com for help,\nand tap the screen to check your Wi-Fi settings.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"<ssa cat='worried'/> Something's up with my WiFi.",spokenPromptOnResolution:"",priority:6,repeatTime:5e3},"WIFI4-Cannot_connect_to_Jibos_server":{code:"WIFI4",description:"Wi-Fi Setup failure: Server down",title:"Can't connect to Jibo's server.",message:"Go to the app for help and to get a new QR code.\nTap here to connect with your new code.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:6,repeatTime:5e3},"WIFI4a-Cannot_connect_to_Jibos_server":{code:"WIFI4a",description:"Wi-Fi Setup failure: Server down",title:"Can't connect to Jibo's server.",message:"Go to support.jibo.com for help,\nand tap the screen to check your Wi-Fi settings.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"<ssa cat='worried'/><tts config='worried'> Something doesn't feel right.</tts>",spokenPromptOnResolution:"Back in action.",priority:6,repeatTime:5e3},"WIFI5-Invalid_password_length":{code:"WIFI5",description:"Wi-Fi Setup failure: Password is too short",title:"Invalid password length.",message:"Go to the app for help and to get a new QR code.\nTap here to connect with your new code...",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:7,repeatTime:2e3},"WIFI5a-Invalid_password_length":{code:"WIFI5a",description:"Wi-Fi Setup failure: Password is too short",title:"Invalid password length.",message:"Go to the Jibo app for help and to get a new QR code.\nThen tap this screen to try connecting again.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"<ssa cat='oops'/> Seems like a little WiFi password issue.",spokenPromptOnResolution:"",priority:7,repeatTime:2e3},"WIFI6-SSID_not_provided":{code:"WIFI6",description:"Wi-Fi Setup failure: No network name provided",title:"SSID not provided.",message:"Go to the app for help and to get a new QR code.\nTap here to connect with your new code...",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:7,repeatTime:4e3},"WIFI6a-SSID_not_provided":{code:"WIFI6a",description:"Wi-Fi Setup failure: No network name provided",title:"SSID not provided.",message:"Go to the Jibo app for help and to get a new QR code.\nThen tap this screen to try connecting again.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"<ssa cat='worried'/> Seems like something's a little off with the WiFi set up.",spokenPromptOnResolution:"And we're back.",priority:7,repeatTime:4e3},"WIFI7-QR_code_expired":{code:"WIFI7",description:"Wi-Fi Setup failure: QR code 5 minute token timeout",title:"QR code expired.",message:"Go to the app for help and to get a new QR code.\nTap here to connect with your new code...",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:7,repeatTime:1500},"WIFI7a-QR_code_expired":{code:"WIFI7a",description:"Wi-Fi Setup failure: QR code 5 minute token timeout",title:"QR code expired.",message:"Go to the Jibo app for help and to get a new QR code.\nThen tap this screen to try connecting again.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"Something's up with your QR code.",spokenPromptOnResolution:"",priority:7,repeatTime:1500},"WIFIX-Uh_oh_something_happened":{code:"WIFIX",description:"",title:"Uh oh, something happened.",message:"Your Jibo didn't connect to Wi-Fi.\nTry rebooting him, or go to the app for help.\nTo change Wi-Fi settings, get a new QR code and tap here...",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:6,repeatTime:5e3},"WIFIXa-Uh_oh_something_happened":{code:"WIFIXa",description:"",title:"Jibo didn't connect to Wi-Fi.",message:"You can try rebooting him manually,\nor tap the screen to check your Wi-Fi settings.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"<ssa cat='worried'/><tts config='worried'> Something doesn't feel right.</tts>",spokenPromptOnResolution:"",priority:6,repeatTime:5e3},"OTA1a-Lost_Wi-Fi_connection":{code:"OTA1a",description:"Over the air update failure: Cannot communicate with router. Display this message for ~2 minutes before moving to next.",title:"Wi-Fi connection lost.",message:"Jibo is trying to reconnect. Moving him closer to\nyour router may help. To check Wi-Fi settings, tap the screen.",tapAction:"none",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:11,repeatTime:3e3},"OTA1b-Lost_Wi-Fi_connection":{code:"OTA1b",description:"Over the air update failure: Cannot communicate with router",title:"Wi-Fi connection lost.",message:"Jibo is trying to reconnect. Moving him closer to\nyour router may help. To check Wi-Fi settings, tap the screen.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:11,repeatTime:3e3},"OTA4-Lost_connection_to_Jibos_server":{code:"OTA4",description:"Over the air update failure: Jibo's server is down or Jibo lost internet connection.",title:"Lost connection to Jibo's server.",message:"Jibo will try to reconnect on his own.\nIn the meantime, go to support.jibo.com for troubleshooting.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:11,repeatTime:8e3},"OTA4a-Lost_connection_to_Jibos_server":{code:"OTA4a",description:"Over the air update failure: Jibo's server is down or Jibo lost internet connection.",title:"Lost connection to Jibo's server.",message:"Jibo will try to reconnect on his own.\nIn the meantime, go to support.jibo.com for troubleshooting.",tapAction:"wifi",icon:"wifi",spokenPromptOnError:"<ssa cat='worried'/><tts config='worried'> Something doesn't feel right.</tts>",spokenPromptOnResolution:"",priority:11,repeatTime:8e3},"OTA7-No_updates_found":{code:"OTA7",description:"",title:"No updates found.",message:"Jibo will try to find updates.\nIn the meantime, go to support.jibo.com for help.",tapAction:"wifi",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:18,repeatTime:8e3},"OTA7a-No_updates_found":{code:"OTA7a",description:"",title:"No updates found.",message:"Jibo will try to find updates.\nIn the meantime, go to support.jibo.com for help.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:18,repeatTime:8e3},"OTA8-Unexpected_server_response":{code:"OTA8",description:"",title:"Unexpected server response.",message:"Something may be wrong with your Wi-Fi.\nWhile Jibo tries to reconnect, go to support.jibo.com for help.",tapAction:"wifi",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:11,repeatTime:4e3},"OTA8a-Unexpected_server_response":{code:"OTA8a",description:"",title:"Unexpected server response.",message:"Something may be wrong with your Wi-Fi.\nWhile Jibo tries to reconnect, go to support.jibo.com for help.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"<ssa cat='worried'/><tts config='worried'> Something doesn't feel right.</tts>",spokenPromptOnResolution:"",priority:11,repeatTime:4e3},"OTAX-Uh_oh_something_happened":{code:"OTAX",description:"",title:"Jibo couldn't finish the update.",message:"You can try rebooting him manually,\nor tap the screen to check your Wi-Fi settings.",tapAction:"wifi",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:11,repeatTime:3e3},"OTAXa-Uh_oh_something_happened":{code:"OTAXa",description:"",title:"Jibo couldn't finish the update.",message:"You can go to support.jibo.com for help,\nor tap the screen to reboot your Jibo.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"<ssa cat='worried'/><tts config='worried'> Something doesn't feel right.</tts>",spokenPromptOnResolution:"",priority:11,repeatTime:3e3},"OTA9-Out_of_storage_OTA":{code:"OTA9",description:"Out of storage during OTA update outside of OOBE",title:"Jibo couldn't finish the update.",message:"There’s not enough space for this update.\nGo to the Jibo app to free up space.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:10,repeatTime:8e3},"OTA10-No_power_OTA":{code:"OTA10",description:"No power supply plugged in for OTA",title:"Update downloaded.",message:"Plug your Jibo into a power source\nto begin installing updates.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:9,repeatTime:2e3},"OTA10a-No_power_OTA":{code:"OTA10a",description:"No power supply plugged in for OTA",title:"Update downloaded.",message:"Plug your Jibo into a power source to begin installing updates.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:9,repeatTime:2e3},"B1-Head_overtemp":{code:"B1",description:"Motor overtemp",title:"Jibo is too hot.",message:"He needs a little time to cool down.",tapAction:"none",icon:"hot",spokenPromptOnError:"",spokenPromptOnResolution:"Was it hot in here, or was it just me. {fire emoji}",priority:3,repeatTime:4500,platformCode:"NECK_THERMISTOR_HIGH_FAULT"},"B2-Torso_overtemp":{code:"B2",description:"Motor overtemp",title:"Jibo is too hot.",message:"He needs a little time to cool down.",tapAction:"none",icon:"hot",spokenPromptOnError:"",spokenPromptOnResolution:"Was it hot in here, or was it just me. {fire emoji}",priority:3,repeatTime:4500,platformCode:"TORSO_THERMISTOR_HIGH_FAULT"},"B3-Pelvis_overtemp":{code:"B3",description:"Motor overtemp",title:"Jibo is too hot.",message:"He needs a little time to cool down.",tapAction:"none",icon:"hot",spokenPromptOnError:"",spokenPromptOnResolution:"Was it hot in here, or was it just me. {fire emoji}",priority:3,repeatTime:4500,platformCode:"PELVIS_THERMISTOR_HIGH_FAULT"},"C1-Head_undertemp":{code:"C1",description:"Motor under temp",title:"Jibo is too cold.",message:"He needs a little time to warm up.",tapAction:"none",icon:"cold",spokenPromptOnError:"",spokenPromptOnResolution:"Was it cold in here, or was it just me. {snowflake emoji}",priority:17,repeatTime:1e4,platformCode:"NECK_THERMISTOR_LOW_FAULT"},"C2-Torso_undertemp":{code:"C2",description:"Motor under temp",title:"Jibo is too cold.",message:"He needs a little time to warm up.",tapAction:"none",icon:"cold",spokenPromptOnError:"",spokenPromptOnResolution:"Was it cold in here, or was it just me. {snowflake emoji}",priority:17,repeatTime:1e4,platformCode:"TORSO_THERMISTOR_LOW_FAULT"},"C3-Pelvis_undertemp":{code:"C3",description:"Motor under temp",title:"Jibo is too cold.",message:"He needs a little time to warm up.",tapAction:"none",icon:"cold",spokenPromptOnError:"",spokenPromptOnResolution:"Was it cold in here, or was it just me. {snowflake emoji}",priority:17,repeatTime:1e4,platformCode:"PELVIS_THERMISTOR_LOW_FAULT"},"D1-Processor_overtemp":{code:"D1",description:"Processor overtemp",title:"Jibo is too hot.",message:"Tap the screen to shut him down for a bit,\nso he can cool off.",tapAction:"shutdown",icon:"hot",spokenPromptOnError:"",spokenPromptOnResolution:"Was it hot in here, or was it just me. {fire emoji}",priority:1,repeatTime:4500,platformCode:"CPU_TEMP_HIGH"},"E1-Head_encoder":{code:"E1",description:"Motor encoder tick reading failure ",title:"Something's not right.",message:"There's a problem with your Jibo's body.\nGo to support.jibo.com for help.",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:2,repeatTime:4500,platformCode:"NECK_ENCODER_FAULT"},"E2-Torso_encoder":{code:"E2",description:"Motor encoder tick reading failure ",title:"Something's not right.",message:"There's a problem with your Jibo's body.\nGo to support.jibo.com for help.",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:2,repeatTime:4500,platformCode:"TORSO_ENCODER_FAULT"},"E3-Pelvis_encoder":{code:"E3",description:"Motor encoder tick reading failure ",title:"Something's not right.",message:"There's a problem with your Jibo's body.\nGo to support.jibo.com for help.",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:2,repeatTime:4500,platformCode:"PELVIS_ENCODER_FAULT"},"F1-Head_index_flag":{code:"F1",description:"Index flag reading failure",title:"Something’s a little off.",message:"Your Jibo needs a reboot to get his body working right.\nTap the screen, and give him a minute to power back up.",tapAction:"reboot",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:4,repeatTime:4500},"F2-Torso_index_flag":{code:"F2",description:"Index flag reading failure",title:"Something’s a little off.",message:"Your Jibo needs a reboot to get his body working right.\nTap the screen, and give him a minute to power back up.",tapAction:"reboot",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:4,repeatTime:4500},"F3-Pelvis_index_flag":{code:"F3",description:"Index flag reading failure",title:"Something’s a little off.",message:"Your Jibo needs a reboot to get his body working right.\nTap the screen, and give him a minute to power back up.",tapAction:"reboot",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:4,repeatTime:4500},"F4-Index_timeout":{code:"F4",description:"Index timeout",title:"Something’s a little off.",message:"Your Jibo needs a reboot to get his body working right.\nTap the screen, and give him a minute to power back up.",tapAction:"reboot",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:4,repeatTime:4500},"H1-Head_BB_crash":{code:"H1",description:"Body board firmware crash",title:"Something’s a little off.",message:"Your Jibo needs a reboot to get his body working right.\nTap the screen, and give him a minute to power back up.",tapAction:"reboot",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:14,repeatTime:1e4,platformCode:"NECK_BOARD_TIMEOUT"},"H2-Torso_BB_crash":{code:"H2",description:"Body board firmware crash",title:"Something’s a little off.",message:"Your Jibo needs a reboot to get his body working right.\nTap the screen, and give him a minute to power back up.",tapAction:"reboot",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:14,repeatTime:1e4,platformCode:"TORSO_BOARD_TIMEOUT"},"H3-Pelvis_BB_crash":{code:"H3",description:"Body board firmware crash",title:"Something’s a little off.",message:"Your Jibo needs a reboot to get his body working right.\nTap the screen, and give him a minute to power back up.",tapAction:"reboot",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:14,repeatTime:1e4,platformCode:"PELVIS_BOARD_TIMEOUT"},"J1-Skill_crash":{code:"J1",description:"Skill crash ",title:"",message:"",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:20,repeatTime:6e3},"K1-Battery_undertemp":{code:"K1",description:"Battery under temp",title:"Jibo’s battery is too cold.",message:"It will warm up on its own, but won't be able to charge\nin the meantime. Tap the screen to clear this message.",tapAction:"dismiss",icon:"coldbattery",spokenPromptOnError:"",spokenPromptOnResolution:"That's better. All is well with my battery now. <ssa cat='happy'/>.",priority:22,repeatTime:1e4,platformCode:"BATTERY_TEMP_LOW"},"K2-Battery_overtemp":{code:"K2",description:"Battery overtemp",title:"Jibo’s battery is too hot.",message:"Remove the battery for a bit, and it should cool down.",tapAction:"none",icon:"hotbattery",spokenPromptOnError:"",spokenPromptOnResolution:"That's better. All is well with my battery now. <ssa cat='happy'/>.",priority:1,repeatTime:4500,platformCode:"BATTERY_TEMP_HIGH"},"K3-Battery_not_installed":{code:"K3",description:"Battery not installed",title:"Battery not installed",message:"Open the bottom of his base, and make sure the\nbattery is installed correctly.",tapAction:"none",icon:"missingbattery",spokenPromptOnError:"",spokenPromptOnResolution:"That's better. All is well with my battery now. <ssa cat='happy'/>.",priority:5,repeatTime:2e3,platformCode:"NO_BATTERY_LOCKOUT"},"K4-Low_battery":{code:"K4",description:"Low battery",title:"Jibo's battery level is very low.",message:"Plug him in as soon as you can.",tapAction:"dismiss",icon:"lowbattery",spokenPromptOnError:"",spokenPromptOnResolution:"That's better. All's well with the battery.",priority:12,repeatTime:2e3,platformCode:"BATTERY_LOW"},"L1-Nuance_down":{code:"L1",description:"Server down: Nuance",title:"Jibo can't talk right now.",message:"Jibo's speech server is down, so he can't speak or\nunderstand you at the moment. Try again in a little while.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"Something's off with one of my servers. Try me again in a little while.",priority:8,repeatTime:8e3},"L2-Server_down":{code:"L2",description:"Server down: Server",title:"L2- Lost connection to Jibo's server.",message:"Jibo will try to reconnect on his own.\nIn the meantime, go to support.jibo.com for help.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"Something's off with one of my servers. Try me again in a little while.",priority:8,repeatTime:8e3,platformCode:"CANNOT_CONNECT_TO_SERVER"},"L3-Weather_down":{code:"L3",description:"Server down: Weather",title:"",message:"",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:16,repeatTime:1e4},"L4-Music_down":{code:"L4",description:"Server down: Music",title:"",message:"",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:16,repeatTime:1e4},"L5-3rd_party_server_down":{code:"L5",description:"Server down: 3rd party skills",title:"",message:"",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:16,repeatTime:1e4},"L6-Wolfram_down":{code:"L6",description:"Server down: Wolfram",title:"",message:"",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:16,repeatTime:1e4},"M1-Camera_failure":{code:"M1",description:"Camera failure",title:"Jibo is having camera issues.",message:"His vision and photography skills may not work as well\nas they should. Go to support.jibo.com for help.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:19,repeatTime:1e4,platformCode:"CAMERA_FAILURE"},"N1-Service_crash_ASR":{code:"N1",description:"Service crash",title:"Jibo can't listen right now.",message:"The service Jibo uses to understand what you're saying\nis down. Give it a little time to come back online.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"Okay now where were we.",priority:21,repeatTime:1e4,platformCode:"SERVICE_CRASH_ASR"},"N2-Service_crash_TTS":{code:"N2",description:"Service crash",title:"",message:"",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:21,repeatTime:1e4,platformCode:"SERVICE_CRASH_TTS"},"N3-Service_crash_NLU":{code:"N3",description:"Service crash",title:"",message:"",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:21,repeatTime:1e4,platformCode:"SERVICE_CRASH_NLU"},"N5-Service_crash_skills_service_manager":{code:"N5",description:"Service crash",title:"",message:"",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:21,repeatTime:1e4,platformCode:"SERVICE_CRASH_SSM"},"N6-Service_crash_body_service":{code:"N6",description:"Service crash",title:"",message:"",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:21,repeatTime:1e4,platformCode:"SERVICE_CRASH_BODY"},"N7-Service_crash_LPS":{code:"N7",description:"Service crash",title:"",message:"",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:21,repeatTime:1e4,platformCode:"SERVICE_CRASH_LPS"},"N8-Service_crash_audio":{code:"N8",description:"Service crash",title:"",message:"",tapAction:"none",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:21,repeatTime:1e4,platformCode:"SERVICE_CRASH_AUDIO"},"O1-Microphone_failure":{code:"O1",description:"Microphone failure",title:"Jibo is having mic issues.",message:"His hearing may not work as well as it should.\nGo to support.jibo.com for help.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:15,repeatTime:1e4},"P1-Low_Robot_Storage":{code:"P1",description:"Low robot storage",title:"Jibo's storage is full.",message:"Go to the Jibo app to free up some storage space.",tapAction:"dismiss",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:13,repeatTime:5e3},"Q1-Lost_Wi-Fi_connection":{code:"Q1",description:"WiFi disconnected",title:"Lost Wi-Fi connection.",message:"Jibo is trying to reconnect to your router.\nTap the screen to check Wi-Fi settings,\nor go to support.jibo.com for help.",tapAction:"wifi",icon:"error",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:6,repeatTime:2e3}}}},{}],35:[function(e,t,i){"use strict";class n{constructor(e,t){this._error=null,this._timeoutId=null,this._error=e,this._timeoutId=t}get error(){return this._error}get timeoutId(){return this._timeoutId}}class s{constructor(){this._errorTimeoutMap={}}contains(e){return this._errorTimeoutMap.hasOwnProperty(e)}add(e,t){if(this._errorTimeoutMap.hasOwnProperty(e.id))return!1;{let i=setTimeout(()=>{this.remove(e.id),t(e)},e.repeatTime);return this._errorTimeoutMap[e.id]=new n(e,i),!0}}remove(e){if(Array.isArray(e)){let t=[];for(let i=0;i<e.length;++i)this._remove(e[i].id)&&t.push(e[i]);return t.length>0}return this._remove(e)}_remove(e){return!!this._errorTimeoutMap.hasOwnProperty(e)&&(clearTimeout(this._errorTimeoutMap[e].timeoutId),delete this._errorTimeoutMap[e],!0)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{}],36:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("jibo"),o=e("../kb-service/KBService"),r=e("./PriorityQueue"),a=e("../listen-service/GlobalListen"),c=e("jibo-common-types"),u=e("./JiboError"),l=e("../../utils/Log"),d=e("./DebugErrorReporter"),h=e("./ErrorServiceUtil"),f=e("./ErrorRescheduler"),p=e("./ErrorCodes.json");class m extends n.HTTPWSService{constructor(e,t){super("error-service",e,t),this._currentError=null,this._errorPriorityQueue=null,this._errorRescheduler=null,this._systemMonitoringServiceSocket=null,this._errorCodesKBRootNode=null,this._errorCodeMap={},this._platformErrorCodeMap={},this._lastErrors={},this._log=l.createLog("ssm-error-service"),this._systemMonitoringService=null,this._debugErrorReporter=null,this._mockErrorsEnabled=!1,this._errorSubscribeCallback=null,this._subscribedErrorObject=null,this._errorPriorityQueue=new r.default(u.default.Comparer,!1),this._errorRescheduler=new f.default,s.runMode===s.RunMode.SIMULATOR&&(this._mockErrorsEnabled=!0),this._log.info("Initialized")}static createInstance(e,t){return m._instance||(m._instance=new m(e,t)),m._instance}static get instance(){return m._instance}init(e){super.init(t=>{n.RegistryClient.instance.getRecords((t,i)=>{if(t)return e(t);let r="http://"+n.RegistryClient.instance.host+":"+o.default.instance.port,a=s.kb.createModel("/error-codes",r);
|
||
a.loadRoot((t,s)=>{return t?e(t):(this._errorCodesKBRootNode=s,this._errorCodesKBRootNode.data.errorCodes=p.errorCodes,Object.keys(p.errorCodes).forEach(e=>{let t=p.errorCodes[e],i=new u.default(e,t);this._errorCodeMap[i.id]=i,i.platformCode&&(this._platformErrorCodeMap[i.platformCode]=i.id)}),void this._errorCodesKBRootNode.save(t=>{if(t)return e(t);if(this._systemMonitoringService=i.find(e=>{return"system-monitoring-service"===e.name}),this._systemMonitoringService){let t="ws://"+this._systemMonitoringService.host+":"+this._systemMonitoringService.port+"/errors/codes";return this._systemMonitoringServiceSocket=new n.WSClient(t),this._systemMonitoringServiceSocket.once("open",()=>{this._systemMonitoringServiceSocket.on("message",this._receivedSystemMonitoringServiceErrors.bind(this)),this._systemMonitoringServiceSocket.on("error",this._onSocketError.bind(this)),this._log.info("connected to the system-monitoring-service/error/codes")}),this._debugErrorReporter=new d.default(this._errorCodeMap,this.addError.bind(this),this.removeError.bind(this),this._receivedMockErrors.bind(this)),this._errorPriorityQueue.onItemAdded=this._errorsAdded.bind(this),this._errorPriorityQueue.onItemRemoved=this._errorsRemoved.bind(this),e()}return e(new Error("unable to find system-monitoring-service from the registry"))}))})})})}routes(e){super.routes(e),e.post("/mockErrorCodes",(e,t)=>{this._mockErrorCodes(e,t)}),e.post("/errorCodeData",(e,t)=>{this._sendErrorCodeData(e,t)}),e.post("/getErrorCount",(e,t)=>{this._getErrorCount(e,t)}),e.post("/subscribeError",(e,t)=>{this._subscribeError(e,t)}),e.post("/processedError",(e,t)=>{this._processedError(e,t)}),e.post("/getCurrentErrorId",(e,t)=>{this._getCurrentErrorId(e,t)})}addError(e){return!(!this._errorCodeMap.hasOwnProperty(e)||this._errorRescheduler.contains(e))&&this._errorPriorityQueue.add(this._errorCodeMap[e])}removeError(e){return!!this._errorCodeMap.hasOwnProperty(e)&&(this._errorRescheduler.remove(e),this._errorPriorityQueue.delete(this._errorCodeMap[e]))}onMessage(e,t){}_getCurrentErrorId(e,t){let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{let e=null!==this._currentError?this._currentError.id:null;this.sendJson(t,{status:"OK",currentErrorId:e})})}_processedError(e,t){let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{try{let e=JSON.parse(i);if(e.hasOwnProperty("errorCode")){let i=e.errorCode,n=!1;if(this._currentError&&this._currentError.id===i){n=!0;let e=this._errorPriorityQueue.shift();this._errorRescheduler.add(e,e=>{this.addError(e.id)})}this.sendJson(t,{status:"OK",processedError:n})}else this.sendJson(t,{status:"error",message:"Client did not send errorCode"},500)}catch(e){this.sendJson(t,{status:"error",message:e},500)}})}_subscribeError(e,t){let i="";e.socket.setTimeout(0),e.on("data",e=>{i+=e}),e.on("end",()=>{try{let e=JSON.parse(i);if(e.hasOwnProperty("errorCode")){let i=e.errorCode;this._errorCodeMap.hasOwnProperty(i)?(this._subscribedErrorObject=this._errorCodeMap[i],this._errorSubscribeCallback=(()=>{let e=!this._errorPriorityQueue.contains(this._subscribedErrorObject)&&!this._errorRescheduler.contains(this._subscribedErrorObject.id),i=this._subscribedErrorObject.id,n=null!==this._currentError?this._currentError.id:null;this._errorSubscribeCallback=null,this._subscribedErrorObject=null,this.sendJson(t,{status:"OK",nextErrorId:n,subscribedErrorId:i,resolved:e})}),this._currentError&&0===u.default.Comparer(this._currentError,this._subscribedErrorObject)||this._errorSubscribeCallback()):this.sendJson(t,{status:"error",message:`Error code ${i} is not a valid error code`},500)}else this.sendJson(t,{status:"error",message:"Client did not send errorCode"},500)}catch(e){this.sendJson(t,{status:"error",message:e},500)}})}_getErrorCount(e,t){let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{this.sendJson(t,{status:"OK",errorCount:this._errorPriorityQueue.length})})}_mockErrorCodes(e,t){let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{try{let e=JSON.parse(i);s.runMode===s.RunMode.SIMULATOR?this._mockErrorsEnabled=!0:this._mockErrorsEnabled=e.enabled,this._debugErrorReporter.mockErrorRequest(e),this.sendJson(t,{status:"OK"})}catch(e){this.sendJson(t,{status:"error",message:e},500)}})}_sendErrorCodeData(e,t){let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{this._errorCodeMap?this.sendJson(t,{status:"OK",errorList:this._errorCodeMap}):this.sendJson(t,{status:"error",message:"error codes in KB not found"},500)})}_onSocketError(e){console.error("system-monitoring-service/error/codes socket error",e)}_receivedMockErrors(e){this._mockErrorsEnabled&&this._receivedPlatformErrors(e)}_receivedSystemMonitoringServiceErrors(e){this._mockErrorsEnabled||this._receivedPlatformErrors(e)}_receivedPlatformErrors(e){let t={};if(e.codes&&this._platformErrorCodeMap&&this._errorCodeMap){for(let i=0;i<e.codes.length;++i){let n=e.codes[i];if(this._platformErrorCodeMap.hasOwnProperty(n)){let s=this._platformErrorCodeMap[n];if(this._errorCodeMap.hasOwnProperty(s)){let n=this._errorCodeMap[s];n&&n.platformCode&&(t[e.codes[i]]=n)}}}let n=h.default.getNonOccurringElements(t,this._lastErrors);n=n.filter(e=>{return!this._errorRescheduler.contains(e.id)}),this._errorPriorityQueue.add(n)}if(Object.keys(this._lastErrors)){let e=h.default.getNonOccurringElements(this._lastErrors,t);this._errorPriorityQueue.delete(e),this._errorRescheduler.remove(e)}this._lastErrors=t}_errorsAdded(e){let t=this._currentError;this._currentError=this._errorPriorityQueue.peek(),!this._subscribedErrorObject||!this._errorSubscribeCallback||this._currentError&&0===u.default.Comparer(this._currentError,this._subscribedErrorObject)?this._currentError&&this._currentError!==t&&this._launchErrorSkill():this._errorSubscribeCallback()}_errorsRemoved(e){if(this._currentError=this._errorPriorityQueue.peek(),this._subscribedErrorObject&&this._errorSubscribeCallback){let t=e.find(e=>{return 0===u.default.Comparer(e,this._subscribedErrorObject)});t&&this._errorSubscribeCallback()}}_launchErrorSkill(){let e=new c.ParseResults("",{skill:"@be/settings",errorId:this._currentError.id},{},0),t=new c.Utterance({utterance:""}),i=new c.ListenResults(t,e);a.default.getInstance().events.listen.skillRelaunch.emit(i)}}m.Types={JiboError:u.default,DebugErrorReporter:d.default,PriorityQueue:r.default,ErrorServiceUtil:h.default,ErrorRescheduler:f.default},m._instance=null,Object.defineProperty(i,"__esModule",{value:!0}),i.default=m},{"../../utils/Log":88,"../kb-service/KBService":42,"../listen-service/GlobalListen":50,"./DebugErrorReporter":33,"./ErrorCodes.json":34,"./ErrorRescheduler":35,"./ErrorServiceUtil":37,"./JiboError":38,"./PriorityQueue":39,jibo:void 0,"jibo-common-types":void 0,"jibo-service-framework":void 0}],37:[function(e,t,i){"use strict";class n{static getNonOccurringElements(e,t){let i=[],n=Object.keys(e);for(let s=0;s<n.length;++s){let o=n[s];t.hasOwnProperty(o)||i.push(e[o])}return i}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{}],38:[function(e,t,i){"use strict";class n{constructor(e,t){this._id=null,this._priority=0,this._platformCode=null,this._repeatTime=0,this._data={description:"",message:"",spokenPromptOnError:"",spokenPromptOnResolution:"",priority:0,repeatTime:-1,platformCode:null},this._id=e,this._data=t,this._data.hasOwnProperty("priority")&&(this._priority=this._data.priority),this._data.hasOwnProperty("platformCode")&&(this._platformCode=this._data.platformCode),this._data.hasOwnProperty("repeatTime")&&(this._repeatTime=this._data.repeatTime)}static Comparer(e,t){return e.priority>t.priority?1:e.priority<t.priority?-1:e.id>t.id?1:e.id<t.id?-1:0}get id(){return this._id}get data(){return this._data}get priority(){return this._priority}get platformCode(){return this._platformCode}get repeatTime(){return this._repeatTime}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{}],39:[function(e,t,i){"use strict";class n{constructor(e,t=true){this._queue=[],this._compareMethod=null,this._allowDuplicates=!0,this._onItemAddedCallback=null,this._onItemRemovedCallback=null,this._compareMethod=e,e||(this._compareMethod=((e,t)=>{return e>t?1:e<t?-1:0})),this._allowDuplicates=t}get onItemAdded(){return this._onItemAddedCallback}set onItemAdded(e){this._onItemAddedCallback=e}get onItemRemoved(){return this._onItemRemovedCallback}set onItemRemoved(e){this._onItemRemovedCallback=e}add(e){if(Array.isArray(e)){let t=[];for(let i=0;i<e.length;++i)this._addElement(e[i])&&t.push(e[i]);return t.length>0&&this._onItemAddedCallback&&this._onItemAddedCallback(t),t.length>0}{let t=this._addElement(e);return t&&this._onItemAddedCallback&&this._onItemAddedCallback([e]),t}}delete(e){if(Array.isArray(e)){let t=[];for(let i=0;i<e.length;++i)this._deleteElement(e[i])&&t.push(e[i]);return t.length>0&&this._onItemRemovedCallback&&this._onItemRemovedCallback(t),t.length>0}{let t=this._deleteElement(e);return t&&this._onItemRemovedCallback&&this._onItemRemovedCallback([e]),t}}peek(){return this._queue.length>0?this._queue[0]:null}shift(){let e=this._queue.length>0?this._queue.shift():null;return e&&this._onItemRemovedCallback&&this._onItemRemovedCallback([e]),e}contains(e){return this._tryGetIndex(e)!==-1}get length(){return this._queue.length}clear(){this._queue=[]}_addElement(e){if(this.contains(e)&&!this._allowDuplicates)return!1;let t=0,i=this._queue.length;for(;t!==i;){let n=Math.floor((i-t)/2)+t,s=this._compareMethod(e,this._queue[n]);s<0?i=n:t=s>0?n+1:i=n}let n=t;return this._queue.splice(n,0,e),!0}_deleteElement(e){let t=this._tryGetIndex(e);return t!==-1&&(this._queue.splice(t,1),!0)}_tryGetIndex(e){let t=0,i=this._queue.length;for(;t!==i;){let n=Math.floor((i-t)/2)+t,s=this._compareMethod(e,this._queue[n]);s<0?i=n:t=s>0?n+1:i=n}let n=t;return n<this._queue.length&&0===this._compareMethod(e,this._queue[n])?n:-1}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{}],40:[function(e,t,i){"use strict";const n=e("request"),s=e("jibo-service-framework"),o=e("../../utils/Log"),r=o.createLog("ssm-loop-manager"),a="loop",c=3,u=1e3;class l{constructor(e){this.taskId=0,this.socketState=0;let t=e;for(t=t.replace(/[^A-Fa-f0-9]/g,"");t.length<32&&t.length>1;)t+=t;t=t.substr(0,32),this.nuanceUserId=t}init(e){s.RegistryClient.instance.getRecords((t,i)=>{t?e(t):i?(i.forEach(e=>{"asr"===e.name&&(this.asrSocketUrl=`ws://${e.host}:${e.port}/port`,this.asrUploadVocabUrl=`http://${e.host}:${e.port}/upload_interface`)}),this._setupASRSocket(e)):e(new Error("no records from registry"))})}update(e,t){let i=this._buildWordUpload(e);this.wordUpload?(this.pendingWordUpload=i,setImmediate(t)):this._sendWords(i,t)}_buildWordUpload(e){let t=[];e.forEach(e=>{if(e.data.firstName||e.data.lastName||e.data.nickName){let i=(e.data.firstName||"").toLowerCase(),n=(e.data.lastName||"").toLowerCase(),s=(i+" "+n).trim(),o=(e.data.nickName||"").toLowerCase(),r={first_name:i,last_name:n,full_name:s,nick_name:o};t.push(r)}});let i={task_id:this.nuanceUserId+"."+this.taskId++,command:"add",grammar:a,mode:"full",new_checksum:"1",old_checksum:"1",userid_list:[this.nuanceUserId],loop_list:t};return i}_sendWords(e,t){this.wordUpload=e,this._setupASRSocket(()=>{this._postWordsToASR(this.wordUpload,e=>{e?t(e):this._waitForOurASRMessage(()=>{if(this.lastWordUpload=this.wordUpload,this.wordUpload=null,this.pendingWordUpload){r.info("sending pending ASR word upload");let e=this.pendingWordUpload;this.pendingWordUpload=null,this._sendWords(e,t)}else t()})})})}_waitForOurASRMessage(e){this.asrSocket.once("message",t=>{if(t.grammar&&t.grammar===a)if("success"===t.success)r.info("succeeded grammar update task message from ASR:",t),e(null,t);else if(r.warn("failed grammar update task message from ASR:",t),this.uploadAttempts=(this.uploadAttempts||0)+1,this.uploadAttempts<c)setTimeout(()=>{r.warn("trying again"),this._sendWords(this.wordUpload,e)},u);else{this.uploadAttempts=0;let t=new Error("giving up on ASR word upload attempts");r.error(t),e(t)}else this._waitForOurASRMessage(e)})}_setupASRSocket(e){1===this.socketState?setImmediate(e):0===this.socketState?(this.asrSocket=new s.WSClient(this.asrSocketUrl),this.asrSocket.on("reopen",()=>{r.warn("reconnected to ASR service"),this.socketState=1,this._resendWordUpload()}),this.asrSocket.on("error",e=>{r.error("error on ASR service socket:",e),this.lastWordUpload=this.wordUpload||this.lastWordUpload,this.wordUpload=null,this.socketState=2}),this.asrSocket.on("close",()=>{r.warn("ASR service closed"),this.lastWordUpload=this.wordUpload||this.lastWordUpload,this.wordUpload=null,this.socketState=2}),this.asrSocket.once("open",()=>{r.info("connected to ASR service"),this.socketState=1,e()})):this.asrSocket.once("reopen",e)}_postWordsToASR(e,t){r.info("POSTing word upload to ASR",e),n.post(this.asrUploadVocabUrl,{json:e},(e,t,i)=>{e=this._checkStatusCode(e,t,i),e?r.error("ASR word upload task POSTing failed!",e):r.info("ASR word upload task finished POSTing")}),t()}_resendWordUpload(){this.lastWordUpload&&(r.info("resending last word upload..."),this._sendWords(this.lastWordUpload,()=>{r.info("done resending last word upload")}))}_checkStatusCode(e,t,i=null){if(!e&&(t.statusCode<200||t.statusCode>299)){let n="HTTP Error Code "+t.statusCode;i&&(n+=i),e=new Error(n)}return e}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=l},{"../../utils/Log":88,"jibo-service-framework":void 0,request:void 0}],41:[function(e,t,i){"use strict";const n=e("assert"),s=e("jibo");var o=s.kb.Model;const r=e("../simulator-server-client"),a=e("../../utils/Log"),c=a.createLog("ssm-holiday-manager"),u=21600,l=3e3,d="/jibo/holidays",h="/jibo/loop";class f{constructor(e,t=true){this.httpUrl=e,this.enableCloud=t}init(e){let t=s.kb.createModel(d,this.httpUrl);this.model=t.begin(),this._preloadHolidayModel(()=>{c.info("local cached holidays loaded, count: ",this._holidaysSize()),this.enableCloud?(c.info("starting holiday cloud syncing..."),this._syncWithCloud(()=>{c.info("local holidays count after syncing: ",this._holidaysSize()),e(),this._periodicSyncWithCloud()})):e()})}_preloadHolidayModel(e){this.model.loadRoot((t,i)=>{c.iferr(t,"model.loadRoot"),this.rootNode=i,this.model.loadLayers(i,"holiday",t=>{c.iferr(t,"loadLayers holiday"),e()})})}_fetchHolidays(){return this.model.fetch(this.rootNode.getEdges("holiday"))}_holidaysSize(){let e=this._fetchHolidays();return e.length}_periodicSyncWithCloud(){c.info("scheduling holiday sync with cloud every",u,"seconds.");let e=()=>{c.info("syncing holidays with cloud..."),this._syncWithCloud(t=>{setTimeout(e,216e5)})};setTimeout(e,216e5)}_syncWithCloud(e){this._setupClients(),this._startTimer(),this._lookupLoopId((t,i)=>{t?e(t):this.personClient.listHolidays({loopId:i},(t,i)=>{this._endTimer("JSC server call Person#listHolidays()"),c.iferr(t,"JSC server call Person#listHolidays()"),t?e(t):this._applyHolidayChanges(i,(t,i)=>{c.iferr(t,"_applyHolidayChanges"),e(t,i)})})})}_setupClients(){this.personClient||(this.personClient=new r.JSC.Person)}_lookupLoopId(e){let t=new o(h,this.httpUrl);t.loadRoot((t,i)=>{c.iferr(t,"loop.loadRoot"),t?e(t):e(null,i.data.id)})}_applyHolidayChanges(e,t){let i=this.model,n=this.rootNode,o=[],r=[],a=[],u=this._fetchHolidays();e.forEach(e=>{let t=!1;for(let i=0;i<u.length;i++){let n=u[i];if(e.id===n._id){r.push(e),t=!0;break}}t||o.push(e)}),u.forEach(t=>{let i=!1;for(let n=0;n<e.length;n++){let s=e[n];if(s.id===t._id){i=!0;break}}i||a.push(t)});let l=!1,d=o.map(e=>{return e.id});i.load(d,e=>{c.iferr(e,"model.load"),o.forEach(e=>{let t,i=this.model.fetch(e._id,!0);i?t=i:(t=new s.kb.Node("holiday"),t._id=e.id,this.model.pool[0].adoptNodeAsOurOwn(t),this.model.cache.add(t)),this._applyCloudHolidayToLocalHoliday(e,t),n.addEdges(t,"holiday"),l=!0}),r.forEach(e=>{let t=this.model.fetch(e.id),i=this._applyCloudHolidayToLocalHoliday(e,t);i&&(l=!0)}),a.forEach(e=>{n.removeEdges(e,"holiday"),l=!0}),l?(c.info("holidays changed. saving..."),this.model.saveLayers(n,"holiday",e=>{c.iferr(e,"model.saveLayers"),c.info("finished saving holidays"),t(null,l)})):t()})}_applyCloudHolidayToLocalHoliday(e,t){let i=this._syncObjectStrict(e,t.data);return i}_syncObjectStrict(e,t){let i=!1;return Object.keys(e).forEach(n=>{e.hasOwnProperty(n)?this._deepEqual(e[n],t[n])||(t[n]=e[n],i=!0):t.hasOwnProperty(n)&&(delete t[n],i=!0)}),i}_deepEqual(e,t){try{n.deepEqual(e,t)}catch(e){if("AssertionError"!==e.name)throw e;return!1}return!0}_startTimer(){this.timer=performance.now()}_endTimer(e){if(this.timer){let t=Math.round(performance.now()-this.timer);t>l&&c.warn(e,"was slow ("+t+"ms)")}}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=f},{"../../utils/Log":88,"../simulator-server-client":71,assert:void 0,jibo:void 0}],42:[function(e,t,i){"use strict";const n=e("fs"),s=e("path"),o=e("rimraf"),r=e("querystring"),a=e("jibo"),c=e("jibo-service-framework"),u=e("./LoopManager"),l=e("./HolidayManager"),d=e("./MediaListManager"),h=e("../../utils/Log");let f=h.createLog("ssm-kb-service");const p=!0;class m{}i.SingletonEnforcer=m;class g extends c.HTTPService{static createInstance(e,t){return new g(new m,e,t)}static get instance(){return g._instance}constructor(e,t,i){if(super("kb",t,i),g._instance)throw new Error("KBService is a singleton");g._instance=this,this.kbdbs={},this.queue={},f.info("Initialized")}init(e){a.systemManager.getMode(t=>{"oobe"===t?(f.info('KB service startup skipped in "oobe" mode'),e()):super.init(t=>{if(t)f.error("error initing HTTPService object",t),e(t);else{let t="http://localhost:"+this.port;this.loopManager=new u.default(t,p),this.loopManager.init(i=>{this.holidayManager=new l.default(t,p),this.holidayManager.init(i=>{this.mediaListManager=new d.default(t,p),this.mediaListManager.init(t=>{e(t)})})})}})})}enableDebug(){this.app.use((e,t,i)=>{let n="null";e.params&&e.params.kbdb&&e.params.kbdb.name&&(n=e.params.kbdb.name),f.debug(`service: ${this.name}, kbdb: ${n}, method: ${e.method}, url: ${e.url}`),i()})}attachKBDB(e,t,i){if(e.params.kbname){let n=r.unescape(e.params.kbname);this.kbdbs[n]?(e.params.kbdb=this.kbdbs[n],i()):a.kb.databaseManager.exists(n,(s,o)=>{if(s)s||(s=new Error("KB slice "+n+" does not exist, create it first")),t.statusCode=500,t.end(s.toString());else if(this.queue[n])f.debug("queueing up pending request for kb slice",n),this.queue[n].push({req:e,callback:i});else{this.queue[n]=[{req:e,callback:i}];let t=new a.kb.KnowledgeDatabase(n);f.debug("initing kbdb["+n+"]"),t.init(e=>{f.iferr(e),e||(this.kbdbs[n]=t),this._processQueue(e,n),delete this.queue[n]})}})}}attachLoopKBDB(e,t,i){e.params.kbname="/jibo/loop",this.attachKBDB(e,t,i)}attachMediaListSlice(e,t,i){e.params.kbname="/jibo/media-list",this.attachKBDB(e,t,i)}routes(e){super.routes(e),e.get("/v1/kb/:kbname/node/load/:id",(e,t)=>{this.attachKBDB(e,t,()=>{this.load(e,t)})}),e.get("/v1/kb/:kbname/node/loadRoot",(e,t)=>{this.attachKBDB(e,t,()=>{this.loadRoot(e,t)})}),e.post("/v1/kb/:kbname/node/save",(e,t)=>{this.attachKBDB(e,t,()=>{this.save(e,t)})}),e.delete("/v1/kb/:kbname/node/remove/:id",(e,t)=>{this.attachKBDB(e,t,()=>{this.remove(e,t)})}),e.get("/v1/kb/:kbname/asset/:filename",(e,t)=>{this.attachKBDB(e,t,()=>{this.getAsset(e,t)})}),e.post("/v1/kb/:kbname/asset/:filename",(e,t)=>{this.attachKBDB(e,t,()=>{this.addAsset(e,t)})}),e.delete("/v1/kb/:kbname/asset/:filename",(e,t)=>{this.attachKBDB(e,t,()=>{this.removeAsset(e,t)})}),e.post("/v1/kb/:kbname/create",(e,t)=>{this.createSlice(e,t)}),e.get("/v1/kb/:kbname/exists",(e,t)=>{this.existsSlice(e,t)}),e.delete("/v1/kb/:kbname/remove/yesiamsure",(e,t)=>{this.removeSlice(e,t)}),e.delete("/v1/removeall/yesiamsure",(e,t)=>{this.removeKbEverything(e,t)}),e.post("/v1/loop/updatePhoneticName",(e,t)=>{this.attachLoopKBDB(e,t,()=>{this.loopUpdatePhoneticName(e,t)})}),e.post("/v1/loop/enrollment",(e,t)=>{this.attachLoopKBDB(e,t,()=>{this.loopSetEnrollment(e,t)})}),e.post("/v1/media/storePhoto",(e,t)=>{this.mediaStorePhoto(e,t)}),e.post("/v1/media/downloadThumbnails",(e,t)=>{this.mediaDownloadThumbnails(e,t)}),e.post("/v1/media/downloadPhoto",(e,t)=>{this.mediaDownloadPhoto(e,t)}),e.post("/v1/media/deletePhoto",(e,t)=>{this.mediaDeletePhoto(e,t)})}load(e,t){let i=e.params.kbdb,n=e.params.id;i.load(n,(e,i)=>{f.iferr(e,"kb.load"),i&&i._id&&f.debug("loaded node",i._id),this.sendJson(t,i)})}loadRoot(e,t){let i=e.params.kbdb;i.loadRoot((e,i)=>{f.iferr(e,"kb.load"),i&&i._id&&f.debug("loaded root node",i._id),this.sendJson(t,i)})}save(e,t){let i=e.params.kbdb;e.body&&e.body._id&&f.debug("save",e.body._id);let n=new a.kb.Node(null,null,e.body);i.adoptNodeAsOurOwn(n),n.save(e=>{f.iferr(e,"node.save"),this.finish(t,e)})}remove(e,t){let i=e.params.kbdb,n=e.params.id;f.debug("remove",n),i.remove(n,e=>{f.iferr(e,"node.remove"),this.finish(t,e)})}createAssetInstance(e){let t=e.params.kbdb,i=e.params.filename,n=t.getDirectory(),s=new a.kb.Asset(i);return s.setRootDir(n),s}getAsset(e,t){let i=this.createAssetInstance(e),n=i.fullFilenameOrURL();this.sendFile(t,n)}addAsset(e,t){let i=this.createAssetInstance(e);i.save(e,e=>{this.finish(t,e)})}removeAsset(e,t){let i=this.createAssetInstance(e);i.remove(e=>{this.finish(t,e)})}createSlice(e,t){let i=r.unescape(e.params.kbname);a.kb.databaseManager.create(i,(e,i)=>{if(e)throw e;this.sendJson(t,{created:i})})}existsSlice(e,t){let i=r.unescape(e.params.kbname);a.kb.databaseManager.exists(i,(e,i)=>{if(e)throw e;this.sendJson(t,{exists:i})})}removeSlice(e,t){let i=r.unescape(e.params.kbname);if("/jibo/loop"===i&&this.loopManager)this.loopManager.shutdown(i=>{if(f.iferr(i),i)throw i;this.loopManager=null,this.removeSlice(e,t)});else{Object.keys(this.kbdbs).forEach(e=>{(i===e||e.startsWith(i+"/"))&&(delete this.kbdbs[i],delete a.kb.databaseManager.release(i))});let e=a.kb.KnowledgeDatabase.getKbDirectory(i);if(e=s.normalize(e),e.length<8)throw new Error("not comfortable with kb slice directory name "+e);f.info("removing kb slice",e),o(e,{disableGlob:!0},e=>{this.finish(t,e)})}}removeKbEverything(e,t){this.loopManager.shutdown(e=>{if(f.iferr(e),e)throw e;this.loopManager=null,this.kbdbs=null;let i=a.kb.KnowledgeDatabase.getRootDirectory();if(i=s.normalize(i),i.length<8)throw new Error("not comfortable with kb root directory name "+i);f.warn("removing the entire kb at",i),o(i,{disableGlob:!0},e=>{if(e)throw e;n.mkdir(i,e=>{this.finish(t,e)})})})}loopUpdatePhoneticName(e,t){e.body&&e.body._id&&f.debug("loop updatePhoneticName",e.body._id);let i=e.body,n=["loopId","memberId","phoneticName"];Object.keys(i).forEach(e=>{if(n.indexOf(e)<0)throw new Error("unacceptable field in account update: "+e)}),this.loopManager.loopUpdatePhoneticName(i,e=>{this.finish(t,e)})}loopSetEnrollment(e,t){e.body&&e.body._id&&f.debug("loop set enrollment",e.body._id);let i=e.body,n=["loopId","memberId","face","voice"];Object.keys(i).forEach(e=>{if(n.indexOf(e)<0)throw new Error("unacceptable field in loop set enrollment:"+e)}),this.loopManager.loopSetEnrollment(i,e=>{this.finish(t,e)})}mediaStorePhoto(e,t){e.body&&e.body.id&&f.debug("media store photo",e.body.id),this.mediaListManager.storePhoto(e=>{this.finish(t,e)})}mediaDownloadThumbnails(e,t){e.body&&e.body.ids&&f.debug("media download thumbnails",e.body.ids);let i=e.body;this.mediaListManager.downloadThumbnails(i.ids,i.type,e=>{this.finish(t,e)})}mediaDownloadPhoto(e,t){e.body&&e.body.id&&f.debug("media download photo",e.body.id);let i=e.body;this.mediaListManager.downloadPhoto(i.id,i.type,e=>{this.finish(t,e)})}mediaDeletePhoto(e,t){e.body&&e.body.id&&f.debug("media delete photo",e.body.id);let i=e.body;this.mediaListManager.deletePhoto(i.id,e=>{this.finish(t,e)})}_processQueue(e,t){let i=this.queue[t],n=!0;for(;i.length>0;){let s=i.shift();s.req.params.kbdb=this.kbdbs[t],n?(s.callback(e),n=!1):s.callback()}}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=g},{"../../utils/Log":88,"./HolidayManager":41,"./LoopManager":43,"./MediaListManager":44,fs:void 0,jibo:void 0,"jibo-service-framework":void 0,path:void 0,querystring:void 0,rimraf:void 0}],43:[function(e,t,i){"use strict";const n=e("path"),s=e("url"),o=e("request"),r=e("async"),a=e("jibo"),c=e("../simulator-server-client");var u=a.kb.Asset;const l=e("./NLULoopInformer"),d=e("./ASRLoopInformer"),h=e("./SyncManager"),f=e("../../utils/Log"),p=f.createLog("ssm-loop-manager"),m="/jibo/loop";var g;!function(e){e[e.male="male"]="male",e[e.female="female"]="female",e[e.other="other"]="other"}(g=i.Gender||(i.Gender={}));class v extends h.default{constructor(e,t=true){super(e,"loop",15e3,t)}init(e){super.init(t=>{p.iferr(t,"super.init"),t?e(t):this._initCredentials(()=>{this._setupLoopInformers(()=>{let t=a.kb.createModel(m,this.httpUrl);this.model=t.begin(),this._preloadLoopModel(()=>{p.info("local cached loop loaded, members: ",this._loopSize()),this._updateLoopInformers(()=>{this.enableCloud?(p.info("starting loop cloud syncing..."),this._syncWithCloud(()=>{let t=this._loopSize();p.info("local loop members: ",t),0===t&&p.error("This robot does not have a loop!"),this._updateLoopInformers(t=>{p.iferr(t,"error updating loop informers"),e()}),this._startSyncTimer()})):(0===this._loopSize()&&p.error("This robot does not have a loop!"),e())})})})})})}shutdown(e){this._notDuringSyncing(t=>{delete this.model,this.isShutdown=!0,e(null)})}accountUpdate(e,t){let i=new c.JSC.Account;this._notDuringSyncing(n=>{i.update(e,(i,s)=>{if(p.iferr(i,"JSC.Acount.update"),i)n(),t(i);else{let s=this.model.fetch(e._id);s?(Object.keys(e).forEach(t=>{"_id"!==t&&(s.data[t]=e[t])}),s.save(e=>{n(),t(e)})):(n(),t(i))}})})}loopUpdatePhoneticName(e,t){let i=new c.JSC.Loop;this._notDuringSyncing(n=>{i.updatePhoneticName(e,(i,s)=>{if(p.iferr(i,"JSC.Loop.updatePhoneticName"),i)n(),t(i);else{let s=this.model.fetch(e.memberId);s?(s.data.phoneticName=e.phoneticName,s.save(e=>{n(),t(e)})):(n(),t(i))}})})}loopSetEnrollment(e,t){let i=new c.JSC.Loop;this._notDuringSyncing(n=>{i.setEnrollment(e,(i,s)=>{if(p.iferr(i,"JSC.Loop.setEnrollment"),i)n(),t(i);else{let s=this.model.fetch(e.memberId);s?(["face","voice"].forEach(t=>{t in e&&(s.data.enrolled=s.data.enrolled||{},s.data.enrolled[t]=e[t])}),s.save(e=>{n(),t(e)})):(n(),t(i))}})})}_syncWithCloud(e){this._setupClients(),this._setupOurAccountId(t=>{t&&this._errorOnce("_setupOurAccountId "+t.toString()),t?e(t):(this._startTimer(),this.loopClient.list({},(t,i)=>{if(this._endTimer("JSC server call Loop#list()"),p.iferr(t,"JSC server call Loop#list()"),t)e(t);else{let{loop,loopEntries,loopAccountIds}=this._findLoopEntries(this.ourAccountId,this.ourRobotName,i);loopEntries?(this._startTimer(),this.accountClient.get({ids:loopAccountIds},(t,i)=>{if(this._endTimer("JSC server call Account#get([ids])"),p.iferr(t,"JSC server call Account#get([ids])"),t)e(t);else{let t={};i.forEach(e=>{t[e._id]=e}),this._applyLoopChanges(loop,loopEntries,t,(t,i)=>{p.iferr(t,"_applyLoopChanges"),e(t,i)})}})):e(new Error("no loop"))}}))})}_updated(e){this._updateLoopInformers(e)}_preloadLoopModel(e){this.model.loadRoot((t,i)=>{p.iferr(t,"model.loadRoot"),this.rootNode=i,this.model.loadLayers(i,["owner","user"],t=>{p.iferr(t,"loadLayers owner, user"),e()})})}_fetchLoop(){return this.model.fetch(this.rootNode.getEdges("user"))}_loopSize(){let e=this._fetchLoop();return e.length}_setupLoopInformers(e){if(this.loopInformers)setImmediate(e);else{this.loopInformers=[];let t=new l.default;this.loopInformers.push(t),t.init(()=>{this.enableCloud&&this.onRobot?(this._setupClients(),this._setupOurAccountId(t=>{if(p.iferr(t,"_setupOurAccountId"),this.ourAccountId){let t=new d.default(this.ourAccountId);this.loopInformers.push(t),t.init(()=>{e()})}else setImmediate(e)})):setImmediate(e)})}}_updateLoopInformers(e){let t=this._fetchLoop();if(this.loopInformers){let i=[];this.loopInformers.forEach(e=>{i.push(i=>{e.update(t,i)})}),r.series(i,e)}else setImmediate(e)}_findLoopEntries(e,t,i){let n,s,o;return i&&0!==i.length?i.forEach(i=>{if(i.robot===e||i.owner===e&&i.robotFriendlyId===t)if(i.members){n&&this._errorOnce("JSC server call Loop#list() multiple loops for account "+e),n=i;for(let t=n.members.length-1;t>=0;t--)n.members[t].memberId||n.members.splice(t,1);for(let t=n.members.length-1;t>=0;t--)n.members[t].status&&"accepted"===n.members[t].status||n.members.splice(t,1);s=n.members,o=s.map(e=>{return e.memberId}),o.indexOf(n.owner)<0&&this._errorOnce("JSC server call Loop#list() owner not in loop for robot "+e),o.indexOf(n.robot)<0&&this._errorOnce("JSC server call Loop#list() robot "+e+" not in loop")}else this._errorOnce("JSC server call Loop#list() loop has no members")}):this._errorOnce("JSC server call Loop#list() account "+e+" does not have a loop"),n||this._errorOnce("JSC server call Loop#list() no loop found for account "+e),{loop:n,loopEntries:s,loopAccountIds:o}}_setupClients(){this.loopClient||(this.loopClient=new c.JSC.Loop),this.accountClient||(this.accountClient=new c.JSC.Account)}_setupOurAccountId(e){this.ourAccountId?setImmediate(e):(this._startTimer(),this.accountClient.get({},(t,i)=>{this._endTimer("JSC server call Account#get()"),t&&this._errorOnce("JSC server call Account#get() "+t.toString()),t?e(t):i&&i.length?1!==i.length?(this._errorOnce("JSC server call Account#get() returned unexpected multiple results"),e(new Error("could not lookup our account"))):(this.ourAccountId=i[0]._id,e()):(this._errorOnce("JSC server call Account#get() did not return our account details"),e(new Error("could not lookup our account")))}))}_applyLoopChanges(e,t,i,n){let s=this.model,o=this.rootNode,r=[],c=[],u=[],l=s.fetch(o.getEdges("user"));t.forEach(e=>{let t=!1;for(let i=0;i<l.length;i++){let n=l[i];if(e.memberId===n._id){c.push(e),t=!0;break}}t||r.push(e)}),l.forEach(e=>{let i=!1;for(let n=0;n<t.length;n++){let s=t[n];if(s.memberId===e._id){i=!0;break}}i||u.push(e)});let d=!1;d=this._applyCloudLoopToLocalLoopRootNode(e,o),o.clearEdges(["owner","robot"]),o.addEdges(e.owner,"owner"),o.addEdges(e.robot,"robot");let h=r.map(e=>{return e.memberId});s.load(h,e=>{p.iferr(e,"model.load"),r.forEach(e=>{let t,n=i[e.memberId],s=this.model.fetch(n._id,!0);s?t=s:(t=new a.kb.Node("user"),t._id=n._id,this.model.pool[0].adoptNodeAsOurOwn(t),this.model.cache.add(t)),this._applyCloudLoopMemberAndAccountToLocalLoopNode(e,n,t),o.addEdges(t,"user"),d=!0}),c.forEach(e=>{let t=this.model.fetch(e.memberId),n=i[e.memberId],s=this._applyCloudLoopMemberAndAccountToLocalLoopNode(e,n,t);s&&(d=!0)}),u.forEach(e=>{o.removeEdges(e,"user"),d=!0}),this._syncLoopPhotos((e,t)=>{t&&(d=!0),d?(p.info("loop changed. saving..."),this.model.saveLayers(o,"user",e=>{p.iferr(e,"model.saveLayers"),p.info("finished saving loop"),n(null,d)})):n()})})}_applyCloudLoopToLocalLoopRootNode(e,t){let i=["id","name","owner","robot","robotFriendlyId","created","updated"],n=this._syncObject(e,t.data,i);return n}_applyCloudLoopMemberAndAccountToLocalLoopNode(e,t,i){let n=["loopId","memberId","account","enrolled","status","type","agreementId","nickname","phoneticName"],s=["email","firstName","lastName","gender","birthday","isActive","photoUrl","facebookConnected","termsAccepted"],o={nickname:"nickName"},r=this._syncObject(e,i.data,n,o),a=this._syncObject(t,i.data,s);return r||a}_syncLoopPhotos(e){let t=!1;const i=this._fetchLoop();let a=[];i.forEach(e=>{const i=e.data.photoUrl,r=e.getAssets("photo")[0];if(i){const c=s.parse(i),l=n.parse(c.pathname),d=l.name,h=l.ext;let f=`${d}.photo${h}`;if(!r||r.filename()!==f){const n=e.getAssets("photo");n.forEach(t=>{a.push(i=>{e.removeAsset(t,i)})}),a.push(n=>{const s=new u(f);s.setRootDir(e.getKb().getDirectory());const r={headers:{"Content-Type":"application/octet-stream"},encoding:null};s.save(o.get(i,r),i=>{p.iferr(i,"newAsset.save"),i||(e.addAssets(s),t=!0),n()})})}}else if(r){const i=e.getAssets("photo");i.forEach(i=>{a.push(n=>{e.removeAsset(i,n),t=!0})})}}),r.series(a,()=>{e(null,t)})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=v},{"../../utils/Log":88,"../simulator-server-client":71,"./ASRLoopInformer":40,"./NLULoopInformer":45,"./SyncManager":46,async:void 0,jibo:void 0,path:void 0,request:void 0,url:void 0}],44:[function(e,t,i){"use strict";const n=e("request"),s=e("jibo");
|
||
var o=s.kb.Model;const r=e("../simulator-server-client"),a=e("./SyncManager"),c=e("../../utils/Log"),u=c.createLog("ssm-media-list-manager"),l="/jibo/media",d="/jibo/loop";class h extends a.default{constructor(e,t=true){super(e,"media list",6e4,t)}init(e){super.init(t=>{if(u.iferr(t,"super.init()"),t)e(t);else{let t=s.kb.createModel(l,this.httpUrl);this.model=t.begin(),this._preloadMediaModel(()=>{u.info("local cached media list loaded, count: ",this._mediaSize()),this.enableCloud?(u.info("starting media list cloud syncing..."),this._syncWithCloud(()=>{u.info("local media list count after syncing: ",this._mediaSize()),this._getServiceRecord("media",(t,i)=>{this.mediaUrl=`http://${i.host}:${i.port}/media`,this._getServiceRecord("media-manager",(t,i)=>{this.mediaManagerUrl=`http://${i.host}:${i.port}/media-manager`,e(),this._startSyncTimer()})})})):e()})}})}storePhoto(e){this._notDuringSyncing(t=>{let i=performance.now();this._syncWithCloud(n=>{let s=Math.round(performance.now()-i);u.warn("storePhoto _syncWithCloud ("+this._mediaSize()+" nodes) took "+s+"ms"),u.iferr(n,"_syncWithCloud"),t(),e(n)})})}deletePhoto(e,t){this.storePhoto(t)}downloadThumbnails(e,t,i){let s=this.mediaManagerUrl+"/download";e.forEach(e=>{let o={contentID:e,immediate:!1,type:t};n.post(s,{json:o},(e,t,n)=>{e=this._checkStatusCode(e,t),u.iferr(e,s),i(e)})})}downloadPhoto(e,t,i){let s=this.mediaManagerUrl+"/download",o={contentID:e,immediate:!0,type:t};n.post(s,{json:o},(e,t,n)=>{u.iferr(e,s),i(e)})}_syncWithCloud(e){this._setupClients(),this._startTimer(),this._lookupLoopId((t,i)=>{t?e(t):this.mediaClient.list({loopIds:[i]},(t,i)=>{this._endTimer("JSC server call Media#list()"),u.iferr(t,"JSC server call Media#list()"),t?e(t):this._applyMediaChanges(i,(t,i)=>{u.iferr(t,"_applyMediaChanges"),e(t,i)})})})}_updated(e){process.nextTick(e)}_preloadMediaModel(e){this.model.loadRoot((t,i)=>{u.iferr(t,"model.loadRoot"),this.rootNode=i,this.model.loadLayers(i,"media",t=>{u.iferr(t,"loadLayers media"),e()})})}_fetchMedia(){return this.model.fetch(this.rootNode.getEdges("media"))}_mediaSize(){let e=this._fetchMedia();return e.length}_setupClients(){this.mediaClient||(this.mediaClient=new r.JSC.Media)}_lookupLoopId(e){let t=new o(d,this.httpUrl);t.loadRoot((t,i)=>{u.iferr(t,"loop.loadRoot"),t?e(t):e(null,i.data.id)})}_applyMediaChanges(e,t){let i=this.model,n=this.rootNode,s=[],o=[],r=[],a=this._fetchMedia();e.forEach(e=>{let t=!1;for(let i=0;i<a.length;i++){let n=a[i];if(e.path===n._id){o.push(e),t=!0;break}}t||s.push(e)}),a.forEach(t=>{let i=!1;for(let n=0;n<e.length;n++){let s=e[n];if(s.path===t._id){i=!0;break}}i||r.push(t)});let c=!1,l=s.map(e=>{return e.path});i.load(l,e=>{u.iferr(e,"model.load"),s.forEach(e=>{let t,i=this.model.fetch(e.path,!0);t=i?i:this._createNodeWithId(e.path,this.model,"media"),this._applyCloudMediaToLocalMedia(e,t),n.addEdges(t,"media"),c=!0}),o.forEach(e=>{let t=this.model.fetch(e.path),i=this._applyCloudMediaToLocalMedia(e,t);i&&(c=!0)}),r.forEach(e=>{n.removeEdges(e,"media"),c=!0});let i=this._setupThumbnailEdges();i&&(c=!0),c?(u.info("media list changed. saving..."),this.model.saveLayers(n,"media",e=>{u.iferr(e,"model.saveLayers");let i=Promise.resolve();r.forEach(e=>{i.then(e.remove())}),i.then(()=>{u.info("finished saving media list"),t(null,c)})})):t()})}_applyCloudMediaToLocalMedia(e,t){let i=this._syncObjectStrict(e,t.data);return i}_setupThumbnailEdges(){let e=!1;const t=this._fetchMedia();return t.forEach(t=>{if(t.data.reference){let i=this.model.fetch(t.data.reference);if(i){let n=t.getEdges("reference");n.length?1===n.length&&n[0]===i._id||(t.removeEdges(n,"reference"),t.addEdges(i,"reference"),e=!0):(t.addEdges(i,"reference"),e=!0)}else u.warn("can not find original media for thumbnail, skipping",t._id)}}),t.forEach(i=>{let n={};t.forEach(e=>{if(e.data.reference===i._id){let t=e.data.type;t?("reference"!==t||this.issuedReferenceMediaTypeWarning||(u.warn('there is at least one media item with media type "reference"',e._id),this.issuedReferenceMediaTypeWarning=!0),n[t]&&u.warn("media has multiple thumbnails with same media type",t,i._id,e._id),n[t]=n[t]||[],n[t].push(e._id)):u.warn("thumbnail missing media type, skipping",e._id)}});let s=Object.keys(n);if(s.length){let t=Object.keys(i.edges||{});s.forEach(s=>{if(t.indexOf(s)<0)i.addEdges(n[s],s),e=!0;else{let t=i.getEdges(s),o=n[s],r=!1;if(t.length!==o.length)r=!0;else for(let a=0;a<t.length;a++)if(t[a]!==o[a]){r=!0;break}r&&(i.removeEdges(t,s),i.addEdges(o,s),e=!0)}}),t.forEach(t=>{"reference"===t&&i.data.reference||s.indexOf(t)<0&&(i.removeEdges(i.getEdges(t),t),e=!0)})}else{let t=Object.keys(i.edges||{});t.forEach(t=>{"reference"===t&&i.data.reference||(i.removeEdges(i.getEdges(t),t),e=!0)})}}),e}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=h},{"../../utils/Log":88,"../simulator-server-client":71,"./SyncManager":46,jibo:void 0,request:void 0}],45:[function(e,t,i){"use strict";const n=e("rule-generator"),s=e("jibo"),o=e("../../utils/Log"),r=e("jibo-service-framework"),a=e("../listen-service/ListenService"),c=o.createLog("ssm-loop-manager");var u;!function(e){e[e.RESET_MEMORY="NLU_EXECUTED_RESET_MEMORY"]="RESET_MEMORY"}(u||(u={}));class l{init(e){this._setupNLULoopStub(()=>{r.RegistryClient.instance.getRecords((t,i)=>{t?e(t):i?(i.forEach(e=>{"nlu"===e.name&&(this.nluSocketUrl=`ws://${e.host}:${e.port}/port`)}),this.socketState=0,this._setupNLUSocket(e)):e(new Error("no records from registry"))})}),a.default.instance.on("reload-rules",()=>{this._reinitLoopRule()})}update(e,t){let i=[];e.forEach(e=>{let t={userId:e._id,first_name:(e.data.firstName||"").toLowerCase(),last_name:(e.data.lastName||"").toLowerCase(),nick_name:(e.data.nickName||"").toLowerCase()};i.push(t)}),this.rule=n.crew2rule(i),this._sendRule(this.rule,t)}_setupNLULoopStub(e){let t=[],i=n.crew2rule(t);this._sendRule(i,e)}_sendRule(e,t){let i=t=>{c.iferr(t,'nlu.compile error compiling "loop" static rule'),s.nlu.compile(e,n,"crew")},n=e=>{c.iferr(e,'nlu.compile error compiling "crew" static rule'),t(e)};s.nlu?s.nlu.compile(e,i,"loop"):(c.warn("no jibo.nlu object, no update to NLU done"),setImmediate(t))}_setupNLUSocket(e){1===this.socketState?setImmediate(e):0===this.socketState?(this.nluSocket=new r.WSClient(this.nluSocketUrl),this.nluSocket.on("reopen",()=>{this.socketState=1,this._reinitLoopRule()}),this.nluSocket.on("error",e=>{this.socketState=2}),this.nluSocket.on("close",()=>{this.socketState=2}),this.nluSocket.on("message",e=>{e.Event===u.RESET_MEMORY&&this._reinitLoopRule()}),this.nluSocket.once("open",()=>{this.socketState=1,e()})):this.nluSocket.once("reopen",e)}_reinitLoopRule(){this.rule&&this._sendRule(this.rule,()=>{a.default.instance.emit("loop-uploaded"),c.warn("sent rule to nlu")})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=l},{"../../utils/Log":88,"../listen-service/ListenService":51,jibo:void 0,"jibo-service-framework":void 0,"rule-generator":void 0}],46:[function(e,t,i){"use strict";const n=e("assert"),s=e("fs"),o=e("jibo"),r=e("../simulator-server-client"),a=e("jibo-service-framework"),c=e("../../utils/Log"),u=c.createLog("ssm-sync-manager"),l=3e3;class d{constructor(e,t,i,n=true){this.httpUrl=e,this.name=t,this.syncingPeriod=i,this.enableCloud=n,this.queue=[],this.pauseDepth=0}init(e){this.onRobot=this._onRobot(),process.nextTick(e)}shutdown(e){this._notDuringSyncing(t=>{this.isShutdown=!0,e(null)})}_initCredentials(e){d.credentialsInited?process.nextTick(e):(u.info("Getting credentials"),o.systemManager.getCredentials((t,i)=>{t?u.warn("Error initializing credentials!"):(u.info("Credentials found, updating JSC"),r.JSC.config.update(i),d.credentialsInited=!0),e(t)}))}_startSyncTimer(e){if(e=void 0!==e&&e,!e){let e=Math.round(this.syncingPeriod/1e3*10)/10;u.info(`setting ${this.name} sync with cloud every ${e} seconds.`)}this.syncTimer=setTimeout(()=>{this._startSyncing()},this.syncingPeriod)}_startSyncing(){this._syncWithCloud((e,t)=>{t?this._updated(()=>{this._finishSyncing()}):this._finishSyncing()})}_finishSyncing(){for(this.syncing=!1,this.syncTimer=setTimeout(()=>{this._startSyncing()},this.syncingPeriod);this.queue.length>0;){let e=this.queue.shift();e()}}_pauseSyncTimer(){0===this.pauseDepth?(this.syncTimer&&(clearTimeout(this.syncTimer),this.syncTimer=void 0),this.pauseDepth=1):this.pauseDepth<0?u.error("pauseDepth is < 0, something is broken!"):this.pauseDepth+=1}_resumeSyncTimer(){this.pauseDepth&&(this.pauseDepth-=1,0===this.pauseDepth&&(this.syncTimer||this._startSyncTimer(!0)))}_notDuringSyncing(e){if(this.isShutdown)throw Error("tried to use ${this.name} manager after shutdown");this.syncing?this.queue.push(()=>{this._pauseSyncTimer(),e(()=>{this._resumeSyncTimer()})}):(this._pauseSyncTimer(),setImmediate(()=>{e(()=>{this._resumeSyncTimer()})}))}_syncObject(e,t,i,n){let s=!1;return i.forEach(i=>{let o=i;n&&(o=n[i]||i),e.hasOwnProperty(i)?this._deepEqual(e[i],t[o])||(t[o]=e[i],s=!0):t.hasOwnProperty(o)&&(delete t[o],s=!0)}),s}_syncObjectStrict(e,t){let i=!1;return Object.keys(e).forEach(n=>{e.hasOwnProperty(n)?this._deepEqual(e[n],t[n])||(t[n]=e[n],i=!0):t.hasOwnProperty(n)&&(delete t[n],i=!0)}),i}_getServiceRecord(e,t){a.RegistryClient.instance.getRecords((i,n)=>{if(i)t(i);else if(n){let i=!1;for(let s=0;s<n.length;s++)if(n[s].name===e){i=!0,t(null,n[s]);break}i||t(new Error('no record for service "'+e+'" found in registry'))}else t(new Error("no records from registry"))})}_createNodeWithId(e,t,i){let n=new o.kb.Node(i);return n._id=e,t.pool[0].adoptNodeAsOurOwn(n),t.cache.add(n),n}_checkStatusCode(e,t,i=null){if(!e&&(t.statusCode<200||t.statusCode>299)){let n="HTTP Error Code "+t.statusCode;i&&(n+=i),e=new Error(n)}return e}_deepEqual(e,t){try{n.deepEqual(e,t)}catch(e){if("AssertionError"!==e.name)throw e;return!1}return!0}_errorOnce(e){this.pastErrors||(this.pastErrors=[]),this.pastErrors.indexOf(e)<0&&(u.error(e),this.pastErrors.push(e))}_startTimer(){this.timer=performance.now()}_endTimer(e){if(this.timer){let t=Math.round(performance.now()-this.timer);t>l&&u.warn(e,"was slow ("+t+"ms)")}}_onRobot(){return"linux"===process.platform&&"arm"===process.arch&&s.existsSync("/var/jibo")}}d.credentialsInited=!1,Object.defineProperty(i,"__esModule",{value:!0}),i.default=d},{"../../utils/Log":88,"../simulator-server-client":71,assert:void 0,fs:void 0,jibo:void 0,"jibo-service-framework":void 0}],47:[function(e,t,i){"use strict";const n=e("./TypedEvents");class s{constructor(e,t,i){this.ruleUri=e,this.options=t,this.id=i,this.events=new n.DialogListenerEvents,this.options=Object.assign({hotphrase:"",parseIncremental:!1,incremental:!1,speech_to_text:!0,language:"en-US",forceGlobal:!1,metadata:""},t),this.listenResults=null}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"./TypedEvents":53}],48:[function(e,t,i){"use strict";const n={HJ_LISTEN:"HJ_LISTEN",NON_HJ_LISTEN:"NON_HJ_LISTEN",PROCESSING:"PROCESSING",WAITING:"WAITING",UNINITIALIZED:"UNINITIALIZED",SUSPENDED:"SUSPENDED"};Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{}],49:[function(e,t,i){"use strict";const n=e("jibo-state-machine"),s=e("jibo-state-machine"),o=e("./GlobalListen"),r=e("jibo-common-types"),a=e("./states/InterruptNonHJListenersState"),c=e("./states/ParseGlobalState"),u=e("../skills-service/SkillsService"),l=e("../skills-service/SkillsServiceSim"),d=e("./ListenService");i.SMEvents={AddNonHJList:"AddNonHJList",RemLastNonHJList:"RemLastNonHJList",ListenCloud:"ListenCloud",ListenFinished:"ListenFinished",HJHeard:"HJHeard",Suspend:"Suspend",UnSuspend:"UnSuspend"};const h={"@be/clock":"@be/be","@be/settings":"@be/be","@be/greetings":"@be/be","@be/chitchat":"@be/be","@be/main-menu":"@be/be","@be/friendly-tips":"@be/be","@be/who-am-i":"@be/be","@be/create":"@be/be","@be/gallery":"@be/be","@be/idle":"@be/be"};var f;!function(e){e[e.DO_NOT_PARSE_LAUNCH=0]="DO_NOT_PARSE_LAUNCH",e[e.HJ_HEARD=1]="HJ_HEARD",e[e.FORCE_GLOBAL=2]="FORCE_GLOBAL"}(f=i.ParseLaunch||(i.ParseLaunch={}));class p extends n.default{constructor(e,t){super(),this.gl=e,this.hjList=new s.State(this,"HJ Listening"),this.suspended=new s.State(this,"Suspended"),this.wait1=new s.State(this,"Wait1"),this.processQueue=new s.State(this,"Process Add Listeners Queue"),this.startNHJList=new s.State(this,"Start Non-HJ Listening"),this.wait2=new s.State(this,"Wait2"),this.dispatchDialog=new s.State(this,"Dispatch Dialog"),this.handleGlobalParse=new s.State(this,"Handle Global Parse"),this.handleLaunchParse=new s.State(this,"Handle Launch Parse"),this.HJOrNoHJ=new s.State(this,"Determine HJ or No HJ"),this.waitIncr=new s.State(this,"Wait Incremental"),this.waitListenFin=new s.State(this,"Wait ListenFinished"),this.emitHJO=new s.State(this,"emit HeyJiboOnly"),this.checkHJO=new s.State(this,"Check for HJO"),this.interrupt1=new a.default(this,"Interrupt NonHJ listeners1",this.hjList),this.interrupt2=new a.default(this,"Interrupt NonHJ listeners2",this.processQueue),t||(t={}),this.nativeSkillMap=t.nativeSkillMap||h,t.hjOnlyTimeout=void 0!==t.hjOnlyTimeout?t.hjOnlyTimeout:4500,t.nonInterruptingState=this.dispatchDialog,t.handleGlobalParseState=this.handleGlobalParse,t.handleLaunchParseState=this.handleLaunchParse,this.parseAgainstRules=new c.default(this,"Parse Against All Rules (Find Winner)",t),this.handleLaunchParse.addTransition(new s.InternalTransition("",this.interrupt2)),this.handleLaunchParse.onEntry=((t,i)=>{const n=i,s=n.result.launchParse,o=u.default.instance||l.default.instance;o&&o.currentSkill&&(o.currentSkill.name===s.NLParse.skill||o.currentSkill.name===this.nativeSkillMap[s.NLParse.skill])?(e.handleRelaunch(s,n),this.handleLaunchParse.transitionTo(this.interrupt2,s)):(e.handleLaunch(s),this.handleLaunchParse.transitionTo(this.interrupt2,s))}),this.handleGlobalParse.addTransition(new s.InternalTransition("Interrupting Launch",this.handleLaunchParse)),this.handleGlobalParse.addTransition(new s.InternalTransition("Interrupting Unknown",this.interrupt2)),this.handleGlobalParse.addTransition(new s.InternalTransition("Non-Interrupting",this.dispatchDialog)),this.handleGlobalParse.onEntry=((e,t)=>{let i=t,n=i.result.NLParse.intent;if(n.match(/^volume/)&&(n="volume"),d.default.instance.canHandleGlobal(n))this.handleGlobalParse.transitionTo(this.dispatchDialog,i);else switch(r.GlobalCommand[n]){case"STOP":i.result.NLParse.skill="@be/idle",i.result.launchParse=new r.ParseResults(i.result.Input,i.result.NLParse),this.handleGlobalParse.transitionTo(this.handleLaunchParse,i);break;case"HELP":i.result.NLParse.skill="@be/friendly-tips",i.result.launchParse=new r.ParseResults(i.result.Input,i.result.NLParse),this.handleGlobalParse.transitionTo(this.handleLaunchParse,i);break;case"SLEEP":i.result.NLParse.skill="@be/idle",i.result.launchParse=new r.ParseResults(i.result.Input,i.result.NLParse),this.handleGlobalParse.transitionTo(this.handleLaunchParse,i);break;case"VOLUME":console.warn("not yet setting volume in SSM"),this.handleGlobalParse.transitionTo(this.interrupt2),o.default.getInstance().events.skillManager.nonInterruptingGlobal.emit();break;case"PAUSE":i.result.NLParse.skill="@be/idle",i.result.launchParse=new r.ParseResults(i.result.Input,i.result.NLParse),this.handleGlobalParse.transitionTo(this.handleLaunchParse,i);break;case"WHATCANIDO":i.result.NLParse.skill="@be/friendly-tips",i.result.launchParse=new r.ParseResults(i.result.Input,i.result.NLParse),this.handleGlobalParse.transitionTo(this.handleLaunchParse,i);break;default:this.handleGlobalParse.transitionTo(this.interrupt2)}}),this.dispatchDialog.addTransition(new s.InternalTransition("Finished",this.processQueue)),this.dispatchDialog.onEntry=((t,i)=>{const n=i;e.emitResults(n,()=>{this.dispatchDialog.transitionTo(this.processQueue)})}),this.hjList.addEventTransition(i.SMEvents.AddNonHJList,this.startNHJList),this.hjList.addEventTransition(i.SMEvents.Suspend,this.suspended),this.hjList.addEventTransition(i.SMEvents.HJHeard,this.waitIncr),this.hjList.onEntry=(()=>{e._clearCached(),e._startHJListening(),e.events.listen.startHjListen.emit()}),this.suspended.addEventTransition(i.SMEvents.UnSuspend,this.hjList),this.suspended.onEntry=(()=>{e.events.internal.enteringSuspend.emit()}),this.startNHJList.addEventTransition(i.SMEvents.ListenFinished,this.interrupt1),this.startNHJList.addEventTransition(i.SMEvents.RemLastNonHJList,this.hjList),this.startNHJList.addEventTransition(i.SMEvents.Suspend,this.suspended),this.startNHJList.addEventTransition(i.SMEvents.ListenCloud,this.wait2),this.startNHJList.onEntry=(()=>{e._clearCached(),e._startNHJListening(()=>{e.events.listen.startNonHjListen.emit()})}),this.startNHJList.onExit=(t=>{t.getDestinationState()===this.hjList&&e.events.listen.listenFinished.emit()}),this.wait2.addEventTransition(i.SMEvents.ListenFinished,this.HJOrNoHJ),this.HJOrNoHJ.addTransition(new s.InternalTransition("HJ or NHJ",this.parseAgainstRules)),this.HJOrNoHJ.onEntry=(()=>{let t=e._lastCloudListenResults;t.result.Input.toLowerCase().search("hey jibo")!==-1?(e._activeHJListeners.forEach(e=>e.events.hjHeard.emit()),this.HJOrNoHJ.transitionTo(this.parseAgainstRules,f.HJ_HEARD)):this._shouldForceGlobal()?this.HJOrNoHJ.transitionTo(this.parseAgainstRules,f.FORCE_GLOBAL):this.HJOrNoHJ.transitionTo(this.parseAgainstRules,f.DO_NOT_PARSE_LAUNCH)}),this.parseAgainstRules.create(e),this.interrupt1.create(e),this.interrupt2.create(e),this.processQueue.addTransition(new s.InternalTransition("No NonHJ Listeners",this.wait1)),this.processQueue.addTransition(new s.InternalTransition("Some NonHJ Listeners",this.startNHJList)),this.processQueue.onEntry=(()=>{e._queuedNonHJListeners.forEach(t=>e._activeNonHJListeners.add(t)),e._queuedNonHJListeners.clear(),e._activeNonHJListeners.size>0?this.processQueue.transitionTo(this.startNHJList):this.processQueue.transitionTo(this.wait1)}),this.wait1.addTransition(new s.TimeoutTransition("200ms",this.hjList,200)),this.wait1.addEventTransition(i.SMEvents.AddNonHJList,this.startNHJList),this.waitIncr.addEventTransition(i.SMEvents.Suspend,this.suspended),this.waitIncr.addEventTransition(i.SMEvents.ListenCloud,this.waitListenFin),this.waitIncr.addEventTransition(i.SMEvents.ListenFinished,this.emitHJO),this.waitIncr.addTypedEventTransition(e.events.listen.incremental,this.waitListenFin),this.waitIncr.addTransition(new s.TimeoutTransition(`${t.hjOnlyTimeout} ms`,this.emitHJO,t.hjOnlyTimeout));let n=t=>{e._lastIncrementalParseResults=t};this.waitIncr.onEntry=(()=>{e._lastCloudListenResults=void 0,e.events.listen.incremental.on(n)}),this.waitIncr.onExit=(()=>{e.events.listen.incremental.removeListener(n)}),this.waitListenFin.addEventTransition(i.SMEvents.Suspend,this.suspended),this.waitListenFin.addEventTransition(i.SMEvents.ListenFinished,this.checkHJO),this.checkHJO.addTransition(new s.InternalTransition(">HJ",this.parseAgainstRules)),this.checkHJO.addTransition(new s.InternalTransition("HJ only",this.emitHJO)),this.checkHJO.onEntry=(()=>{this._textIsHJO(e._lastCloudListenResults.result.Input)?this.checkHJO.transitionTo(this.emitHJO):this.checkHJO.transitionTo(this.parseAgainstRules,f.HJ_HEARD)}),this.emitHJO.addTransition(new s.InternalTransition("",this.processQueue)),this.emitHJO.onEntry=(()=>{e.handleHJO(new r.ListenResults(null)),this.emitHJO.transitionTo(this.processQueue)})}_shouldForceGlobal(){let e=!1;return this.gl._activeNonHJListeners.forEach(t=>{e=t.options.forceGlobal||e}),e}_textIsHJO(e){let t=e.replace(/(hey)|(jibo)/gi,"").trim();return 0===t.length}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=p},{"../skills-service/SkillsService":72,"../skills-service/SkillsServiceSim":73,"./GlobalListen":50,"./ListenService":51,"./states/InterruptNonHJListenersState":54,"./states/ParseGlobalState":55,"jibo-common-types":void 0,"jibo-state-machine":void 0}],50:[function(e,t,i){"use strict";const n=e("./RuleManager"),s=e("./GLStateMachine"),o=e("./GLStateMachine"),r=e("./GLState"),a=e("./TypedEvents"),c=e("jibo-common-types"),u=e("async"),l=e("../../clients/asr/ASRService"),d=e("uuid");let h=GLOBAL.jibo.utils.perf.SerialTimer;const f={bargein:!1,detectEnd:!0,expectedDuration:"medium",heyJibo:!0,incremental:!0,language:"en-US",metadata:"",speech_to_text:!0},p={bargein:!1,detectEnd:!0,expectedDuration:"medium",heyJibo:!1,incremental:!0,language:"en-US",metadata:"",speech_to_text:!0};var m;!function(e){e[e.HJ=0]="HJ",e[e.NON_HJ=1]="NON_HJ"}(m=i.ListenerType||(i.ListenerType={}));class g{constructor(e,t){this.events=new a.default,this._activeHJListeners=new Set,this._activeNonHJListeners=new Set,this._queuedNonHJListeners=new Set,this._shouldLog=!1,this.language="en-US",this.instanceId="GLInstance-"+d.v4(),this._initialized=!1,this._willResume=!1,this._rulePaths=new Map,this._sm=new s.default(this,e),t&&(this.setLaunchRule(t.launchRulesUri),this.setNluStatus(t.nluStatus),this.setLanguage(t.language))}static parsesCorrectly(e){return!!e.NLParse}resetListenersLocally(){this._activeHJListeners=new Set,this._activeNonHJListeners=new Set,this._queuedNonHJListeners=new Set,this._jiboListener=null}destroy(e){this._forEachActiveListener(e=>{e.events.unsubscribed.emit(),this.removeDialogListener(e)}),this._activeHJListeners=null,this._activeNonHJListeners=null,this._queuedNonHJListeners=null,this._sm.destroy(),this._jiboListener?this._jiboListener.stop(()=>{this._jiboListener.removeAllListeners(),this._jiboListener=null,e&&e()}):e&&e()}getState(){let e=this._sm.current;return this._initialized?e===this._sm.suspended?r.default.SUSPENDED:e===this._sm.hjList||e===this._sm.waitIncr||e===this._sm.waitListenFin?r.default.HJ_LISTEN:e===this._sm.startNHJList||e===this._sm.wait2?r.default.NON_HJ_LISTEN:e===this._sm.wait1?r.default.WAITING:r.default.PROCESSING:r.default.UNINITIALIZED}suspendHJListening(){return new Promise(e=>{this._willResume=!1;let t=()=>{this.events.internal.enteringSuspend.once(()=>e()),this._forEachActiveListener(e=>{e.events.interrupted.emit(),this.removeDialogListener(e)}),this._sm.emit(o.SMEvents.Suspend)};this._sm.current===this._sm.hjList||this._sm.current===this._sm.waitListenFin||this._sm.current===this._sm.waitIncr||this._sm.current===this._sm.startNHJList?t():this.events.listen.startHjListen.once(t)})}resumeHJListening(e){return new Promise((e,t)=>{this._sm.current===this._sm.suspended?(this._willResume=!0,this.events.listen.startHjListen.once(()=>e()),this._sm.emit(o.SMEvents.UnSuspend)):this._willResume?this.events.listen.startHjListen.once(()=>e()):t(new Error(`Can't resume when not suspended`))})}shouldLog(e){return"undefined"!=typeof e&&(this._shouldLog=e),this._shouldLog}setLanguage(e){return("en-US"===e||"ja-JP"===e||"zh-CN"===e)&&(this.language=e,!0)}getLanguage(){return this.language}setMetadata(e){"string"!=typeof e&&(e=JSON.stringify(e)),this.metadata=e}init(e,t){if(this._initialized)throw Error(`Global listen is already initialized`);this._globalRuleUri=e,this._initialized=!0,this._sm.start(),t("")}preLoadNLUs(e,t){let i=[];e.forEach(e=>{i.push(t=>{n.default.instance.getNluUri(e,(e,i)=>{t(e)})})}),u.parallel(i,e=>{t(e)})}_startNHJListening(e){this.log("Starting Non-HJ listening");let t=p;t.language=this.language,t.metadata=this.metadata,this._createListener(p,e)}_startHJListening(e){this.log("Starting HJ listening");let t=f;t.language=this.language,t.metadata=this.metadata,this._createListener(f,e)}parseGlobal(e,t){n.default.instance.parseFromUri(e.result.Input,this._globalRuleUri,(e,i)=>{return e?t(e):t(null,i)})}parseLaunch(e,t){return this._launchRulesUri?void n.default.instance.parseFromUri(e.result.Input,this._launchRulesUri,(e,i)=>{return e?t(e):t(null,i)}):t(null,new c.ParseResults(""))}parseAndSaveLocal(e,t,i){let s=t===m.HJ?this._activeHJListeners:this._activeNonHJListeners,o=[],r=[];s.forEach(t=>{let i;i=t.options.parseAllASR?e.otherResults.map(e=>{return e.utterance}):[e.result.Input];let s=[],a=[];i.forEach(i=>{s.push(s=>{n.default.instance.parseFromUri(i,t.ruleUri,(t,n)=>{t&&(console.error(t),n=n||new c.ParseResults(i,e.result.NLParse));let o=new c.Utterance({utterance:i,score:n.heuristic_score}),r=new c.ListenResults(o,n,e.otherResults);a.push(r),s()})})}),o.push(e=>{u.parallel(s,i=>{a.sort((e,t)=>{return t.result.heuristic_score-e.result.heuristic_score}),t.listenResults=a[0],r.push(a[0]),e(i)})})}),u.parallel(o,e=>{return e?i(e):void i(null,r)})}handleGlobal(e){this._activeHJListeners.forEach(t=>{t.events.interrupted.emit(e),this.removeDialogListener(t)});const t=new c.ListenResults(null,e);this.log("global parse: ",e.NLParse.global,t),this.events.skillManager.globalCommand.emit(t)}handleLaunch(e){this._activeHJListeners.forEach(t=>{t.events.interrupted.emit(e),this.removeDialogListener(t)});let t=new c.ListenResults(null,e);this.log("skill launch parse: ",e.NLParse.skill,t),this.events.skillManager.skillLaunch.emit(t)}handleRelaunch(e,t){const i=new c.Utterance({utterance:e.Input,score:e.heuristic_score}),n=new c.ListenResults(i,e,t.otherResults);this.events.listen.skillRelaunch.emit(n),this.events.listen.noGlobalMatch.emit(e)}emitResults(e,t){let i=e===m.HJ?this._activeHJListeners:this._activeNonHJListeners;i.forEach(e=>{e.events.cloudReceived.emit(e.listenResults),this.removeDialogListener(e)}),t(null)}handleHJO(e){this.events.listen.hjOnly.emit(e),this._activeHJListeners.forEach(t=>{t.events.hjOnly.emit(e),this.removeDialogListener(t)})}addDialogListener(e){if(e.options.hotphrase)this._activeHJListeners.add(e);else{if(this._activeNonHJListeners.has(e)||this._queuedNonHJListeners.has(e))throw new Error(`Listener already exists`);this._sm.getCurrentState()===this._sm.hjList||this._sm.getCurrentState()===this._sm.wait1?(this._activeNonHJListeners.add(e),this._sm.emit(o.SMEvents.AddNonHJList)):this._sm.getCurrentState()===this._sm.startNHJList?this._activeNonHJListeners.add(e):this._queuedNonHJListeners.add(e)}}removeDialogListener(e){this._activeHJListeners&&this._activeNonHJListeners&&(e.options.hotphrase?this._activeHJListeners.has(e)?(e.events.removeAllListeners(),this._activeHJListeners.delete(e)):console.warn(`Can't remove listener '${e.id}' since it hasn't been added`):this._activeNonHJListeners.has(e)?(1===this._activeNonHJListeners.size&&this._sm.emit(o.SMEvents.RemLastNonHJList),e.events.removeAllListeners(),this._activeNonHJListeners.delete(e)):this._queuedNonHJListeners.has(e)?(e.events.removeAllListeners(),this._queuedNonHJListeners.delete(e)):(console.warn(new Error("queued NHJ listeners")),console.warn(`Can't remove listener '${e.id}' since it hasn't been added`)))}_stopListener(e,t){this._jiboListener?this._jiboListener.stop(()=>{t&&this._forEachActiveListener(e=>{e.events.interrupted.emit()}),this.events.listen.listenFinished.emit(),this._jiboListener.removeAllListeners(),e()}):e()}_clearCached(){this._lastCloudListenResults=null,this._lastIncrementalParseResults=null}setGlobalRule(e){this._globalRuleUri=e}setLaunchRule(e){this._launchRulesUri=e}getLaunchRule(){return this._launchRulesUri}getGlobalRule(){return this._globalRuleUri}saveRule(e,t,i){n.default.instance.saveToDisk(e,t,i)}reloadRules(e){if(this._nluStatus===c.NLU_STATUS.CONNECTED){let t=[],i={launch:this._launchRulesUri,global:this._globalRuleUri};for(let s in i){let e=i[s];t.push(t=>{let i=this._rulePaths[e];i?n.default.instance.getUriFromRulePaths(i,t,{desiredUri:e}):t(`reloadRules: no ${s} rule to reload`)})}u.parallel(t,e)}else{const t={name:"RELOAD_ERROR",message:"Could not reload rules: NLU Service is disconnected."};e(t)}}setNluStatus(e){this._nluStatus=e}getNluStatus(){return this._nluStatus}getCombinedUri(e,t,i){n.default.instance.getUriFromRulePaths(e,(i,n)=>{return i?t(i):(this._rulePaths[n]=e,void t(null,n))},i)}getNluUri(e,t){n.default.instance.getNluUri(e,(e,i)=>{return e?t(e):void t(null,i)})}getUriFromText(e,t){n.default.instance.getUriFromText(e,t)}getUriFromFst(e,t){n.default.instance.getUriFromFst(e,t)}log(...e){this._shouldLog&&console.warn("GlobalListen: ",...e)}_createListener(e,t){this._stopListener(()=>{this._lastCloudListenResults=void 0,this._lastIncrementalParseResults=void 0;let i=Object.assign({},e);this._jiboListener=l.default.instance.createListener(i),this._jiboListener.on("cloud",e=>{this.log("cloud: ",e.result),this._lastCloudListenResults=e,this._sm.emit(o.SMEvents.ListenCloud,e),this.events.listen.cloudReceived.emit(e),this._jiboListener=null,this._sm.emit(o.SMEvents.ListenFinished),this.events.listen.listenFinished.emit()}),this._jiboListener.on("incremental",e=>{this._handleIncrementalSignal(e.result),this.events.listen.incremental.emit(e.result)}),this._jiboListener.on("embedded",e=>{let t=new c.ListenResults(null,e);this._sm.emit(o.SMEvents.HJHeard,t),this.events.listen.hjHeard.emit(t),this._activeHJListeners.forEach(e=>{e.events.hjHeard.emit(t)})}),this._jiboListener.on("speaker-id",e=>{this.events.listen.speakerId.emit(e),this._activeHJListeners.forEach(t=>{t.events.speakerId.emit(e)})}),this._jiboListener.on("speech-start",()=>{this.log("speech start"),this.events.listen.sos.emit(),this._forEachActiveListener(e=>e.events.sos.emit())}),this._jiboListener.on("end",()=>{this._serialTimer=new h("internalGL",GLOBAL.jibo._GLTimer),this.log("end"),this.events.listen.eos.emit(),this._forEachActiveListener(e=>e.events.eos.emit())}),this._jiboListener.on("error",e=>{this.log("error: ",e)}),this._jiboListener.start(),t&&t(null,this._jiboListener)})}_handleIncrementalSignal(e){let t=new c.ListenResults({utterance:e.Input,score:0});this._forEachActiveListener(i=>{i.options.incremental&&(i.options.parseIncremental?n.default.instance.parseFromUri(e.Input,i.ruleUri,(e,n)=>{t.result=n,i.events.incremental.emit(t)}):i.events.incremental.emit(t))})}_forEachActiveListener(e){this._activeNonHJListeners.forEach(e),this._activeHJListeners.forEach(e)}}i._GlobalListen=g;class v{static getInstance(){if(v._instance)return v._instance;throw new Error("No Global Listen Instance Found. Must create Instance")}static createInstance(e){return v._instance=new g(e),v._instance}static _resetInstance(e,t){if(v._instance){const i={launchRulesUri:v._instance.getLaunchRule(),nluStatus:v._instance.getNluStatus(),language:v._instance.getLanguage()};v._instance.destroy(()=>{v._instance=new g(e,i),t&&t(null,v._instance)})}else v._instance=new g(e,{}),t&&t(null,v._instance)}constructor(){throw new Error(`Can't instantiate GlobalListen, use 'getInstance()'`)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=v},{"../../clients/asr/ASRService":11,"./GLState":48,"./GLStateMachine":49,"./RuleManager":52,"./TypedEvents":53,async:void 0,"jibo-common-types":void 0,uuid:void 0}],51:[function(e,t,i){"use strict";const n=e("./GlobalListen"),s=e("./DialogListener"),o=e("find-root"),r=e("path"),a=e("uuid"),c=e("jibo-service-framework"),u=e("jibo-common-types"),l=e("../../clients/asr/ASRService"),d=e("../../clients/asr/AudioAction"),h=e("../../utils/Log"),f=e("../performance-service/PerformanceService"),p=e("./RuleManager");let m=h.createLog("ssm-listen-service");class g{}class v extends c.HTTPWSService{constructor(e,t,i){if(super("gl",t,i),this._listeners=new Map,this._globalRuleUri="",this._isEnrolling=!1,v._instance)throw new Error("ListenService is a singleton");v._instance=this,this.clearAllListeners=this.clearAllListeners.bind(this),m.info("Initialized"),this.globalHandlers=new Map,Object.keys(u.GlobalCommand).forEach(e=>{this.globalHandlers.set(u.GlobalCommand[e],!1)})}static createInstance(e,t){return new v(new g,e,t)}static get instance(){return v._instance}init(e){super.init(t=>{return t?e(t):(this.initASRSocket(),c.RegistryClient.instance.getRecords((t,i)=>{return t?e(t):void i.forEach(e=>{"nlu"===e.name&&this.initNLUSocket(e)})}),void this.initializeService(e))})}resetMemory(e,t=true){p.RuleManager.instance.resetMemory(i=>{this.emit("reload-rules"),t?this.once("loop-uploaded",()=>{n.default.getInstance().reloadRules(t=>{t&&console.error("Error reuploading rules ",t),e(t)})}):e(i)})}canHandleGlobal(e){return this.globalHandlers.get(e)}onMessage(e,t){}onClose(e){this.listenSocket=void 0,this.clearAllListeners(),this.resetInstance()}initASRSocket(){l.default.instance.on("close",()=>{
|
||
const e=this.returnType("OK","socket-close","",{});this.sendWsJson(this.listenSocket,e),n.default.getInstance().resetListenersLocally()}),l.default.instance.on("reopen",()=>{const e=this.returnType("OK","socket-reopen","",{});this.sendWsJson(this.listenSocket,e),console.error("SERVICE CRASH; ASR SERVICE DISCONNECTED."),this.resetInstance(!1)})}initNLUSocket(e){const t="ws:"+e.host+":"+e.port+"/reset_memory";this.nluSocket=new c.WSClient(t),this.nluSocket.on("open",(e,t)=>{n.default.getInstance().setNluStatus(u.NLU_STATUS.CONNECTED)}),this.nluSocket.on("error",(e,t)=>{console.error(e,t)}),this.nluSocket.on("reopen",()=>{n.default.getInstance().setNluStatus(u.NLU_STATUS.CONNECTED),this.once("loop-uploaded",()=>{n.default.getInstance().reloadRules((e,t)=>{e&&console.error("Error reuploading rules ",e);const i=this.returnType("OK","nlu-reopen","",{});this.sendWsJson(this.listenSocket,i)})})}),this.nluSocket.on("close",()=>{this.emit("nlu-close"),n.default.getInstance().setNluStatus(u.NLU_STATUS.DISCONNECTED);const e=this.returnType("OK","nlu-close","",{});this.sendWsJson(this.listenSocket,e)}),this.nluSocket.on("message",e=>{const t=this.returnType("OK","nlu-message","",e);this.sendWsJson(this.listenSocket,t),this.emit("nlu-message",e)})}onConnection(e){super.onConnection(e),"/listeners"===e.upgradeReq.url&&(this.listenSocket=e)}routes(e){super.routes(e),e.post("/subscribe",(e,t)=>{this.onSubscribe(e,t)}),e.post("/unsubscribe",(e,t)=>{this.onUnsubscribe(e,t)}),e.post("/enroll",(e,t)=>{this.onEnroll(e,t)}),e.post("/metadata",(e,t)=>{this.onMetadata(e,t)}),e.post("/pronounce",(e,t)=>{this.onPronunciation(e,t)}),e.post("/spoof",(e,t)=>{this.onSpoof(e,t)}),e.post("/pause",(e,t)=>{this.onPause(e,t)}),e.post("/resume",(e,t)=>{this.onResume(e,t)}),e.post("/language",(e,t)=>{this.onLanguage(e,t)}),e.post("/globals",(e,t)=>{this.onGlobals(e,t)}),e.post("/update_global_rule",(e,t)=>{this.updateGlobalRule(e,t)})}resetInstance(e=true){const t=n.default.getInstance().getGlobalRule();n.default.getInstance().events.listen.removeAllListeners(),n.default.getInstance().events.skillManager.removeAllListeners(),e?this.resetMemory(()=>{this._resetInstance(t)}):this._resetInstance(t)}returnType(e,t,i,n){let s={status:e,message:t,id:i,result:n||{},moreinfo:""};return s}sendWsJson(e,t){e&&super.sendWsJson(e,t)}_resetInstance(e){n.default._resetInstance({},(t,i)=>{this.initGlobalListen(e,e=>{e&&console.error(e),this._listeners.forEach(e=>{n.default.getInstance().addDialogListener(e)})}),this.enroller&&this._isEnrolling&&this._suspendIfNeeded(()=>{this.enroller.collectAndEnroll()})})}initializeService(e){let t=this.getRulePaths();this.emit("gotRulePaths",t),n.default.createInstance(this.options),this.resetMemory(()=>{n.default.getInstance().getCombinedUri(t,(t,i)=>{return t?e(t):(this._globalRuleUri=i,this.emit("gotGlobalRule",i),void this.initGlobalListen(this._globalRuleUri,(t,i)=>{e(t)}))})},!1)}onSubscribe(e,t){let i,o;e.on("data",e=>{i=JSON.parse(e),this.emit("onSubscribe",i.rule);let r=this.returnType("subscribed","","",i);i.id?(o=i.id,r.id=i.id,this._listeners.has(i.id)&&(r.status="subscribe-failed",r.moreinfo=`Listener '${i.id}' already subscirbed`)):(o=a.v4(),r.id=o);let c;switch(i.ruleType){case"text":c=n.default.getInstance().getUriFromText.bind(n.default.getInstance());break;case"fst":c=n.default.getInstance().getUriFromFst.bind(n.default.getInstance());break;case"handle":c=((e,t)=>{t(null,e)})}c(i.rule,(e,a)=>{if(this.emit("onRuleUri",a),e)return void console.error("ERROR: Could not subscribe listener",e);let c=new s.default(a,i.options,o);this._listeners.set(o,c),c.events.cloudReceived.on(e=>{e||(e=new u.ListenResults),f.default.instance.log(Date.now(),"JiboCloudReturnSSM");let t=this.returnType("OK","cloud",o,e);this.sendWsJson(this.listenSocket,t),c.events.unsubscribed.emit()}),c.events.eos.on(e=>{f.default.instance.log(Date.now(),"JiboEOSDetectSSM");let t=this.returnType("OK","eos",o,e);this.sendWsJson(this.listenSocket,t)}),c.events.sos.on(e=>{let t=this.returnType("OK","sos",o,e);this.sendWsJson(this.listenSocket,t)}),c.events.incremental.on(e=>{let t=this.returnType("OK","incremental",o,e);this.sendWsJson(this.listenSocket,t)}),c.events.interrupted.on(e=>{let t=this.returnType("OK","interrupt",o,e);this.sendWsJson(this.listenSocket,t),c.events.unsubscribed.emit()}),c.events.unsubscribed.on(e=>{this._listeners.delete(o);let t=this.returnType("OK","unsubscribed",o,e);this.sendWsJson(this.listenSocket,t)}),c.events.hjHeard.on(e=>{f.default.instance.log(Date.now(),"JiboHJRecSSM");let t=this.returnType("OK","hj-heard",o,e);this.sendWsJson(this.listenSocket,t)}),c.events.hjOnly.on(e=>{f.default.instance.log(Date.now(),"JiboHJRecSSM");let t=this.returnType("OK","hj-only",o,e);this.sendWsJson(this.listenSocket,t),c.events.unsubscribed.emit()}),c.events.speakerId.on(e=>{f.default.instance.log(Date.now(),"SpkrIdRecSSM");let t=this.returnType("OK","speaker-id",o,e);this.sendWsJson(this.listenSocket,t)}),n.default.getInstance().addDialogListener(c),this.sendJson(t,r,200);let l=this.returnType("OK","rule-compiled",o,a);this.sendWsJson(this.listenSocket,l)})})}onUnsubscribe(e,t){let i,s;e.on("data",e=>{i=JSON.parse(e);let o=this.returnType("unsubscribed","","",i);if(!i.id)return o.status="FAILED",o.message="no listener id to unsubscribe",void this.sendJson(t,o,200);if(o.id=i.id,s=o.id,!this._listeners.has(i.id))return o.status="FAILED",o.message=`Listener '${i.id}' not found`,void this.sendJson(t,o,200);let r=this._getListener(s);r.events.unsubscribed.emit(),n.default.getInstance().removeDialogListener(r),this.sendJson(t,o,200)})}onEnroll(e,t){let i;e.on("data",e=>{i=JSON.parse(e);let n=i.id,s=this.returnType("OK","enrollment-msg-received","",i);this.sendJson(t,s,200),console.log("LS ENROLLER COMMAND",i.action),this.enroller&&"start"!==i.action||"stop"===i.action?"collectSample"===i.action?(this._isEnrolling=!0,this._suspendIfNeeded(()=>{this.enroller.collectSample()})):"collectAndEnroll"===i.action?(this._isEnrolling=!0,this._suspendIfNeeded(()=>{this.enroller.collectAndEnroll()})):"clearAndEnroll"===i.action?(this._isEnrolling=!0,this._suspendIfNeeded(()=>{this.enroller.clearAndEnroll()})):"clearData"===i.action?(this._isEnrolling=!0,this.enroller.clearPreviousData()):"stop"===i.action?(this._isEnrolling=!1,this.enroller&&(this.enroller.stop(),this.enroller.removeAllListeners(),this.enroller=null),this._unsuspendIfNeeded(),s=this.returnType("OK","stopped-enrollment","",i),this.sendJson(t,s,200)):(s=this.returnType("FAILED","failed-enrollment",'invalid action request to enrollment. valid actions are "start" and "stop"',i),this.sendJson(t,s,200)):(this.enroller=l.default.instance.createEnroller({speakerName:i.speakerId,enrollmentType:i.enrollmentType}),this.enroller.on("saving-audio",e=>{console.log("enroller emitting saving audio");let t=this.returnType("OK","saving-audio",n,e);this.sendWsJson(this.listenSocket,t)}),this.enroller.on("need-more-data",e=>{console.log("enroller emitting nmd");let t=this.returnType("OK","need-more-data",n,e);this.sendWsJson(this.listenSocket,t)}),this.enroller.on("enrollment-started",()=>{let e=this.returnType("OK","started-enrollment",n,{});this.sendWsJson(this.listenSocket,e)}),this.enroller.on("enrollment-done",(e,t)=>{let i={result:e,hjResult:t},s=this.returnType("OK","finished-enrollment",n,i);this.sendWsJson(this.listenSocket,s),this.enroller=null}),this.enroller.on("enrollment-error",(e,t)=>{this._isEnrolling=!1;let i=this.returnType("OK","failed-enrollment",n,t);i.moreInfo=e,this.sendWsJson(this.listenSocket,i)}),this.enroller.on("error",e=>{throw new Error(e)}),this.enroller.on("enrollment-event",()=>{this._isEnrolling=!1,this._unsuspendIfNeeded()}),"collectSample"===i.action||"start"===i.action?(this._isEnrolling=!0,this._suspendIfNeeded(()=>{this.enroller.collectSample()})):"clearAndEnroll"===i.action?(this._isEnrolling=!0,this._suspendIfNeeded(()=>{this.enroller.clearAndEnroll()})):"collectAndEnroll"===i.action&&(this._isEnrolling=!0,this._suspendIfNeeded(()=>{this.enroller.collectAndEnroll()})))})}onPronunciation(e,t){let i;e.on("data",e=>{i=JSON.parse(e);let n=this.returnType("OK","pronunciation-started","",i),s=i.options;if(this.sendJson(t,n,200),"generateG2P"===s.action)this.nameListener=l.default.instance.createNameListener(s),this.nameListener.on("generated-pronun",e=>{let t=this.returnType("OK","generated-pronun",s.listenerId,e);this.sendWsJson(this.listenSocket,t)}),this.nameListener.on("heard-pronun",e=>{let t=this.returnType("OK","heard-pronun",s.listenerId,e);this.sendWsJson(this.listenSocket,t)}),this.nameListener.on("pronun-error",e=>{let t=this.returnType("OK","pronun-error",s.listenerId,e);this.sendWsJson(this.listenSocket,t)}),this.nameListener.on("error",e=>{throw console.error("error: ",e),new Error(e)}),this.nameListener.on("finished",()=>{this._unsuspendIfNeeded(()=>{let e=this.returnType("OK","gl-started","",{});this.sendWsJson(this.listenSocket,e)})}),this.nameListener.start();else if("collectExample"===s.action){if(!this.nameListener){let e=this.returnType("FAILED","pronun-error","",{});return e.message="Error: cannot collect acoustic example without g2p model. Must start pronunciation listener before collecting example.",void this.sendWsJson(this.listenSocket,e)}this._suspendIfNeeded(()=>{let e=this.returnType("OK","gl-stopped","",{});this.sendWsJson(this.listenSocket,e),this.nameListener.collectExample()})}else if("stop"===s.action&&this.nameListener)this.nameListener.stop();else{let e=this.returnType("FAILED","invalid action request to pronunciation interface","",{});this.sendWsJson(this.listenSocket,e)}})}onSpoof(e,t){e.on("data",e=>{let i=JSON.parse(e),n=i.utterance,s=i.speaker;l.default.instance.spoofUtterance(n,s);let o=this.returnType("OK","spoofed-utterance","",{});this.sendJson(t,o,200)})}onPause(e,t){n.default.getInstance().suspendHJListening().then(()=>{let e=this.returnType("OK","gl-stopped","",{});this.sendJson(t,e,200),this.sendWsJson(this.listenSocket,e)})}onResume(e,t){n.default.getInstance().resumeHJListening().then(()=>{let e=this.returnType("OK","gl-started","",{});this.sendJson(t,e,200),this.sendWsJson(this.listenSocket,e)})}onLanguage(e,t){e.on("data",e=>{let i=JSON.parse(e),s=n.default.getInstance().setLanguage(i),o=this.returnType("OK","language:"+i,"",{});s||(o.status="FAILED",o.message="unaccepted language option. Options include en-US, ja-JP, zh-CN"),this.sendJson(t,o,200)})}onMetadata(e,t){e.on("data",e=>{let i=JSON.parse(e),s=i.metadata;n.default.getInstance().setMetadata(s);let o=this.returnType("OK","metadata:"+JSON.stringify(s),"",{});this.sendJson(t,o,200)})}onGlobals(e,t){e.on("data",e=>{let i=JSON.parse(e);this.globalHandlers.set(i.action,i.canHandle);let n=this.returnType("OK",JSON.stringify(i.action+":"+i.canHandle),"",{});this.sendJson(t,n,200)})}initGlobalListen(e,t){n.default.getInstance().init(e,e=>{e&&console.error("Error initializing GL ",e);let i=n.default.getInstance().events.listen,s=n.default.getInstance().events.skillManager;i.cloudReceived.on(e=>{this.emit("cloud-received"),f.default.instance.log(Date.now(),"JiboCloudReturnSSM");let t=this.returnType("OK","cloud","",e);this.sendWsJson(this.listenSocket,t)}),i.hjOnly.on(e=>{this.emit("hj-only"),f.default.instance.log(Date.now(),"JiboHJOnlySSM");let t=this.returnType("OK","hj-only","",e);this.sendWsJson(this.listenSocket,t)}),i.eos.on(e=>{f.default.instance.log(Date.now(),"JiboEOSDetectSSM");let t=this.returnType("OK","eos","",e);this.sendWsJson(this.listenSocket,t)}),i.listenFinished.on(e=>{let t=this.returnType("OK","finished","",e);this.sendWsJson(this.listenSocket,t)}),i.hjHeard.on(e=>{f.default.instance.log(Date.now(),"JiboHJRecSSM"),this.emit("hj-heard");let t=this.returnType("OK","hj-heard","",e);this.sendWsJson(this.listenSocket,t)}),i.speakerId.on(e=>{f.default.instance.log(Date.now(),"JiboSpkrIdRecSSM"),this.emit("speaker-id");let t=this.returnType("OK","speaker-id","",e);this.sendWsJson(this.listenSocket,t)}),i.incremental.on(e=>{this.emit("incremental");let t=this.returnType("OK","incremental","",e);this.sendWsJson(this.listenSocket,t)}),i.noGlobalMatch.on(e=>{let t=this.returnType("OK","no-global","",e);this.sendWsJson(this.listenSocket,t)}),i.startNonHjListen.on(e=>{let t=this.returnType("OK","start-non-hj","",e);this.sendWsJson(this.listenSocket,t)}),i.skillRelaunch.on(e=>{this.emit("skill-relaunch",e.result);let t=this.returnType("OK","skill-relaunch","",e.result);this.sendWsJson(this.listenSocket,t)}),s.skillLaunch.on(e=>{this.emit("skill-launch",e.result)}),s.globalCommand.on(e=>{let t=this.returnType("OK","global","",e);this.sendWsJson(this.listenSocket,t),this.emit("global-command",e)}),s.nonInterruptingGlobal.on(()=>{let e=this.returnType("OK","non-interrupting-global","","");this.sendWsJson(this.listenSocket,e)}),t()})}updateGlobalRule(e,t){let i;e.on("data",e=>{let n=JSON.parse(e);i=n.rulePath;let s=this.returnType("OK","","",n);this.sendJson(t,s,200)}),n.default.getInstance().getNluUri(i,(e,t)=>{return e?void m.error(e):void n.default.getInstance().getCombinedUri([t,this._globalRuleUri],(e,t)=>{return e?void m.error(e):void n.default.getInstance().setGlobalRule(t)})})}_getListener(e){let t=this._listeners.get(e);if(!t)throw new Error(`No listener of id '${e}' subscribed`);return t}getRulePaths(){let e=[],t=o(__dirname);return e.push(r.join(t,"resources/rules/GlobalCommandsLaunch.rule")),e}clearAllListeners(){this._listeners.forEach(e=>{n.default.getInstance().removeDialogListener(e)}),this._listeners=new Map}_suspendIfNeeded(e){let t=n.default.getInstance()._sm.current===n.default.getInstance()._sm.suspended;return t?void this._callIfExists(e):void n.default.getInstance().suspendHJListening().then(()=>{console.log("suspended GL");let t=this.returnType("OK","gl-stopped","",{});this.sendWsJson(this.listenSocket,t),this._callIfExists(e)})}_unsuspendIfNeeded(e){let t=n.default.getInstance()._sm.current===n.default.getInstance()._sm.suspended;return t?void n.default.getInstance().resumeHJListening().then(()=>{console.log("resumed GL");let t=this.returnType("OK","gl-started","",{});this.sendWsJson(this.listenSocket,t),this._callIfExists(e)}):void this._callIfExists(e)}_callIfExists(e){e&&e()}}v.AudioAction=d.default,Object.defineProperty(i,"__esModule",{value:!0}),i.default=v},{"../../clients/asr/ASRService":11,"../../clients/asr/AudioAction":13,"../../utils/Log":88,"../performance-service/PerformanceService":65,"./DialogListener":47,"./GlobalListen":50,"./RuleManager":52,"find-root":void 0,"jibo-common-types":void 0,"jibo-service-framework":void 0,path:void 0,uuid:void 0}],52:[function(e,t,i){"use strict";const n=e("path"),s=e("fs"),o=e("jibo"),r=e("async"),a=e("../skills-service/SkillsService"),c=e("md5");class u{constructor(){if(this.cachePerformanceTimestamp=0,this.FST_CACHE_DIR=s.existsSync("/var/jibo")?"/var/jibo":n.join(process.env.HOME||process.env.USERPROFILE,".jibo"),this._uriCache=new Map,u._instance)throw new Error("RuleManager is a singleton");u._instance=this}static get instance(){return u._instance||(u._instance=new u),u._instance}getNluUri(e,t){e=n.resolve(e),this._uriCache.has(e)?t(null,this._uriCache.get(e)):this._compileNLUFromPath(e,t)}size(){return this._uriCache.size}clearCache(e){e?(e=n.resolve(e),this._uriCache.delete(e)):this._uriCache=new Map}getUriFromText(e,t,i){o.nlu.compile(e,(e,i)=>{e?t(e):t(null,i)})}getUriFromFst(e,t,i){let s;return s=n.isAbsolute(e)?e:n.join(a.default.instance.currentSkill.path,e),this._uriCache.has(e)?void t(null,this._uriCache.get(e)):void this.compileFromFst(e,s,t)}compileFromFst(e,t,i){o.nlu.compileFromFst(t,(t,n)=>{t?i(t):(this._uriCache.set(e,n),i(null,n))},e)}parseFromRulePath(e,t,i){this.getNluUri(t,(t,n)=>{return t?i(t):void this.parseFromUri(e,n,i)})}parseFromNlu(e,t,i){o.nlu.parseFromRule(t,e,(e,t)=>{e?i(e):i(null,t)})}parseFromFst(e,t,i){o.nlu.parseFromFile(t,e,(e,t)=>{e?i(e):i(null,t)})}parseFromUri(e,t,i){o.nlu.parseFromURI(t,e,(e,t)=>{e?i(e):i(null,t)})}createCacheFilenameFromRulePaths(e){let t="";for(let i of e){let e=s.statSync(i);t+=`${i}:${e.mtime.getTime()},`}const n=c(t);return`${this.FST_CACHE_DIR}/${n}-cache.fst`}foundInRulePathsCache(e,t,i){const n=this.createCacheFilenameFromRulePaths(e);try{return s.accessSync(n,s.F_OK),o.nlu.compileFromFst(n,(e,i)=>{console.log(`Fetched and compiled ${n} in ${(Date.now()-this.cachePerformanceTimestamp)/1e3} seconds`),t(e,i)},i),!0}catch(e){return!1}}addToRulePathsCache(e,t,i){const n=this.createCacheFilenameFromRulePaths(e);return this.saveToDisk(t,n,e=>{e&&console.error(`addToFstFileCache failed: ${e}`),i(e,t)}),this.pruneRulePathsCache(6),n}pruneRulePathsCache(e){s.readdir(this.FST_CACHE_DIR,(t,i)=>{let n=[];for(let o of i)if(o.endsWith("-cache.fst")){const e=this.FST_CACHE_DIR+"/"+o;n.push({filename:e,accessTime:s.statSync(e).atime.getTime()})}n.sort((e,t)=>t.accessTime-e.accessTime);for(let r=e;r<n.length;r++)console.log(`cleanFstCache: removing ${n[r].filename}`),s.unlink(n[r].filename)})}combineRulesFromPaths(e,t,i=false){this.getUriFromRulePaths(e,t,{ignoreErrors:i})}getUriFromRulePaths(e,t,i={}){if(this.cachePerformanceTimestamp=Date.now(),!this.foundInRulePathsCache(e,t,i.desiredUri)){let n=[],s=[];e.forEach(e=>{s.push(t=>{this.getNluUri(e,(s,o)=>{return s?i.ignoreErrors?(console.error(`${e} rule failed to compile: `,s),t()):t(s):(n.push(o),void t())})})}),r.parallel(s,s=>{return s&&!i.ignoreErrors||0===n.length?t(s||"No launch rules compiled successfully"):void o.nlu.union(n,(i,n)=>{if(i)console.error(`getUriFromRulePaths: Failed to unionize: ${e.join("\n")}`),t(i);else{let i=this.addToRulePathsCache(e,n,t);console.log(`Compiled from sources to ${i} in ${(Date.now()-this.cachePerformanceTimestamp)/1e3} seconds`)}},i.desiredUri)})}}saveToDisk(e,t,i){o.nlu.saveFstOnDisk(e,t,(e,t)=>{e?i(e):i(null,t)})}resetMemory(e){o.nlu.resetMemory((t,i)=>{t?e(t):e(null,i)})}_compileNLUFromPath(e,t){s.readFile(e,"utf8",(i,n)=>{i?t(i):o.nlu.compile(n,(i,n)=>{i?("string"==typeof i&&(i=i.replace(/\\\/dummypath\\\/dummyfile\.rule/g,e)),t(i)):(this._uriCache.set(e,n),t(null,n))})})}}i.RuleManager=u,Object.defineProperty(i,"__esModule",{value:!0}),i.default=u},{"../skills-service/SkillsService":72,async:void 0,fs:void 0,jibo:void 0,md5:void 0,path:void 0}],53:[function(e,t,i){"use strict";const n=e("jibo-typed-events");class s extends n.EventContainer{constructor(){super(),this.cloudReceived=new n.Event("Received Cloud results"),this.interrupted=new n.Event("Listen behavior interrupted"),this.unsubscribed=new n.Event("Listener has been unsubscribed"),this.incremental=new n.Event("Incremental speech results"),this.eos=new n.Event("End of Speech signal received"),this.sos=new n.Event("Start of Speech signal received"),this.hjHeard=new n.Event("Heard Hey Jibo"),this.speakerId=new n.Event("Got speaker Id results"),this.hjOnly=new n.Event("Heard Hey Jibo only")}}i.DialogListenerEvents=s;class o extends n.EventContainer{constructor(){super(),this.cloudReceived=new n.Event("Received Cloud results"),this.hjOnly=new n.Event("Heard only HJ"),this.listenFinished=new n.Event("SDK listener finished"),this.incremental=new n.Event("Incremental speech results"),this.hjHeard=new n.Event("Heard Hey Jibo"),this.speakerId=new n.Event("Got speaker Id results"),this.eos=new n.Event("End of Speech signal received"),this.sos=new n.Event("Start of Speech signal received"),this.startHjListen=new n.Event("Starting HJ listening"),this.noGlobalMatch=new n.Event("Parsed against global grammar and no result"),this.startNonHjListen=new n.Event("Starting a non Hey Jibo listen"),this.skillRelaunch=new n.Event("Parsed launch grammar from currently running skill")}}i.ListenEvents=o;class r extends n.EventContainer{constructor(){super(),this.globalCommand=new n.Event("Global Command detected"),this.nonInterruptingGlobal=new n.Event("Non-Interrupting Global Command Handled"),this.skillLaunch=new n.Event("Skill Launch Command detected")}}i.SkillManagerEvents=r;class a extends n.EventContainer{constructor(){super(),this.enteringSuspend=new n.Event("Entering suspended state")}}i.InternalEvents=a;class c{constructor(){this.listen=new o,this.skillManager=new r,this.internal=new a}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=c},{"jibo-typed-events":void 0}],54:[function(e,t,i){"use strict";const n=e("jibo-state-machine");class s extends n.State{constructor(e,t,i){super(e,t),this.nextState=i}create(e){this.addTransition(new n.ImmediateTransition("",this.nextState)),this.onEntry=((t,i)=>{const n=i;e._activeNonHJListeners.forEach(t=>{t.events.interrupted.emit(n),e.removeDialogListener(t)})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"jibo-state-machine":void 0}],55:[function(e,t,i){"use strict";const n=e("jibo-state-machine"),s=e("../GlobalListen"),o=e("jibo-common-types"),r=e("async"),a=e("../GLStateMachine");class c extends n.State{constructor(e,t,i){super(e,t),this.options=i,this.nonInterruptingState=i.nonInterruptingState,this.handleGlobalParseState=i.handleGlobalParseState,this.handleLaunchParseState=i.handleLaunchParseState}emitNoGlobal(e,t,i){e.events.listen.noGlobalMatch.emit(i),e._activeHJListeners.size>0&&t?this.transitionTo(this.nonInterruptingState,s.ListenerType.HJ):this.transitionTo(this.nonInterruptingState,s.ListenerType.NON_HJ)}create(e){this.addTransition(new n.InternalTransition("Local Win",this.nonInterruptingState)),this.addTransition(new n.InternalTransition("Global Win",this.handleGlobalParseState)),this.addTransition(new n.InternalTransition("Launch Win",this.handleLaunchParseState)),this.onEntry=((t,i)=>{const n=i,c=e._lastCloudListenResults,u=c.result.Input,l=n===a.ParseLaunch.HJ_HEARD||n===a.ParseLaunch.FORCE_GLOBAL;let d,h,f,p=[];p.push(t=>{e.parseGlobal(c,(e,i)=>{return e?void t(e):(h=i||new o.ParseResults(u),void t(null))})}),n===a.ParseLaunch.FORCE_GLOBAL||n===a.ParseLaunch.HJ_HEARD?p.push(t=>{e.parseLaunch(c,(e,i)=>{return e?void t(e):(f=i||new o.ParseResults(u),void t(null))})}):f=new o.ParseResults(u),p.push(t=>{let i=s.ListenerType.NON_HJ;n===a.ParseLaunch.HJ_HEARD&&(i=s.ListenerType.HJ),e.parseAndSaveLocal(c,i,(e,i)=>{return e?void t(e):i.length?(i.sort((e,t)=>{return t.result.heuristic_score-e.result.heuristic_score}),d=i[0].result,void t(null)):(d=new o.ParseResults(c.result.Input),void t(null))})}),r.parallel(p,t=>{if(t)return console.error(t);const i=Math.max(d.heuristic_score||0,h.heuristic_score||0,f.heuristic_score||0);d.heuristic_score===i?this.emitNoGlobal(e,l,d):f.heuristic_score===i&&l?(c.result.launchParse=f,this.transitionTo(this.handleLaunchParseState,c)):h.heuristic_score>d.heuristic_score?(e.handleGlobal(h),c.result.NLParse=h.NLParse,this.transitionTo(this.handleGlobalParseState,c)):this.emitNoGlobal(e,l,d)})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=c},{"../GLStateMachine":49,"../GlobalListen":50,async:void 0,"jibo-common-types":void 0,"jibo-state-machine":void 0}],56:[function(e,t,i){"use strict";const n=e("./VisualAwareness");let s=0;class o{constructor(e=0){this.position=new n.Point3,this.confidence=1,this.type=e;const t=process.hrtime();this.ts=[t[0],Math.round(t[1]/1e3)],this.id=s++}updatePosition(e){this.position.x=e.x,this.position.y=e.y,this.position.z=e.z}}i.AudioEntity=o;class r{constructor(){this.entities=[]}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=r},{"./VisualAwareness":58}],57:[function(e,t,i){"use strict";const n=e("./VisualAwareness"),s=e("./AudioAwareness"),o=e("./VisualAwareness"),r=e("./AudioAwareness"),a=e("./VisualAwareness"),c=e("jibo-service-framework");class u{}const l=e("../../utils/Log");let d=l.createLog("ssm-lps-service");class h extends c.HTTPWSService{constructor(e,t,i){super("lps",t,i),this.visualAwareness=new n.default,this.audioAwareness=new s.default,h._instance=this,this.onBarcode=this.onBarcode.bind(this),this.onDemandDetect=this.onDemandDetect.bind(this),this.onFaces=this.onFaces.bind(this),this.update=this.update.bind(this),d.info("Initialized")}static createInstance(e,t){return new h(new u,e,t)}static get instance(){return h._instance}init(e){super.init(t=>{this.lastUpdate=performance.now(),setImmediate(this.update),e(t)})}getVisualEntityFromId(e){let t;return this.visualAwareness.entities.forEach(i=>{i.id===e&&(t=i)}),t}triggerSimulatedHJEvent(){const e=new r.AudioEntity(1),t=new a.Point3;t.x=1,t.y=0,t.z=1,e.updatePosition(t),this.oneTimeAudioAwareness||(this.oneTimeAudioAwareness=new s.default),this.oneTimeAudioAwareness.entities.push(e)}triggerAudioEvent(e){let t=new r.AudioEntity;t.updatePosition(e),t.confidence=100,this.audioAwareness.entities.push(t),this.currentAudioId=t.id,this.emit("audio-event-start",e,t.id)}triggerAudioEventEnd(){let e=this.currentAudioId;this.emit("audio-event-end",e),setTimeout(()=>{this.removeAudioEntityById(e)},3e3)}getAudioEntityFromId(e){for(let t=0;t<this.audioAwareness.entities.length;t++)if(this.audioAwareness.entities[t].id===e)return this.audioAwareness.entities[t]}getAudioEntities(){return this.audioAwareness.entities}removeAudioEntityById(e){let t=-1;for(let i=0;i<this.audioAwareness.entities.length;i++)if(this.audioAwareness.entities[i].id===e){t=i;break}return t!==-1&&(this.audioAwareness.entities.splice(t,1),!0)}onVisualEntityAudio(e){let t=this.getVisualEntityFromId(e);this.triggerAudioEvent(t.position),this.update()}setTargetId(e,t){this.visualAwareness.entities.forEach(i=>{i.id===e&&(i.id=t)})}getEntities(){return this.visualAwareness.entities}updateTarget(e){let t=this.getVisualEntityFromId(e.id);t||(t=new o.Entity(e),this.visualAwareness.entities.push(t)),t.updatePosition(e),this.update(!0),this.emit("update",e)}removeEntity(e){let t;for(let i=0;i<this.visualAwareness.entities.length;i++)if(this.visualAwareness.entities[i].id===e){t=i;break}(t||0===t)&&this.visualAwareness.entities.splice(t,1)}onMessage(e,t){}onConnection(e){super.onConnection(e),"/lps/visual_awareness"===e.upgradeReq.url?this.visualSocket=e:"/lps/audible_awareness"===e.upgradeReq.url&&(this.audibleSocket=e)}onClose(e){e===this.audibleSocket?this.audibleSocket=void 0:e===this.visualSocket&&(this.visualSocket=void 0)}routes(e){super.routes(e),e.post("/lps/barcode",this.onBarcode),e.post("/lps/demand_detect",this.onDemandDetect),e.post("/lps/faces",this.onFaces)}onFaces(e,t){t.writeHead(200,{"Content-Type":"json"}),t.end(JSON.stringify(this.visualAwareness.entities))}onBarcode(e,t){this.finishNoContent(t,200)}onDemandDetect(e,t){t.writeHead(200,{"Content-Type":"json"}),t.end(0)}update(e=false){setImmediate(this.update);let t=performance.now();(t-this.lastUpdate>=100||e)&&(this.lastUpdate=t,this.visualSocket&&this.sendWsJson(this.visualSocket,this.visualAwareness),this.audibleSocket&&(this.oneTimeAudioAwareness?(this.oneTimeAudioAwareness.entities=this.oneTimeAudioAwareness.entities.concat(this.audioAwareness.entities),this.sendWsJson(this.audibleSocket,this.oneTimeAudioAwareness),this.oneTimeAudioAwareness=null):this.sendWsJson(this.audibleSocket,this.audioAwareness)))}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=h},{"../../utils/Log":88,"./AudioAwareness":56,"./VisualAwareness":58,"jibo-service-framework":void 0}],58:[function(e,t,i){"use strict";let n=0;class s{constructor(e){this.x=0,this.y=0,e&&(this.x=e.x,this.y=e.y)}}i.Point2=s;class o extends s{constructor(e){super(e),this.z=0,e&&(this.z=e.z)}}i.Point3=o;class r{constructor(){this.time_since_epoch={count:0}}}i.Timestamp=r;class a{constructor(e){this.origin=new o,this.dir=new o,this.cameraId=0,this.tag="",this.timestamp=new r,this.dir.x=e.x,this.dir.y=e.y,this.dir.z=e.z}}i.Ray=a;class c{constructor(){this.position=new o,this.rotation=new o,this.velocity=new o,this.angVelocity=new o}}i.Tracker3D=c;class u{constructor(){this.n11=0,this.n12=0,this.n21=0,this.n22=0}}i.Covariance=u;class l{constructor(){this.left=0,this.top=0,this.right=0,this.bottom=0}}i.Rectangle=l;class d{constructor(){this.id=0,this.cameraId=0,this.confidence=0,this.covariance=new u,this.rectangle=new l,this.velocity=new s,this.inFOV=!1,this.visible=!1,this.lastUpdate=new r,this.name="",this.needModelUpdate=!1}}i.Tracker2D=d;class h{constructor(e){this.id=0,this.confidence=0,this.visible=!1,this.tracker=new c,this.extent=new o,this.rays=[],this.trackers=new d,this.rays=[new a(e)]}}i.PartEntry=h;class f{constructor(e){this.key="",this.value=new h(e)}}i.Part=f;class p{constructor(e){this.id=0,this.confidence=0,this.description="",this.orientation=new o,this.extent=new o,this.static=!1,this.parts=[],this.id=void 0===e.id?n++:e.id,this.position=new o(e),this.parts=[new f(e)]}updatePosition(e){this.position.x=e.x,this.position.y=e.y,this.position.z=e.z,this.parts[0].value.rays[0].dir.x=e.x,this.parts[0].value.rays[0].dir.y=e.y,this.parts[0].value.rays[0].dir.z=e.z}}i.Entity=p;class m{constructor(){this.ts=[0,0],this.entities=[]}addTarget(e){this.entities.push(new p(e))}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=m},{}],59:[function(e,t,i){"use strict";const n=e("request"),s=e("jibo-service-framework"),o=e("../../utils/Log");let r=o.createLog("ssm-media-proxy-service");class a{}i.SingletonEnforcer=a;class c extends s.HTTPService{static createInstance(e,t){return new c(new a,e,t)}static get instance(){return c._instance}constructor(e,t,i){if(super("media-proxy",t,i),c._instance)throw new Error("MediaProxyService is a singleton");c._instance=this,r.info("Initialized")}init(e){super.init(t=>{t?e(t):s.RegistryClient.instance.getRecordByName("media",(t,i)=>{r.iferr(t,"RegistryClient.instance.getRecordByName"),this.mediaServiceUrl=`http://${i.host}:${i.port}`,s.RegistryClient.instance.getRecordByName("media-manager",(t,i)=>{r.iferr(t,"RegistryClient.instance.getRecordByName"),this.mediaManagerServiceUrl=`http://${i.host}:${i.port}`,e(t)})})})}routes(e){super.routes(e),e.get("/proxy/media/photo/get",(e,t)=>{this.photoGet(e,t)})}photoGet(e,t){let i=e.query.id,s={contentID:i,immediate:!0,type:"image"};n.post(this.mediaManagerServiceUrl+"/media-manager/download",{json:s},(e,s)=>{r.iferr(e,"media-manager download");let o=this.mediaServiceUrl+`/media/photo/get?id=${i}`;r.info("proxying",o),n.get(o).pipe(t)})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=c},{"../../utils/Log":88,"jibo-service-framework":void 0,request:void 0}],60:[function(e,t,i){"use strict";const n=e("fs"),s=e("path"),o=e("mkdirp"),r=e("https"),a=e("jibo-service-framework"),c=e("../simulator-server-client"),u=e("jibo-log");let l=new u("ssm-media-manager-service");class d extends a.HTTPService{constructor(e,t){super("media-manager",e,t),this.options=e,d._instance=this}static createInstance(e,t){return new d(e,t)}static get instance(){return d._instance}init(e){super.init(t=>{e(t)})}routes(e){super.routes(e),e.post("/media-manager/upload",this.onUpload.bind(this)),e.post("/media-manager/download",this.onDownload.bind(this)),e.post("/media-manager/delete",this.onDelete.bind(this))}get mediaRootDir(){let e=s.join(process.env.HOME||process.env.USERPROFILE,".jibo","photos");return e}onUpload(e,t){let i=e.body,s=this._filename(i);this._setupLoopId(e=>{e?this.finishNoContent(t,500):n.stat(s,(e,o)=>{e?(l.error("Stat failed",s,e),this.finishNoContent(t,500)):o.isFile()?(this._setupClients(),this.mediaClient.get({paths:[i.contentID]},(e,o)=>{if(l.iferr(e,"Media#get"),o.length>0)l.warn("File already exists on server",i.contentID),i.keepLocal||n.unlink(s,e=>{l.iferr(e,"could not unlink file")}),this.finishNoContent(t,204);else{let e=n.createReadStream(s),o={loopId:this.loopId,body:e,path:i.contentID,type:i.type,isEncrypted:!1,reference:i.reference?i.reference:void 0};this.mediaClient.create(o,(e,o)=>{l.iferr(e,"Media#create"),e||i.keepLocal||n.unlink(s,e=>{l.iferr(e,"could not unlink file")}),this.finishNoContent(t,204)})}})):(l.warn("Not a file",s),this.finishNoContent(t,500))})})}onDownload(e,t){let i=e.body,s=this._filename(i),a=this._filename(i,!0);n.stat(s,(e,c)=>{e?(this._setupClients(),this.mediaClient.get({paths:[i.contentID]},(e,c)=>{if(l.iferr(e,"Media#get"),e||null===c)l.error("Error getting file from server",i.contentID,e),
|
||
this.finishNoContent(t,404);else if(c.length>0){n.existsSync(this.mediaRootDir)||o.sync(this.mediaRootDir);let e=n.createWriteStream(a,{encoding:"binary"});r.get(c[0].url,i=>{i.pipe(e),e.on("finish",()=>{n.rename(a,s,e=>{l.info("Done downloading"),e?(l.error(e,"fs.rename "+a+", "+s),this.finishNoContent(t,500)):this.finishNoContent(t,204)})})})}else l.info("Could not download, file does not exist on server",i.contentID),this.finishNoContent(t,404)})):(l.info("File already exists",s),this.finishNoContent(t,500))})}onDelete(e,t){let i=e.body,s=this._filename(i);if(i.deleteLocal){let e=n.statSync(s);e?e.isFile()?(n.unlinkSync(s),l.info("deleted file: ",s)):l.error("Not a file",s):l.error("Stat failed",s)}i.deleteRemote?(this._setupClients(),this.mediaClient.remove({paths:[i.contentID]},(e,n)=>{e?l.error("Failed (with error) to delete:",i.contentID,e):0===n.length?l.error("Failed to delete:",i.contentID):l.info("Successful deletion",i.contenID),this.finishNoContent(t,204)})):this.finishNoContent(t,204)}_setupLoopId(e){if(this.loopId)process.nextTick(e);else{const t=new c.JSC.Loop;t.list((t,i)=>{t?e(t):i&&0!==i.length?i.length>1?e(new Error("multiple loops found, can not deal with this.")):(this.loopId=i[0].id,e()):e(new Error("failed to lookup loopId, no loop"))})}}_setupClients(){this.mediaClient||(this.mediaClient=new c.JSC.Media)}_filename(e,t=false){let i="";return"recording"===e.type&&(i=".mp4"),"image"!==e.type&&"thumb"!==e.type&&"thumb_robot"!==e.type||(i=".jpg"),t?s.join(this.mediaRootDir,".DL."+e.contentID+i):s.join(this.mediaRootDir,e.contentID+i)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=d},{"../simulator-server-client":71,fs:void 0,https:void 0,"jibo-log":void 0,"jibo-service-framework":void 0,mkdirp:void 0,path:void 0}],61:[function(e,t,i){"use strict";const n=e("path"),s=e("find-root"),o=e("jibo-service-framework"),r=e("../simulator-server-client"),a=e("fs"),c=e("mkdirp"),u=e("uuid"),l=e("jimp"),d=e("async");class h extends o.HTTPService{constructor(e,t){super("media",e,t),this.options=e,h._instance=this,this.onPhoto=this.onPhoto.bind(this),this.onPhotoStore=this.onPhotoStore.bind(this),this.onPhotoGet=this.onPhotoGet.bind(this),this.contentIds=[],this.recordings=[]}static createInstance(e,t){return new h(e,t)}static get instance(){return h._instance}init(e){super.init(t=>{e(t)})}routes(e){super.routes(e),e.post("/media/photo",this.onPhoto),e.get("/media/photo",this.onPhotoGet),e.post("/media/photo/store",this.onPhotoStore),e.get("/media/photo/get",this.onPhotoGet),e.post("/media/recording/start",this.onRecordingStart.bind(this)),e.post("/media/recording/control",this.onRecordingStop.bind(this)),e.post("/media/recording/play",this.onRecordingPlay.bind(this))}getRequestData(e,t){let i="";e.readable?(e.on("data",e=>i+=e),e.on("end",()=>{let e,n;try{e=JSON.parse(i)}catch(e){n=e}n?t(n):t(null,e)})):t(null,e.body)}get mediaRootDir(){let e=n.join(process.env.HOME||process.env.USERPROFILE,".jibo","photos");return e}writeImage(e,t,i,s){let o=n.join(this.mediaRootDir,`${e}.jpg`);l.read(t,(e,t)=>{return e?s(e):void t.resize(i[0],i[1]).write(o,s)})}onPhoto(e,t){let i=u.v4();this.contentIds.push(i);let n={id:i,width:1920,height:1080,expiration:Date.now()+6e4,stored:!1};this.lastPicturePath=this.getFakeSourceFilename(i),this.sendJson(t,n,200)}onPhotoStore(e,t){this.getRequestData(e,(e,i)=>{this.emit("on-photo-store",i);let n,s;if(i.buffer)n=u.v4(),s=i.buffer;else{if(!i.id)return this.sendJson(t,{error:"must specify buffer or id"},500);if(n=i.id,!(this.contentIds.indexOf(n)>=0))return this.sendJson(t,{error:"unknown content id"},500);{let e=this.getFakeSourceFilename(n);s=a.readFileSync(e);for(let t=this.contentIds.length;t>0;t--)this.contentIds[t-1]===n&&this.contentIds.splice(t-1,1)}}this.photoStore(n,s,i.thumbnails,(e,i)=>{e?this.sendJson(t,{error:e.message},500):this.sendJson(t,i,200)})})}photoStore(e,t,i,s){a.existsSync(this.mediaRootDir)||c.sync(this.mediaRootDir);let o={id:e,thumbnails:{}},r=n.join(this.mediaRootDir,`${o.id}.jpg`);a.writeFile(r,t,{encoding:"base64"},e=>{if(e)return s(e);let t=[];Object.keys(i).forEach(e=>{const n=u.v4();o.thumbnails[e]=n,t.push(t=>{this.writeImage(n,r,i[e],t)})}),d.parallel(t,e=>{return e?s(e):void(this.options.serverMediaService?this.updateMedia(o,e=>{return e?s(e):void s(null,o)}):s(null,o))})})}getUploadPhotoFunction(e,t,i,s){return o=>{const c=n.join(this.mediaRootDir,`${t}.jpg`);a.readFile(c,(n,a)=>{if(n)return o(n);const c={loopId:e,body:a,path:t,type:i};s&&(c.reference=s);const u=new r.JSC.Media;u.create(c,o)})}}updateMedia(e,t){const i=new r.JSC.Loop;i.list((i,n)=>{if(i||!n||0===n.length)return t();const s=n[0].id;d.series([this.getUploadPhotoFunction(s,e.id,"image"),this.getUploadPhotoFunction(s,e.thumbnails.mobile,"thumb",e.id)],t)})}onPhotoGet(e,t){let i,s=e.query.id;i=this.contentIds.indexOf(s)>=0?this.getFakeSourceFilename(s):n.join(this.mediaRootDir,`${s}.jpg`);let o=a.readFileSync(i);t.writeHead(200,{"Content-Type":"image/gif"}),t.end(o,"binary")}onRecordingStart(e,t){const i=new Date,n={options:e.body,startTime:Date.now(),id:i.toISOString().substring(0,10)+":"+i.toISOString().substring(11,19)+u.v4()+"."+(e.body.video?"AV":"AX")};this.recordings.push(n),this.sendJson(t,{id:n.id},200),this.emit("recording-start",n)}onRecordingStop(e,t){this.sendJson(t,{},200),this.emit("recording-stop")}onRecordingPlay(e,t){this.sendJson(t,{},200),this.emit("recording-play",e.body)}getFakeSourceFilename(e){let t=(3&e[0])+1;return n.join(s(__dirname),`resources/images/pic${t}.jpg`)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=h},{"../simulator-server-client":71,async:void 0,"find-root":void 0,fs:void 0,"jibo-service-framework":void 0,jimp:void 0,mkdirp:void 0,path:void 0,uuid:void 0}],62:[function(e,t,i){"use strict";const n=e("./Parser"),s=e("jibo-service-framework"),o=e("../../utils/Log"),r=e("jibo-common-types");let a=o.createLog("ssm-nlu-service"),c=0;class u{}var l;!function(e){e[e.OK="OK"]="OK",e[e.ERROR="ERROR"]="ERROR"}(l=i.REQ_STATUS||(i.REQ_STATUS={}));var d;!function(e){e[e.COMPILE="COMPILE"]="COMPILE",e[e.PARSE_FROM_URI="PARSE_FROM_URI"]="PARSE_FROM_URI",e[e.PARSE_FROM_TEXT="PARSE_FROM_TEXT"]="PARSE_FROM_TEXT",e[e.PARSE_FROM_FILE="PARSE_FROM_FILE"]="PARSE_FROM_FILE",e[e.UNION="UNION"]="UNION",e[e.REMOVE_FROM_MEM="REMOVE_FROM_MEM"]="REMOVE_FROM_MEM",e[e.RESET_MEMORY="RESET_MEMORY"]="RESET_MEMORY",e[e.SAVE_FST_IN_DISK="SAVE_FST_IN_DISK"]="SAVE_FST_IN_DISK"}(d||(d={}));class h extends s.HTTPWSService{constructor(e,t,i){super("nlu",t,i),this.handles={},h._instance=this,this.parseMessage=this.parseMessage.bind(this),this.parser=new n.default,a.info("Initialized")}static createInstance(e,t){return new h(new u,e,t)}static get instance(){return h._instance}init(e){super.init(t=>{e(t)})}routes(e){super.routes(e),e.post("/nlu_interface",this.parseMessage)}onConnection(e){super.onConnection(e),"/reset_memory"===e.upgradeReq.url&&(this.socket=e)}onMessage(e,t){}onClose(e){this.socket=null}parseMessage(e,t){let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{let e;try{e=JSON.parse(i)}catch(e){return void this.sendJson(t,{Status:l.ERROR,Message:"Inavlid request. Request body is not valid JSON"},200)}e.REQ_TYPE===d.COMPILE?this.compile(e.REQ_CONTENT.RULE_STRING,e.REQ_CONTENT.BINARYFST_PATH,e.REQ_CONTENT.URI,t):e.REQ_TYPE===d.PARSE_FROM_URI?this.parseFromUri(e.REQ_CONTENT.URI,e.REQ_CONTENT.TXT_STRING,t):e.REQ_TYPE===d.PARSE_FROM_TEXT?this.parseFromText(e.REQ_CONTENT.RULE_STRING,e.REQ_CONTENT.TXT_STRING,t):e.REQ_TYPE===d.PARSE_FROM_FILE?this.parseFromFile(e.REQ_CONTENT.URI,e.REQ_CONTENT.TXT_STRING,t):e.REQ_TYPE===d.UNION?this.union(e.REQ_CONTENT.URIS,e.REQ_CONTENT.URI,t):e.REQ_TYPE===d.REMOVE_FROM_MEM?this.removeFromMemory(e.REQ_CONTENT.URI,t):e.REQ_TYPE===d.RESET_MEMORY?this.resetMemory(t):e.REQ_TYPE===d.SAVE_FST_IN_DISK&&this.saveFstOnDisk(e.REQ_CONTENT.URI,e.REQ_CONTENT.BINARYFST_PATH,t)})}_parseText(e,t){let i=this.parser.nlu.build_sentence_parser(e),n=i.parse_sentence(t);return JSON.parse(n)}parseFromUri(e,t,i){let n={Status:l.OK,URI:""},s=this.handles[e];s&&this.parser.nlu?n.Result=this._parseText(s,t):(n.Status=l.ERROR,n.Message=`No handle named '${e}' exists`),this.sendJson(i,n,200)}parseFromText(e,t,i){let n={Status:l.OK};try{let i=this.parser.nlu.compile_fst_from_text(e,`handle:${c++}`);n.Result=this._parseText(i,t)}catch(e){n.Status=l.ERROR,n.Message=e.message}this.sendJson(i,n,200)}parseFromFile(e,t,i){let n={Status:l.OK};try{let i=this.parser.nlu.read_fst_from_uri("file://"+e);n.Result=this._parseText(i,t)}catch(e){n.Status=l.ERROR,n.Message=e.message}this.sendJson(i,n,200)}compile(e,t,i,n){let s={Status:l.OK,URI:""},o=`handle:${c++}`;if(i&&(o=i,o.startsWith("handle:")||(o="handle:"+o)),t)this.handles[o]=this.parser.nlu.load_fst_from_fst_file(t,o),s.URI=o;else try{this.handles[o]=this.parser.nlu.compile_fst_from_text(e,o),s.URI=o}catch(e){s.Status=l.ERROR,s.Message=e.message}this.sendJson(n,s,200)}union(e,t,i){let n={Status:l.OK,URI:""},s=`handle:${c++}`;t&&(s=t,s.startsWith("handle:")||(s="handle:"+s));try{this.handles[s]=this.parser.nlu.union_fst(e,s),n.URI=s}catch(e){n.Status=l.ERROR,n.Message=e.message}this.sendJson(i,n,200)}removeFromMemory(e,t){let i={Status:l.OK};try{this.handles[e]=null,this.parser.nlu.remove_from_memory(e)}catch(e){i.Status=l.ERROR,i.Message=e.message}this.sendJson(t,i,200)}saveFstOnDisk(e,t,i){let n={Status:l.OK,Stats:{SAVE_TIME:0},Message:"OK"};if(e){e.startsWith("handle:")||(e="handle:"+e);let i=this.parser.nlu.read_fst_from_uri(e);i.save_fst(t)}else{const e={exception:"Bad request",info:{msg:"Must provide rule uri and filePath to save fst on disk."}};n.Message=e}this.sendJson(i,n,200)}resetMemory(e){let t={Status:l.OK,Stats:{COMP_TIME:0,REMOVE_TIME:0},Message:"OK"};if(this.sendJson(e,t,200),this.socket){const e={Event:r.NLUMessages.RESET_MEMORY};this.sendWsJson(this.socket,e)}}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=h},{"../../utils/Log":88,"./Parser":63,"jibo-common-types":void 0,"jibo-service-framework":void 0}],63:[function(e,t,i){"use strict";const n=e("find-root"),s=e("path"),o=e("fs");class r{constructor(){let t=s.join(n(__dirname)),i=s.join(t,"parser/build/Release/jsjibonlu.jibo"),r=s.join(t,"parser/build/Release/jsjibonlu.node");o.existsSync(i)&&o.renameSync(i,r);try{this.nlu=e(r);let i=s.join(t,"parser","deps","data");this.nlu.set_data_dir(i)}catch(e){console.error(e),this.nlu=void 0}}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=r},{"find-root":void 0,fs:void 0,path:void 0}],64:[function(e,t,i){"use strict";const n=e("uuid"),s=e("jibo-service-framework"),o=e("../../utils/Log");let r=o.createLog("ssm-notifications-service");class a{}class c extends s.HTTPWSService{static createInstance(e,t){return new c(new a,e,t)}static get instance(){return c._instance}constructor(e,t,i){super("notifications",t,i),c._instance=this,this._queue=[],r.info("Initialized")}init(e){super.init(t=>{e(t)})}onMessage(e,t){}onConnection(e){super.onConnection(e)}routes(e){super.routes(e),e.post("/notifications",(e,t)=>{this.createNotification(e,t)}),e.put("/notifications/:id",(e,t)=>{this.updateNotification(e,t)}),e.get("/notifications",(e,t)=>{this.getAllNotifications(e,t)}),e.delete("/notifications/:id",(e,t)=>{this.deleteNotification(e,t)}),e.delete("/notifications",(e,t)=>{this.deleteAllNotifications(e,t)})}createNotification(e,t){e.body.id=n.v4(),this._queue.push(e.body),this.sendJson(t,e.body,200),this.notifyEmit("notification-created",e.body)}updateNotification(e,t){const i=this._queue.find(t=>t.id===e.params.id);return void 0===i?void this.sendJson(t,{},404):(i.type=e.body.type?e.body.type:i.type,i.title=e.body.title?e.body.title:i.title,i.description=e.body.description?e.body.description:i.description,this.sendJson(t,i,200),void this.notifyEmit("notification-updated",i))}getAllNotifications(e,t){let i=this._queue;this.sendJson(t,i,200)}deleteNotification(e,t){const i=this._queue.findIndex(t=>t.id===e.params.id);return i===-1?void this.sendJson(t,{},404):(this._queue.splice(i,1),this.sendJson(t,{},200),void this.notifyEmit("notification-deleted",e.params.id))}deleteAllNotifications(e,t){this._queue=[],this.sendJson(t,{},200),this.notifyEmit("notifications-all-deleted",void 0)}notifyEmit(e,t){this.emit(e,t),this.connections.forEach(i=>{this.sendWsJson(i,{eventName:e,event:t})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=c},{"../../utils/Log":88,"jibo-service-framework":void 0,uuid:void 0}],65:[function(e,t,i){"use strict";const n=e("jibo-service-framework");class s{static get instance(){return s._instance||(s._instance=new s),s._instance}init(e){e()}log(e,t,i){}}class o extends n.HTTPWSService{constructor(e,t){if(super("performance",e,t),this.options=e,o._instance)throw new Error("PerformanceService is a singleton");o._instance=this}static createInstance(e,t){return new o(e,t)}static get instance(){return o._instance?o._instance:s.instance}init(e){super.init(t=>{return t?e(t):void e()})}routes(e){super.routes(e),e.post("/log",(e,t)=>{let i="";e.on("data",e=>i+=e),e.on("end",()=>{let e;try{e=JSON.parse(i),this.log(e.time,e.type,e.description),this.sendJson(t,{status:"OK"})}catch(e){console.warn("Performance service cannot parse ",i),this.sendJson(t,{status:"error",message:"could not parse json",json:i},400)}})})}log(e,t,i){this.connections.forEach(n=>{this.sendWsJson(n,{time:e,type:t,description:i?i:""})})}now(){return performance.timing.navigationStart+performance.now()}onMessage(e,t){console.log("PerformanceService.onMessage",e),"time-ping"===e.type&&this.sendWsJson(t,{time:this.now(),type:"time-pong",description:e.description})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=o},{"jibo-service-framework":void 0}],66:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("../../utils/Log");let o=s.createLog("ssm-registry-service"),r=[];class a{}class c extends n.HTTPService{static createInstance(e,t){return new c(new a,e,t)}static get instance(){return c._instance}constructor(e,t,i){if(super("registry",t,i),this.registry=new u(r),c._instance)throw new Error("KBService is a singleton");c._instance=this,o.info("Initialized")}routes(e){e.get("/registry",(e,t)=>{this.sendJson(t,this.registry)}),e.put("/registry",(e,t)=>{let i=e.body;this.registry.put(i),this.finishNoContent(t)}),e.post("/registry",(e,t)=>{let i=e.body;this.registry.get(i.name)?(this.registry.post(i)&&o.info("updating registry entry for",i.name),this.finishNoContent(t)):this.finish(t,new Error("error during POST: no such entry "+i.name))}),e.delete("/registry",(e,t)=>{let i=e.body;this.registry.delete(i.name),this.finishNoContent(t)})}}class u{constructor(e=[]){if(this.records=[],e)for(let t=0;t<e.length;t++)this.put(e[t])}get(e){for(let t=0;t<this.records.length;t++)if(e===this.records[t].name)return this.records[t];return null}put(e){return!this.get(e.name)&&(this.records.push(e),!0)}post(e){for(let t=0;t<this.records.length;t++)if(e.name===this.records[t].name)return this.updateRecord(this.records[t],e);return!1}delete(e){for(let t=0;t<this.records.length;t++)if(e===this.records[t].name)return this.records.splice(t,1),!0;return!1}updateRecord(e,t){const i=e.host!==t.host||e.port!==t.port||e.path!==t.path;return i&&(e.host=t.host,e.port=t.port,e.path=t.path),e.ttl=t.ttl,e.tls=t.tls,i}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=c},{"../../utils/Log":88,"jibo-service-framework":void 0}],67:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("../../utils/Log"),o=e("../../utils/OTAUpdater");class r extends n.HTTPService{constructor(e,t){if(super("scheduler",e,t),this.options=e,r._instance)throw new Error("SchedulerService is a singleton");this._log=s.createLog("ssm-scheduler-service"),r._instance=this,o.default.createInstance(this._log),this._log.info("Initialized")}static createInstance(e,t){return new r(e,t)}static get instance(){return r._instance}init(e){super.init(t=>{return t?e(t):void e()})}routes(e){super.routes(e),e.post("/ota-update",(e,t)=>{let i="";e.on("data",e=>i+=e),e.on("end",()=>{o.default.instance.downloadAndInstall(e=>{return e?this.sendJson(t,{status:"Error",message:e.message},500):this.sendJson(t,{status:"OK"})})})}),e.post("/download-status",(e,t)=>{let i="";e.on("data",e=>i+=e),e.on("end",()=>{o.default.instance.getDownloadStatus((e,i)=>{return e?this.sendJson(t,{status:"Error",message:e.message},500):this.sendJson(t,{status:"OK",data:i})})})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=r},{"../../utils/Log":88,"../../utils/OTAUpdater":89,"jibo-service-framework":void 0}],68:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("../../utils/Log");let o=s.createLog("ssm-service-manager");class r{}class a extends n.HTTPService{static createInstance(e,t){return new a(new r,e,t)}static get instance(){return a._instance}constructor(e,t,i){if(super("service-manager",t,i),a._instance)throw new Error("ServiceManager is a singleton");a._instance=this,o.info("Initialized")}routes(e){super.routes(e),e.get("/",(e,t)=>{n.RegistryClient.instance.getRecords((e,i)=>{let s="<!doctype html><html><head><title>Skills Service Manager</title></head><body>\n";i.forEach(e=>{e.name.indexOf("-service")>0&&(s+=`<div><a href="http://${n.RegistryClient.instance.host}:${e.port}">${e.name}</a></div>
|
||
`)}),s+="</body></html>\n",t.end(s)})}),e.get("/test",(e,t)=>{this.sendJson(t,{foo:"bar"})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=a},{"../../utils/Log":88,"jibo-service-framework":void 0}],69:[function(e,t,i){"use strict";function n(e,...t){process.nextTick(()=>{e(...t)})}const s=e("./data");class o{static update(e){console.log("SSC config.updaate",e)}}class r{update(e,t){console.log("SSC Account.update",e),n(t,null)}get(e,t){e.ids?n(t,null,s.default.accounts):n(t,null,[s.default.accounts[1]])}}class a{list(e,t){t||"function"!=typeof e||(t=e,e=null),n(t,null,s.default.loop)}setEnrollment(e,t){n(t,null)}}class c{create(e,t){n(t,null)}list(e,t){n(t,null,[])}}class u{connect(e,t){class i{on(e,t){}}let s=new i;n(t,null,s)}}class l{listHolidays(e,t){n(t,null,s.default.holidays)}}class d{}d.config=o,d.Account=r,d.Loop=a,d.Media=c,d.Notification=u,d.Person=l,i.JSC=d},{"./data":70}],70:[function(e,t,i){"use strict";const n={accounts:[{_id:"576d983a5bb1c11100ae4188",email:"jibotestloop1@jibo.com",lastName:"Jetson",firstName:"George",gender:"male",birthday:-720576e5,isActive:!0,facebookConnected:!1},{_id:"576d983d5bb1c11100ae4189",isActive:!0,facebookConnected:!1},{_id:"576d983e9a06e1110090109f",email:"jibotestloop1+jane@jibo.com",lastName:"Jetson",firstName:"Jane",gender:"female",birthday:3211668e5,isActive:!0,facebookConnected:!1},{_id:"576d983f5bb1c11100ae418b",email:"jibotestloop1+judy@jibo.com",lastName:"Jetson",firstName:"Judy",gender:"female",birthday:10071828e5,isActive:!0,facebookConnected:!1},{_id:"576d98405bb1c11100ae418c",email:"jibotestloop1+elroy@jibo.com",lastName:"Jetson",firstName:"Elroy",gender:"male",birthday:1065672e6,isActive:!0,facebookConnected:!1},{_id:"576d98419a06e111009010a0",email:"jibotestloop1+rosie@jibo.com",lastName:"Jetson",firstName:"Rosie",gender:"female",birthday:-4282704e5,isActive:!0,facebookConnected:!1},{_id:"576d98429a06e111009010a1",email:"jibotestloop1+astro@jibo.com",lastName:"Jetson",firstName:"Astro",gender:"male",birthday:1264482e6,isActive:!0,facebookConnected:!1}],loop:[{id:"576d983d5bb1c11100ae418a",name:"TestLoop",owner:"576d983a5bb1c11100ae4188",robot:"576d983d5bb1c11100ae4189",robotFriendlyId:"Fake-Not-Real-Jibo",members:[{loopId:"576d983d5bb1c11100ae418a",memberId:"576d983a5bb1c11100ae4188",account:{email:"jibotestloop1@jibo.com",firstName:"George",lastName:"Jetson",gender:"male",birthday:-720576e5},enrolled:{face:!0,voice:!1},status:"accepted",type:"outgoing"},{loopId:"576d983d5bb1c11100ae418a",memberId:"576d983d5bb1c11100ae4189",account:{},enrolled:{face:!1,voice:!1},status:"accepted",type:"outgoing"},{loopId:"576d983d5bb1c11100ae418a",memberId:"576d983e9a06e1110090109f",account:{email:"jibotestloop1+jane@jibo.com",firstName:"Jane",lastName:"Jetson",gender:"female",birthday:3211668e5},enrolled:{face:!0,voice:!0},status:"accepted",type:"outgoing"},{loopId:"576d983d5bb1c11100ae418a",memberId:"576d983f5bb1c11100ae418b",account:{email:"jibotestloop1+judy@jibo.com",firstName:"Judy",lastName:"Jetson",gender:"female",birthday:10071828e5},enrolled:{voice:!0},status:"accepted",type:"outgoing"},{loopId:"576d983d5bb1c11100ae418a",memberId:"576d98405bb1c11100ae418c",account:{email:"jibotestloop1+elroy@jibo.com",firstName:"Elroy",lastName:"Jetson",gender:"male",birthday:1065672e6},enrolled:{face:!1,voice:!1},status:"accepted",nickname:"Junior",type:"outgoing"},{loopId:"576d983d5bb1c11100ae418a",memberId:"576d98419a06e111009010a0",account:{email:"jibotestloop1+rosie@jibo.com",firstName:"Rosie",lastName:"Jetson",gender:"female",birthday:-4282704e5},enrolled:{face:!1,voice:!1},status:"accepted",type:"outgoing"},{loopId:"576d983d5bb1c11100ae418a",memberId:"576d98429a06e111009010a1",account:{email:"jibotestloop1+astro@jibo.com",firstName:"Astro",lastName:"Jetson",gender:"male",birthday:1264482e6},enrolled:{face:!1,voice:!1},status:"accepted",type:"outgoing"}],created:1466785494997,updated:1476809757933}],holidays:[{id:"57d1aeac571a56100057970c",name:"MLK Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-01-18",created:1473359532106},{id:"57d1aeac571a56100057970d",name:"Presidents Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-02-15",created:1473359532117},{id:"57d1aeac571a56100057970e",name:"Tax Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-04-18",created:1473359532119},{id:"57d1aeac571a56100057970f",name:"Memorial Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-05-30",created:1473359532121},{id:"57d1aeac571a561000579710",name:"Flag Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-06-14",created:1473359532122},{id:"57d1aeac571a561000579711",name:"Independence Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-07-04",created:1473359532124},{id:"57d1aeac571a561000579712",name:"Labor Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-09-05",created:1473359532126},{id:"57d1aeac571a561000579713",name:"Veterans Day",category:"national",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-11-11",created:1473359532128},{id:"57d1aeac571a561000579714",name:"New Years Day",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-01-01",created:1473359532130},{id:"57d1aeac571a561000579715",name:"Groundhog Day",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-02-02",created:1473359532132},{id:"57d1aeac571a561000579717",name:"St. Patrick's Day",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-03-17",created:1473359532139},{id:"57d1aeac571a561000579718",name:"April Fool's Day",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-04-01",created:1473359532141},{id:"57d1aeac571a561000579719",name:"Cinco de Mayo",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-05-05",created:1473359532143},{id:"57d1aeac571a56100057971a",name:"Mother's Day",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-05-08",created:1473359532146},{id:"57d1aeac571a56100057971b",name:"Father's Day",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-06-19",created:1473359532148},{id:"57d1aeac571a56100057971c",name:"Halloween",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-10-31",created:1473359532151},{id:"57d1aeac571a56100057971d",name:"Thanksgiving",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-11-24",created:1473359532153},{id:"57d1aeac571a56100057971e",name:"New Years Eve",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-12-31",created:1473359532154},{id:"57d1aeac571a56100057971f",name:"Ash Wednesday",category:"cultural",subcategory:"christian",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-02-10",created:1473359532156},{id:"57d1aeac571a561000579720",name:"Good Friday",category:"cultural",subcategory:"christian",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-03-25",created:1473359532158},{id:"57d1aeac571a561000579721",name:"Palm Sunday",category:"cultural",subcategory:"christian",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-03-20",created:1473359532163},{id:"57d1aeac571a561000579722",name:"Easter",category:"cultural",subcategory:"christian",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-03-27",created:1473359532165},{id:"57d1aeac571a561000579723",name:"Christmas",category:"cultural",subcategory:"christian",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-12-25",created:1473359532167},{id:"57d1aeac571a561000579724",name:"Ramadan",category:"cultural",subcategory:"islamic",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-06-05",created:1473359532169},{id:"57d1aeac571a561000579725",name:"Eid-al-Fitr",category:"cultural",subcategory:"islamic",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-07-05",created:1473359532170},{id:"57d1aeac571a561000579726",name:"Purim",category:"cultural",subcategory:"hebrew",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-03-23",created:1473359532172},{id:"57d1aeac571a561000579727",name:"Passover",category:"cultural",subcategory:"hebrew",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-04-22",created:1473359532174},{id:"57d1aeac571a561000579728",name:"Rosh Hashanah",category:"cultural",subcategory:"hebrew",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-10-02",created:1473359532177},{id:"57d1aeac571a561000579729",name:"Yom Kippur",category:"cultural",subcategory:"hebrew",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-10-11",created:1473359532179},{id:"57d1aeac571a56100057972a",name:"Sukkot",category:"cultural",subcategory:"hebrew",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-10-16",created:1473359532182},{id:"57d1aeac571a56100057972b",name:"Hanukkah",category:"cultural",subcategory:"hebrew",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-12-24",created:1473359532184},{id:"57d1aeac571a56100057972c",name:"Kwanzaa",category:"cultural",subcategory:"african",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-12-26",created:1473359532187},{id:"57d1aeac571a56100057972d",name:"Chinese New Year",category:"cultural",subcategory:"chinese",loopId:"576d983d5bb1c11100ae418a",isEnabled:!1,date:"2016-02-08",created:1473359532188},{id:"57d1aeac571a56100057972e",category:"birthday",loopId:"576d983d5bb1c11100ae418a",memberId:"576d983e9a06e1110090109f",isEnabled:!0,date:"1980-03-06",created:1473359532190},{id:"57d1aeac571a56100057972f",category:"birthday",loopId:"576d983d5bb1c11100ae418a",memberId:"576d983f5bb1c11100ae418b",isEnabled:!0,date:"2001-12-01",created:1473359532192},{id:"57d1aeac571a561000579730",category:"birthday",loopId:"576d983d5bb1c11100ae418a",memberId:"576d98405bb1c11100ae418c",isEnabled:!0,date:"2003-10-09",created:1473359532194},{id:"57d1aeac571a561000579731",category:"birthday",loopId:"576d983d5bb1c11100ae418a",memberId:"576d98419a06e111009010a0",isEnabled:!0,date:"1956-06-06",created:1473359532199},{id:"57d1aeac571a561000579732",category:"birthday",loopId:"576d983d5bb1c11100ae418a",memberId:"576d98429a06e111009010a1",isEnabled:!0,date:"2010-01-26",created:1473359532201},{id:"57e03cd8571a561000579a50",category:"birthday",loopId:"576d983d5bb1c11100ae418a",memberId:"576d983a5bb1c11100ae4188",isEnabled:!0,date:"1967-09-20",created:1474313432916},{id:"57eb9d767078a80010ad94a4",name:"Valentines Day",category:"public",loopId:"576d983d5bb1c11100ae418a",isEnabled:!0,date:"2016-02-14",created:1475059062266}]};Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{}],71:[function(e,t,i){"use strict";try{i.JSC=e("@jibo/jibo-server-client")}catch(t){i.JSC=e("./SimulatorServerClient").JSC}},{"./SimulatorServerClient":69,"@jibo/jibo-server-client":void 0}],72:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("path"),o=e("electron"),r=e("../listen-service/RuleManager"),a=e("../listen-service/GlobalListen"),c=e("../performance-service/PerformanceService"),u=e("find-root"),l=e("async"),d=e("../../utils/Log"),h=e("../../clients/SystemManagerClient"),f=e("../../clients/DevToolsClient"),p=e("../../background/screen/ScreenScheduler");let m=d.createLog("ssm-skills-service");class g{}class v extends n.HTTPWSService{constructor(e,t,i){if(super("skills-service",t,i),this.options=t,v._instance)throw new Error("SkillsService is a singleton");v._instance=this,m.info("Initialized")}static createInstance(e,t){return new v(new g,e,t)}static get instance(){return v._instance}static setGlobalListenRules(e,t){function i(e){let t=s.join(u(__dirname),"resources/rules/GlobalCommandsLaunch.rule");return t?void a.default.getInstance().getCombinedUri([t],(t,i)=>{return c.default.instance.log(Date.now(),"JiboCombineGlobalRules"),t?e(t):(a.default.getInstance().setGlobalRule(i),void e())}):e("Initializing GLService with no global rules")}function n(t){return 0===e.length?t():void a.default.getInstance().getCombinedUri(e,(e,i)=>{return c.default.instance.log(Date.now(),"JiboCombineLaunchRules"),e?t(e):(a.default.getInstance().setLaunchRule(i),void t())},{ignoreErrors:!0})}c.default.instance.log(Date.now(),"JiboSetLaunchRule"),r.RuleManager.instance.clearCache(),l.parallel([i,n],t)}static setSingleLaunchRule(t,i){let n=[],o=s.join(t.path,"package.json"),r=e(o);r.jibo&&r.jibo.launchRule&&(Array.isArray(r.jibo.launchRule)?r.jibo.launchRule.forEach(e=>{n.push(s.join(t.path,e))}):"string"==typeof r.jibo.launchRule&&n.push(s.join(t.path,r.jibo.launchRule))),v.setGlobalListenRules(n,i)}init(e){super.init(t=>{return t?e(t):void p.default.stopTimerAndTurnOn().then(()=>{this.setLaunchRules(e)})})}setLaunchRules(e,t=true){return this.options.startSkill?void(this.options.singleSkill?(console.warn("SSM operating in single skill mode"),h.default.instance.getSkillRecordByName(this.options.startSkill,(i,n)=>{v.setSingleLaunchRule(n,i=>{return i?e(i):void(t?this.launch(this.options.startSkill,{},e):e())})})):!this.options.singleSkill):void v.setGlobalListenRules([],t=>{e(t)})}routes(t){super.routes(t),t.get("/skill/list",(e,t)=>{h.default.instance.list((e,i)=>{return e?this.sendJson(t,{error:e.message},500):void this.sendJson(t,{skills:i})})}),t.get("/devtools",(e,t)=>{f.default.createInstance("127.0.0.1",9191).getJson((e,i)=>{this.sendJson(t,i)})}),t.get("/ssm-devtools",(e,t)=>{f.default.createInstance("127.0.0.1",12345).getJson((e,i)=>{this.sendJson(t,i)})}),t.get("/version",(t,i)=>{const n=u(__dirname),o=e(s.join(n,"package.json"));this.sendJson(i,{version:o.version})}),t.post("/launch-dev",(e,t)=>{let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{let e;try{e=JSON.parse(i)}catch(e){return void this.sendJson(t,{Status:"ERROR",Message:"Invalid request from launch. Request body is not valid JSON"},200)}console.info("attempting to run skill",e.command),this.launch(e.command,{},i=>{i?(console.error("error running skill",e.command,i),this.sendJson(t,{Status:"ERROR",Message:'Skill "'+name+'" does not exist or could not by launched. Make sure to run `jibo sync`'},200)):(console.info("System Manager launched skill",e.command),this.sendJson(t,{Status:"OK",Message:'Skill "'+name+'" started successfully'},200))})})}),t.post("/terminate",(e,t)=>{let i="";e.on("data",e=>{i+=e}),e.on("end",()=>{let e;try{e=JSON.parse(i)}catch(e){return void this.sendJson(t,{Status:"ERROR",Message:"Invalid request from launch. Request body is not valid JSON"},200)}h.default.instance.terminate(e.command,e=>{o.ipcRenderer.send("show"),p.default.start(),this.currentSkill=null,this.finishNoContent(t)})})})}launch(e,t,i){c.default.instance.log(Date.now(),"JiboLaunch");let n=e=>{this.currentSkill=e,this.options.singleSkill&&v.setSingleLaunchRule(e,t=>{return t?i(t):void h.default.instance.launch(e.name,e=>{return e?i(e):void p.default.stopTimerAndTurnOn().then(()=>{i()}).catch(e=>{i(e)})})})};h.default.instance.getSkillRecordByName(e,(e,t)=>{return c.default.instance.log(Date.now(),"JiboLaunchGetSkillRecordByName"),e?i(e):void(this.currentSkill?h.default.instance.terminate(this.currentSkill.name,e=>{return c.default.instance.log(Date.now(),"JiboLaunchTerminateCurrentSkill"),e?i(e):void n(t)}):n(t))})}resetLaunchRules(e){v.setSingleLaunchRule(this.currentSkill,e)}terminate(e){return this.currentSkill?void h.default.instance.terminate(this.currentSkill.name,t=>{return this.currentSkill=null,p.default.start(),o.ipcRenderer.send("show"),t?e(t):void e()}):void e()}onMessage(e,t){if("initDone"===e.command)console.info(this.currentSkill.name,"launched and initialized"),o.ipcRenderer.send("hide"),this.sendWsJson(t,{command:"show"});else if("finished"===e.command&&"@be/be"===this.currentSkill.name){let e={};e.Input="",e.NLParse={skill:"@be/idle"},e.status="GOT-PARSE",a.default.getInstance().events.listen.skillRelaunch.emit({result:e})}}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=v},{"../../background/screen/ScreenScheduler":7,"../../clients/DevToolsClient":9,"../../clients/SystemManagerClient":10,"../../utils/Log":88,"../listen-service/GlobalListen":50,"../listen-service/RuleManager":52,"../performance-service/PerformanceService":65,async:void 0,electron:void 0,"find-root":void 0,"jibo-service-framework":void 0,path:void 0}],73:[function(e,t,i){"use strict";const n=e("path"),s=e("fs"),o=e("find-root"),r=e("./SkillsService"),a=e("../listen-service/GlobalListen"),c=e("jibo-service-framework");class u extends c.HTTPWSService{constructor(e,t){if(super("skills-service",e,t),this.options=e,this.currentSkill={name:"@be/be",path:"/"},u._instance)throw new Error("SkillsServiceSim is a singleton");u._instance=this}static createInstance(e,t){return new u(e,t)}static get instance(){return u._instance}init(e){super.init(e)}onMessage(t,i){if("initDone"===t.command)if(this.options.skillsBaseDir){let t=this.options.skillsBaseDir,o=n.join(this.options.skillsBaseDir,"package.json");if(s.statSync(t).isDirectory()&&s.existsSync(o)){let n=e(o);this.currentSkill.name=n.name,this.currentSkill.path=t,r.default.setSingleLaunchRule(this.currentSkill,e=>{if(e)throw new Error("Could not set up launch rule");this.sendWsJson(i,{command:"show"})})}}else this.sendWsJson(i,{command:"show"});else if("finished"===t.command&&"@be/be"===this.currentSkill.name){let e={};e.Input="",e.NLParse={skill:"@be/idle"},e.status="GOT-PARSE",a.default.getInstance().events.listen.skillRelaunch.emit({result:e})}}routes(t){super.routes(t),t.get("/version",(t,i)=>{const s=o(__dirname),r=e(n.join(s,"package.json"));this.sendJson(i,{version:r.version})})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=u},{"../listen-service/GlobalListen":50,"./SkillsService":72,"find-root":void 0,fs:void 0,"jibo-service-framework":void 0,path:void 0}],74:[function(e,t,i){"use strict";const n=e("path"),s=e("jibo-service-framework"),o=e("fs"),r=e("uuid"),a={secretAccessKey:"W5dxPYfmdGTETneE1LeuIcp8aCXrgr4eomrfW50s",accessKeyId:"3MRGwcKUvQuAk8Hsl7Xp",region:"stg-entrypoint"},c="EdNNKxicwehgIXhlLM4Nb1L66NZC6NXTLhVRuyCs";class u extends s.HTTPWSService{static createInstance(e,t){return new u(e,t)}static get instance(){return u._instance}constructor(e,t){super("system-manager",e,t),u._instance=this,this.onGetIdentity=this.onGetIdentity.bind(this),this.onGetCredentials=this.onGetCredentials.bind(this),this.onGetMode=this.onGetMode.bind(this),this.onGetVersion=this.onGetVersion.bind(this)}init(e){super.init(t=>{e(t)})}routes(e){super.routes(e),e.get("/credentials",this.onGetCredentials),e.get("/identity",this.onGetIdentity),e.get("/mode",this.onGetMode),e.get("/version",this.onGetVersion)}onMessage(e,t){}getRequestData(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{try{let e=JSON.parse(i);t(null,e)}catch(e){t(e)}})}onGetCredentials(e,t){let i=n.join(process.env.HOME||process.env.USERPROFILE,".jibo","credentials.json");o.readFile(i,"utf8",(e,n)=>{let s;if(e&&"ENOENT"===e.code)e=null,s=a,o.writeFileSync(i,JSON.stringify(s,null,4));else{try{s=JSON.parse(n)}catch(e){console.error(`The credentials file has invalid JSON at ${i}`)}s&&s.secretAccessKey===c&&(s=a,o.writeFileSync(i,JSON.stringify(s,null,4)))}s&&this.sendJson(t,s)})}onGetIdentity(e,t){this.sendJson(t,{guid:r.v4(),name:"opal-sage-victor-valley",cpuid:r.v4(),wifi_mac:r.v4()})}onGetMode(e,t){this.sendJson(t,{mode:"normal"})}onGetVersion(e,t){this.sendJson(t,{version:"Jibo Release Version: Release-3.1.0\n"})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=u},{fs:void 0,"jibo-service-framework":void 0,path:void 0,uuid:void 0}],75:[function(e,t,i){"use strict";const n=e("jibo-service-framework");class s extends n.HTTPWSService{constructor(e,t){super("system-monitoring-service",e,t)}static createInstance(e,t){return s._instance||(s._instance=new s(e,t)),s._instance}static get instance(){return s._instance||console.error("system monitoring service sim instance not created"),s._instance}onMessage(e,t){console.log("SystemMonitoringServiceSim::OnMessage")}}s._instance=null,Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"jibo-service-framework":void 0}],76:[function(e,t,i){"use strict";const n=e("jibo-node-xml"),s=e("pos").Lexer;var o;!function(e){e[e.Incremental="Incremental"]="Incremental",e[e.Instant="Instant"]="Instant",e[e.Test="Test"]="Test"}(o=i.TTSPlaybackMode||(i.TTSPlaybackMode={}));const r={[o.Incremental]:{words:.3,pauses:.2},[o.Test]:{words:.3,pauses:.2},[o.Instant]:{words:3e-4,pauses:2e-4}},a={ids:/(?:^|\s)[a-z0-9-]{8,45}(?:$|\s)/gi,number:/[0-9]*\.[0-9]+|[0-9]+(?=\W)/gi,space:/\s+/gi,unblank:/\S/,email:/[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](?:\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](?:-?\.?[a-zA-Z0-9])*(?:\.[a-zA-Z](?:-?[a-zA-Z0-9])*)+/gi,urls:/(?:https?:\/\/)(?:[\da-z\.-]+)\.(?:[a-z\.]{2,6})(?:[\/\w\.\-\?#]*)*\/?/gi,punctuation:/[\.]{3}|[\/\.\,\?\!\"\:\;\$\(\)\#]/gi};class c{constructor(e=o.Instant){this.mode=e,this._lexer=new s,this._lexer.regexs=[a.urls,a.ids,a.number,a.space,a.email,a.punctuation]}static _isEndPunctuation(e){return"."===e||"?"===e||"!"===e}createPromptAndTokens(e){let t,i,s,o;try{i=n.Parser.parseXML(e)}catch(e){console.error(`Error parsing TTS prompt: `,e)}return i?[t,s]=this._extractTextFromXML(i):([o,s]=this._extractWordTokens(e),s&&!c._isEndPunctuation(s[s.length-1])&&s.push(this._createPauseToken(o,r[this.mode].pauses)),t=e),s||0!==t.length||(s=[]),[t,s]}_createBreakToken(e,t){return{name:"<break>",start:e,end:Math.round(100*(e+t))/100}}_createPauseToken(e,t){return{name:"[lpau]",start:e,end:Math.round(100*(e+t))/100}}_extractWordTokens(e,t=0,i=[]){const n=r[this.mode].words;let s=t;return this._lexer.lex(e).forEach(e=>{e=e.trim(),i.push({name:e.toLowerCase(),start:Math.round(100*s)/100,end:Math.round(100*(s+n))/100}),s=Math.round(100*(s+n))/100}),[s,i]}_extractTextFromXML(e){let t=[],i=[];const n=this._extractTextFromXMLRecursive(e,t,0,i);return i.length>0&&!c._isEndPunctuation(i[i.length-1].name)&&i.push(this._createPauseToken(n,r[this.mode].pauses)),[t.join(" "),i]}_extractTextFromXMLRecursive(e,t,i,n){let s=i;if("TEXT"===e.type){let o=e.value.trim();t.push(o),[s,n]=this._extractWordTokens(o,i,n)}else if("break"===e.type.toLowerCase()){let t=0;try{t=Number.parseFloat(e.getAttribute("size"))}catch(e){console.log(`Couldn't parse 'size' attribute of break tag: `,e)}t>0&&(this.mode===o.Instant&&(t=r[o.Instant].pauses),n.push(this._createBreakToken(s,t)),s=Math.round(100*(s+t))/100)}return e.forEachChild(e=>{s=this._extractTextFromXMLRecursive(e,t,s,n)}),s}}i.TTSPromptParser=c},{"jibo-node-xml":void 0,pos:void 0}],77:[function(e,t,i){"use strict";const n=e("events"),s=e("jibo-service-framework"),o=e("./TTSPromptParser"),r=e("../../utils/Log");let a=r.createLog("ssm-tts-service");class c{}class u extends n.EventEmitter{constructor(e,t,i,n){super(),this.tokens=e,this.ttsService=t,this.realTime=i,this.res=n,this._stopped=!1,this.update=this.update.bind(this),this.ttsService.emit("sending-tokens"),a.info("Initialized")}stop(){this._stopped=!0,this.ttsService.sendJson(this.res,{Status:"OK",Message:"Speaking TTS"},204)}start(){this._startTime=performance.now(),this.update()}update(){if(!this._stopped){let e=performance.now()-this._startTime,t=this.realTime?1e3:1;if(e>this.tokens[0].start*t){let e=this.tokens.shift();this.ttsService.emit("token",e.name)}0===this.tokens.length?(this.ttsService.sendWsJson(this.ttsService.tokensSocket,this.ttsService.returnType("",0,"STOP")),this.stop(),this.emit("stop"),this.removeAllListeners()):setImmediate(this.update)}}}class l extends s.HTTPWSService{constructor(e,t,i){super("tts",t,i),this.mode=o.TTSPlaybackMode.Incremental,l._instance=this}static createInstance(e,t){return new l(new c,e,t)}static get instance(){return l._instance}setMode(e){let t=o.TTSPlaybackMode[e]||o.TTSPlaybackMode.Incremental;t||(t=o.TTSPlaybackMode.Incremental,console.warn(`Invalid TTS playback mode '${e}', using '${t}'`)),this.mode=t}toggleDevMode(){console.warn(`Deprecated, please use 'setMode'`),this.mode!==o.TTSPlaybackMode.Incremental?this.mode=o.TTSPlaybackMode.Incremental:this.mode=o.TTSPlaybackMode.Instant}init(e){super.init(t=>{e(t)})}onMessage(e,t){}onConnection(e){super.onConnection(e),"/tts_tokens"===e.upgradeReq.url?this.tokensSocket=e:"/tts_phones"===e.upgradeReq.url&&(this.phonesSocket=e)}routes(e){super.routes(e),e.post("/tts_token_times",(e,t)=>{this.onTokenTimes(e,t)}),e.post("/tts_speak",(e,t)=>{this.onSpeak(e,t)}),e.get("/tts_stop",(e,t)=>{this.onStop(e,t)})}returnType(e,t,i){return{token:e,timestamp:t,status:i,moreinfo:[]}}onTokenTimes(e,t){e.on("data",e=>{let i=JSON.parse(e);const n=new o.TTSPromptParser(this.mode),s=n.createPromptAndTokens(i.prompt);let r={tokentimes:{tokens:s[1]}};this.sendJson(t,r,200)})}onSpeak(e,t){e.on("data",e=>{let i=JSON.parse(e);this.stopCurrentWorker();const n=new o.TTSPromptParser(this.mode),s=n.createPromptAndTokens(i.prompt),r=this.mode===o.TTSPlaybackMode.Incremental;s[1].length&&(this.currentWorker=new u(s[1],this,r,t),this.currentWorker.on("stop",()=>{this.currentWorker.removeAllListeners(),this.currentWorker=null}),this.currentWorker.start())})}stopCurrentWorker(){this.currentWorker&&(this.currentWorker.stop(),this.currentWorker.removeAllListeners(),this.currentWorker=null),this.emit("stop")}onStop(e,t){let i={Status:"OK",Message:"Stopping TTS"};this.sendJson(t,i,200),this.stopCurrentWorker(),this.sendWsJson(this.tokensSocket,this.returnType("",0,"STOP"))}}l.TTSPromptParser=o.TTSPromptParser,Object.defineProperty(i,"__esModule",{value:!0}),i.default=l},{"../../utils/Log":88,"./TTSPromptParser":76,events:void 0,"jibo-service-framework":void 0}],78:[function(e,t,i){"use strict";const n=e("https");let s=e("fs");const o=e("./scanning/ActiveScan"),r=e("./scanning/StatusHandler"),a=e("./scanning/NetworkManager"),c=e("./scanning/ErrorCode"),u=e("../../clients/SystemManagerClient"),l="/var/etc/networks.conf",d=1e3,h=15e3,f=1e3;class p{constructor(e){this.inProgress=!1,this.networkManager=new a.default,this.statusHandler=new r.default,this.activeScan=new o.default,this.tempNetworks=null,this.lastState=-1,this.scanData=null,this.connecting=0,this.connected=0,this._wifiService=e,this.syncedTime=!1,this._jiboServerUrl=null,this._wifiService.on("scan_results_populated",e=>{this.updateSavedProfiles(e)}),this.scanListen(h),this.statusListen(2500)}init(e){u.default.instance.getCredentials((t,i)=>{t?this._jiboServerUrl=this._wifiService.options.region+".jibo.com":this._jiboServerUrl=i.region+".jibo.com",this._wifiService.log.info("Jibo server url is "+this._jiboServerUrl),e()})}addNetwork(e){this.connecting=1,u.default.instance.addNetwork(e)}removeNetwork(e,t,i){u.default.instance.removeNetwork(e,(e,n)=>{n?this._removeInterfaceSetting(t,e=>{e?i(e):u.default.instance.saveConfig((e,t)=>{i(t?null:e)})}):i(e)})}disconnect(e){u.default.instance.disconnect((t,i)=>{t?e(t):e(null,i)})}getScanResults(e){let t=setInterval((i,n)=>{this.activeScan.scanResults((i,n)=>{i?(clearInterval(t),e(i)):n&&n.split("\n").length>2&&(clearInterval(t),e(null,n))})},d)}pollStats(e){u.default.instance.signalPoll(e)}scan(e){this.activeScan.scan(e)}getSavedNetworks(e){this.networkManager.getNetworks((t,i)=>{if(t)return void e(t);{let t=[];const n=i.split("\n");for(let s=0;s<n.length;++s){let e=n[s].split("\t");const i=e[1];if(i){const n=e[0],s="[CURRENT]"===e[3];t.push({index:n,ssid:i,current:s})}}e(null,t)}})}selectNetwork(e,t,i){t?this._saveInterfaceSettings(t,n=>{n?(console.log("Save Interface Settings Failure"),i(n,null)):t.networkType===m.DHCP?this._configureNetworkSettings(m.DHCP,null,(t,n)=>{t?(console.log("DHCP Failure Settings!"),i(t)):this.adjustStatusPolling(e,e=>{e?i(e):i(null,"success")})}):t.networkType===m.STATIC&&(console.log("Setting network as a static network!"),this.getSavedNetworks((n,s)=>{if(n)return i(n);let o=!1;const r=s.length;for(let a=0;a<r;a++)if(s[a].ssid===t.ssid){o=!0;break}o?this._configureNetworkSettings(m.STATIC,t.staticSettings,(n,s)=>{n?this._removeInterfaceSetting(t.ssid,()=>{i(n)}):this.adjustStatusPolling(e,(e,t)=>{e?i(e):i(null,"success")})}):i(new Error("Could not select network "+t.ssid))}))}):this.getSavedNetworks((t,n)=>{if(t)return i(t);const s=n.length;for(let o=0;o<s;o++)if(n[o].index===e){this._getInterfaceSettings(n[o].ssid,(t,n)=>{n?this._configureNetworkSettings(m.STATIC,n,t=>{t?this._removeInterfaceSetting(e,()=>{return i(t)}):this.adjustStatusPolling(e,e=>{return e?i(e):i(null,"success")})}):this._configureNetworkSettings(m.DHCP,null,(t,n)=>{return t?i(t):void this.adjustStatusPolling(e,e=>{return e?i(e):i(null,"success")})})});break}})}verifyConnection(e){this.status((t,i)=>{return t?void e(new c.default(666,"BAD THINGS ARE HAPPENING: "+t)):void(i.indexOf("COMPLETED")>-1?(console.log("VerifyConnection #1 (AP): OK"),this.status((t,i)=>{i&&i.indexOf("ip_address=")>-1?(console.log("VerifyConnection #2 (IP): OK"),this._checkJiboServers(t=>{let i=t?t:"OK";console.log("VerifyConnection #3 (Jibo Servers): "+i),t?e(new c.default(4,"Cannot Ping Jibo Servers")):e()})):e(new c.default(2,"Could Not Obtain IP Address"))})):e(new c.default(1,"Did not connect to the Access Point")))})}setNetwork(e,t,i){let n;if(t.ssid)n=e+' ssid "'+t.ssid+'"';else if(t.hidden)n=e+" scan_ssid 1";else if(t.psk)n=e+' psk "'+t.psk+'"';else if(t.security)switch(t.security){case"WPA-PSK":n=e+" key_mgmt WPA-PSK";break;case"WPA2-PSK":n=e+" key_mgmt WPA-PSK";break;case"OPEN":n=e+" key_mgmt NONE"}u.default.instance.setNetwork(n,i)}status(e){this.statusHandler.status(e)}statusListen(e){this.statusHandler.listen(e,this.statusCB.bind(this))}scanListen(e){this.activeScan.listen(e,this.scanCB.bind(this))}networkProfiles(e){this.networkManager.getContainer(e)}saveNetwork(e,t){u.default.instance.saveConfig((e,i)=>{e?t(e):t(null,i)})}adjustStatusPolling(e,t){this.connecting=1,this.statusListen(f),u.default.instance.selectNetwork(e,i=>{i?t(i):u.default.instance.enableNetwork(e,e=>{e?t(e,null):t(null)})})}scanCB(e,t){return e?void console.log("Error Detected: "+e):void this.activeScan.scanResults(this.scanResultsCB.bind(this))}networkCB(e,t){return e?void console.log("Error Detected: "+e):void(t.split("\n").length>2&&this.networkManager.updateProfiles(t,this.updateActiveNetworksDictionary.bind(this)))}updateSavedProfiles(e){this.scanData=e,this.networkManager.getNetworks(this.networkCB.bind(this))}updateActiveNetworksDictionary(e){this.scanData&&e.updateWiFiProfiles(this.scanData,()=>{e.getBestNetwork(e=>{e.rssi&&this.selectNetwork(e.networkID,null,(t,i)=>{e.tried=!0})})})}_isInterfaceEqual(e,t){return e.method===t.method&&e.address===t.address&&e.network===t.network&&e.netmask===t.netmask&&e.broadcast===t.broadcast&&e.gateway===t.gateway&&e.dns===t.dns}_getDNSString(e){let t="";return e&&(e.dns1&&(t+=e.dns1),e.dns2&&(e.dns1&&(t+=" "),t+=e.dns2)),t}_configureNetworkSettings(e,t,i){let n=e===m.DHCP?"dhcp":"static";u.default.instance.getInterface((e,s)=>{let o={method:n,address:t?t.staticIP:"",network:"",netmask:t?t.netmask:"",broadcast:"",gateway:t?t.gateway:"",dns:this._getDNSString(t)};this._isInterfaceEqual(s,o)?i(null,"Network settings are the same. Do not need to update."):this._setInterface(n,t,(e,t)=>{e?(console.log("setInterface error; reverting to dhcp"),this._setInterface("dhcp",null,()=>{i(e)})):i(null,"Network settings updated. ["+t+"]")})})}_setInterface(e,t,i){let n=this._getDNSString(t),s={method:e,address:t?t.staticIP:"",network:"",netmask:t?t.netmask:"",broadcast:"",gateway:t?t.gateway:"",dns:n};u.default.instance.setInterface(s,i)}_saveInterfaceSettings(e,t){if(e.staticSettings&&e.staticSettings.staticIP){let i={};if(s.existsSync(l))try{i=JSON.parse(s.readFileSync(l,"utf8"))}catch(e){return void t(e)}i[e.ssid]={staticIP:e.staticSettings.staticIP,gateway:e.staticSettings.gateway,netmask:e.staticSettings.netmask,dns1:e.staticSettings.dns1,dns2:e.staticSettings.dns2};try{s.writeFile(l,JSON.stringify(i),"utf8",e=>{e?t(new Error(e)):t()})}catch(e){t(new Error(e))}}else t()}_getInterfaceSettings(e,t){s.readFile(l,"utf8",(i,n)=>{
|
||
i&&t();try{let i=JSON.parse(n);i.hasOwnProperty(e)?t(null,i[e]):t()}catch(e){t(e)}})}_removeInterfaceSetting(e,t){s.readFile(l,"utf8",(i,n)=>{if(i)return void t();try{let i=JSON.parse(n);i.hasOwnProperty(e)?(delete i[e],s.writeFile(l,JSON.stringify(i),"utf8",e=>{e?t(new Error(e)):t()})):t()}catch(e){t(new Error(e))}})}scanResultsCB(e,t){let i=setInterval((e,t)=>{this.activeScan.scanResults((e,t)=>{return e?void clearInterval(i):t&&t.split("\n").length>2?(0!==this.connecting||0!==this.connected||this.inProgress||this._wifiService.sendSocketData("scan_results_populated",t),void clearInterval(i)):void 0})},d)}stateCB(e){let t={"-1":"INIT",0:"SCANNING",1:"AUTHENTICATING",2:"4WAY_HANDSHAKE",3:"CONNECTED",4:"DISCONNECTED"},i=15e3;switch(3===e?(this.connected=1,this.activeScan.stopListener()):this.connected=0,1!==e&&2!==e&&this.resetStatus(),e){case-1:switch(this.lastState){case 0:this.resetStatus();break;case 1:this.resetStatus();break;case 3:this.resetStatus();break;case 4:this.resetStatus()}break;case 0:switch(this.lastState){case-1:this.resetStatus();break;case 0:this.resetStatus();break;case 1:if(!this.inProgress){setTimeout(()=>{this.verifyConnection(e=>{e?(this._wifiService.sendError(e),this.resetStatus(),u.default.instance.disconnect((e,t)=>{e?console.log(e):console.log("Disconnecting. After Authentication, Device went to SCANNING")})):this.resetStatus()})},i);break}case 2:if(!this.inProgress){setTimeout(()=>{this.verifyConnection(e=>{e?(this._wifiService.sendError(e),this.resetStatus(),u.default.instance.disconnect((e,t)=>{e?console.log(e):console.log("Disconnecting. After 4WAY, Device went to SCANNING")})):this.resetStatus()})},i);break}case 3:this.resetStatus()}break;case 1:switch(this.lastState){case 1:break;case 2:break;case 3:break;case 4:}break;case 2:switch(this.lastState){case 1:break;case 2:break;case 3:break;case 4:}break;case 3:switch(this.lastState){case 0:this.resetStatus();break;case 1:this.resetStatus();break;case 2:this.resetStatus();break;case 3:break;case 4:this.resetStatus()}break;case 4:switch(this.lastState){case 0:this.resetStatus();break;case 1:if(!this.inProgress){setTimeout(()=>{this.verifyConnection(e=>{e?(this._wifiService.sendError(e),this.resetStatus(),u.default.instance.disconnect((e,t)=>{e?console.log(e):console.log("Disconnecting. After Authentication, Device went to DISCONECTED")})):this.resetStatus()})},i);break}case 2:if(!this.inProgress){setTimeout(()=>{this.verifyConnection(e=>{e?(this._wifiService.sendError(e),this.resetStatus(),u.default.instance.disconnect((e,t)=>{e?console.log(e):console.log("Disconnecting. After 4WAY, Device went to DISCONNECTED")})):this.resetStatus()})},i);break}break;case 3:this.connected=0,this.inProgress=!1,this.connecting=0,this.resetStatus()}}if(this.lastState!==e){let i={newState:t[e],oldState:t[this.lastState]};this._wifiService.sendSocketData("state-change",i),this._wifiService.emit("state-change",i),this._wifiService.log.info("state-change:",i)}3!==e||3===this.lastState||this.inProgress||setTimeout(()=>{this.verifyConnection(e=>{e?(this._wifiService.sendError(e),this.resetStatus(),u.default.instance.disconnect((e,t)=>{e&&console.log(e)})):this.resetStatus()})},i),this.lastState=e,3===this.lastState&&this.resetStatus()}resetStatus(){1===this.connected?(this.connecting=0,this.statusListen(15e3),this.activeScan.stopListener()):1===this.connecting?(this.connecting=0,this.statusListen(1e3),this.scanListen(2e4)):(this.statusListen(5e3),this.scanListen(15e3))}statusCB(e,t){if(e)return void console.log("Error Detected: "+e);let i=0;t.indexOf("SCANNING")>-1?i=0:t.indexOf("AUTHENTICATING")>-1?i=1:t.indexOf("4WAY_HANDSHAKE")>-1?i=2:t.indexOf("COMPLETED")>-1?i=3:t.indexOf("DISCONNECTED")>-1&&(i=4),this.stateCB(i)}_checkJiboServers(e){if(!this._jiboServerUrl)return void e("Do not have a jibo server url to check!");let t={host:this._jiboServerUrl,path:"/"},i=n.get(t,t=>{let i="";t.on("data",function(e){i+=e}).on("error",function(t){e(t.message)}).on("end",function(){e()})});i.on("error",t=>{this.syncedTime?e(t):(console.log("Attempting to sync time..."),u.default.instance.syncTime(i=>{i||(this.syncedTime=!0),e(t)}))}),i.on("socket",function(e){e.setTimeout(15e3),e.on("timeout",function(){i.abort()})})}}var m;!function(e){e[e.DHCP=0]="DHCP",e[e.STATIC=1]="STATIC"}(m=i.NetworkType||(i.NetworkType={})),Object.defineProperty(i,"__esModule",{value:!0}),i.default=p},{"../../clients/SystemManagerClient":10,"./scanning/ActiveScan":80,"./scanning/ErrorCode":81,"./scanning/NetworkManager":83,"./scanning/StatusHandler":85,fs:void 0,https:void 0}],79:[function(e,t,i){"use strict";const n=e("jibo-service-framework"),s=e("./WifiManager"),o=e("../../utils/Log"),r=e("async"),a=e("./scanning/ErrorCode");let c=0;class u extends n.HTTPWSService{constructor(e,t){if(super("wifi",e,t),this.options=e,u._instance)throw new Error("WifiService is a singleton");this.log=o.createLog("ssm-wifi-service"),u._instance=this,this._wifiMgr=new s.default(this),this._eventSocket=null,this.log.info("Initialized")}static createInstance(e,t){return new u(e,t)}static get instance(){return u._instance}init(e){super.init(t=>{return t?e(t):void this._wifiMgr.init(e)})}routes(e){super.routes(e),e.post("/remove_all",(e,t)=>{this._onRemoveAll(e,t)}),e.post("/remove_network",(e,t)=>{this._onRemoveNetwork(e,t)}),e.post("/select_network",(e,t)=>{this._onSelectNetwork(e,t)}),e.post("/add_network",(e,t)=>{this._onAddNetwork(e,t)}),e.post("/get_current_network",(e,t)=>{this._onGetCurrentNetwork(e,t)}),e.post("/get_saved_networks",(e,t)=>{this._onGetSavedNetworks(e,t)}),e.post("/verify_connection",(e,t)=>{this._onVerifyConnection(e,t)})}onConnection(e){super.onConnection(e),"/wifi_events"===e.upgradeReq.url&&(this._eventSocket=e)}onClose(e){e===this._eventSocket&&(this._eventSocket=void 0)}onMessage(e,t){}sendSocketData(e,t){if(this._eventSocket){let i={eventName:e,data:t};this.sendWsJson(this._eventSocket,i)}}sendError(e){this.sendSocketData("error",e),this.log.info("error:",e)}verifyConnection(e){this._wifiMgr.verifyConnection(e)}getScanResults(e){this._wifiMgr.scan((t,i)=>{t?e(new Error("Error scanning: "+t)):this._wifiMgr.getScanResults((t,i)=>{if(t)return e(new Error("Error scanning results:"+t));let n=i.split("\n");if(n.length>1){n.shift();for(let t=n.length-1;t>=0&&!n[t];--t)n.pop();e(null,n)}else e(null,[])})})}getCurrentNetwork(e){this._wifiMgr.status((t,i)=>{if(t)e(t);else{let t={ssid:"",strength:0,speed:0,ip_address:""};if(i.indexOf("wpa_state=COMPLETED")>-1){let n=i.split("\n"),s=n.length;for(let o=0;o<s;o++)n[o].indexOf("ssid=")>-1?t.ssid=n[o].split("=")[1]:n[o].indexOf("ip_address=")>-1&&(t.ip_address=n[o].split("=")[1]);this._wifiMgr.pollStats((i,n)=>{if(i)e(i);else{let i=n.split("\n"),s=null,o=i.length;for(let r=0;r<o;r++)i[r].indexOf("RSSI")>-1?s||(s=parseInt(i[r].split("=")[1])):i[r].indexOf("AVG_RSSI")>-1?s=parseInt(i[r].split("=")[1]):i[r].indexOf("LINKSPEED")>-1&&(t.speed=parseInt(i[r].split("=")[1]));s&&(s>-50?t.strength=100:t.strength=2*(s+100)),e(null,t)}})}else e(new Error("Not Connected"))}})}_onVerifyConnection(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{this._wifiMgr.verifyConnection(e=>{return e?this.sendJson(t,e,500):void this.sendJson(t,{status:"OK"})})})}_onRemoveAll(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{this._removeAllNetworks(e=>{return e?this.sendJson(t,{error:e.stack},500):void this.sendJson(t,{status:"OK"})})})}_onRemoveNetwork(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{let e;try{e=JSON.parse(i),this._removeNetwork(e.ssid,e=>{return e?this.sendJson(t,{error:e.stack},500):void this.sendJson(t,{status:"OK"})})}catch(e){console.warn("Wifi service cannot parse ",i),this.sendJson(t,{status:"error",message:"could not parse json",json:i},400)}})}_onSelectNetwork(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{let e;try{e=JSON.parse(i),this._selectNetwork(e.ssid,e=>{return e?this.sendJson(t,{error:e.stack},500):void this.sendJson(t,{status:"OK"})})}catch(e){console.warn("Wifi service cannot parse ",i),this.sendJson(t,{status:"error",message:"could not parse json",json:i},400)}})}_onAddNetwork(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{let e;try{e=JSON.parse(i),this._addNetwork(e.networkData,e.minVerifyTime,e=>{return e?this.sendJson(t,e,500):void this.sendJson(t,{status:"OK"})})}catch(e){console.warn("Wifi service cannot parse ",i),this.sendJson(t,{status:"error",message:"could not parse json",json:i},400)}})}_onGetCurrentNetwork(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{this.getCurrentNetwork((e,i)=>{return e?this.sendJson(t,{error:e.stack},500):void this.sendJson(t,{status:"OK",stats:i})})})}_onGetSavedNetworks(e,t){let i="";e.on("data",e=>i+=e),e.on("end",()=>{this._wifiMgr.getSavedNetworks((e,i)=>{return e?this.sendJson(t,{error:e.stack},500):void this.sendJson(t,{status:"OK",networks:i})})})}_removeAllNetworks(e){this._wifiMgr.getSavedNetworks((t,i)=>{if(i){let t=[],n=i.length;for(let s=0;s<n;s++)t.push(e=>{this._wifiMgr.removeNetwork(i[s].index,i[s].ssid,e)});r.parallel(t,t=>{e(t)})}})}_removeNetwork(e,t){this._wifiMgr.getSavedNetworks((i,n)=>{if(i)return t(i);let s=this._getNetworkID(e,n);s?this._wifiMgr.removeNetwork(s,e,e=>{t(e)}):t(new Error(e+" is not currently saved"))})}_selectNetwork(e,t){this._wifiMgr.getSavedNetworks((i,n)=>{if(i)return t(i);let s=this._getNetworkID(e,n);s?this._wifiMgr.selectNetwork(s,null,e=>{e?t(e):this._wifiMgr.saveNetwork(s,e=>{t(e)})}):t(new Error(e+" is not currently saved"))})}_getNetworkID(e,t){let i=null;const n=t.length;for(let s=0;s<n;s++)if(t[s].ssid===e){i=t[s].index;break}return i}_addNetwork(e,t,i){if(this._wifiMgr.inProgress){let n=setInterval(()=>{this._wifiMgr.inProgress?console.log("Currently in process of adding network. Please wait!"):(clearInterval(n),this._addNetwork(e,t,i))},1e3)}else{if(this._wifiMgr.inProgress=!0,!e.hasOwnProperty("ssid")||!e.ssid.length){this._wifiMgr.inProgress=!1;let e=new a.default(6,"No SSID Specified");return this.sendError(e),void i(e)}if(0===e.pswd.length)e.security="OPEN";else{if(!(e.pswd.length>7&&e.pswd.length<64)){this._wifiMgr.inProgress=!1;let e=new a.default(5,"Invalid password length! Must be at least 8 characters and less than 64 characters");return this.sendError(e),void i(e)}e.security="WPA-PSK"}this._wifiMgr.getSavedNetworks((n,s)=>{if(n)return i(new a.default(666,n.message));let o=this._getNetworkID(e.ssid,s);o?(i(new a.default(666,e.ssid+" already exists...not adding")),this._wifiMgr.inProgress=!1):this._wifiMgr.addNetwork((n,s)=>{if(n)this._wifiMgr.inProgress=!1,i(new a.default(666,"No access to wpa_cli "+n));else{let n=s.match(/\d+/)[0];this._wifiMgr.scan((s,o)=>{s?(this._wifiMgr.inProgress=!1,i(new a.default(666,"Error Scanning! "+s))):this._wifiMgr.getScanResults((s,o)=>{s?(this._wifiMgr.inProgress=!1,i(new a.default(666,"Error retrieving Scan Results..."))):(o.indexOf(e.ssid)>-1?(console.log("network is NOT hidden!"),e.hidden=0):(console.log("network is hidden!"),e.hidden=1),this._setNetwork(n,e,s=>{s?(this._wifiMgr.inProgress=!1,i(new a.default(1,"Could not set network! "+s))):this._wifiMgr.saveNetwork(n,s=>{s?(this._wifiMgr.inProgress=!1,i(new a.default(666,"Could not save network! "+s))):this._wifiMgr.selectNetwork(n,e,e=>{e?(this._wifiMgr.inProgress=!1,i(new a.default(1,"Could not select network! "+e))):this._wifiMgr.saveNetwork(n,e=>{if(e)this._wifiMgr.inProgress=!1,i(new a.default(666,"Could not save network! "+e));else if(t&&t>0){console.log("Verifying network..."),c=0;let e=setInterval(()=>{c++},1e3);this._verify(t,t=>{clearInterval(e),c=0,this._wifiMgr.inProgress=!1,t?(this.sendError(t),this._wifiMgr.disconnect(()=>{i(t)})):i()})}else this._wifiMgr.inProgress=!1,i()})})})}))})})}})})}}_setNetwork(e,t,i){let n={ssid:t.ssid,psk:null,security:null,hidden:null};this._wifiMgr.setNetwork(e,n,(n,s)=>{if(n)i(n);else if(console.log("Successfully added SSID "+t.ssid),t.pswd.length>0){let n={ssid:null,psk:t.pswd,security:null,hidden:null};this._wifiMgr.setNetwork(e,n,(n,s)=>{if(n)i(n);else{console.log("Successfully added PSK");let n={ssid:null,psk:null,security:t.security,hidden:null};this._wifiMgr.setNetwork(e,n,(n,s)=>{if(n)i(n);else if(console.log("Successfully added Security"),1===t.hidden){let n={ssid:null,psk:null,security:null,hidden:t.hidden};this._wifiMgr.setNetwork(e,n,(e,t)=>{e?i(new Error("Failed to set hidden SSID!")):(console.log("Successfully set (hidden) network!"),i())})}else console.log("Successfully set network!"),i()})}})}else if(0===t.pswd.length){let n={ssid:null,psk:null,security:t.security,hidden:null};this._wifiMgr.setNetwork(e,n,(n,s)=>{if(n)i(n);else if(1===t.hidden){let n={ssid:null,psk:null,security:null,hidden:t.hidden};this._wifiMgr.setNetwork(e,n,(e,t)=>{e?i(new Error("Failed to set hidden SSID!")):i()})}else i()})}else i(new Error("Invalid PSK Settings!"))})}_verify(e,t){this._wifiMgr.verifyConnection(i=>{i?c>e?t(i):this._verify(e,t):t()})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=u},{"../../utils/Log":88,"./WifiManager":78,"./scanning/ErrorCode":81,async:void 0,"jibo-service-framework":void 0}],80:[function(e,t,i){"use strict";const n=e("./Scan"),s=e("../../../clients/SystemManagerClient");class o extends n.default{constructor(){super(),this.listener=null}scan(e){s.default.instance.scan(e)}listen(e,t){null===this.listener&&this.interval!==e?this.listener=setInterval(()=>{s.default.instance.scan((e,i)=>{e?t(e,i):t(e,i)})},e):this.interval!==e?(clearInterval(this.listener),this.listener=setInterval(()=>{s.default.instance.scan((e,i)=>{e?t(e,i):t(e,i)})},e)):t(null,null),this.interval=e}stopListener(){clearInterval(this.listener)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=o},{"../../../clients/SystemManagerClient":10,"./Scan":84}],81:[function(e,t,i){"use strict";class n{constructor(e,t){this.code=e,t&&(this.description=t)}}i.ErrorCode=n,Object.defineProperty(i,"__esModule",{value:!0}),i.default=n},{}],82:[function(e,t,i){"use strict";class n{constructor(){this.container={}}addNewNetworkProfile(e){if(4===e.split("\t").length){let t=new s(e);null===t.ssid||this.container.hasOwnProperty(t.ssid)||(this.container[t.ssid]=t)}}getBestNetwork(e){let t=new s("a"),i=!1;for(let n in this.container)1!==this.container[n].active||this.container[n].tried||this.container[n].rssi<t.rssi&&(t=this.container[n],i=!0);if(!i)for(let n in this.container)this.container[n].tried=!1;e(t)}updateWiFiProfiles(e,t){let i=e.split("\n");for(let n=0;n<i.length;++n){let e=i[n].split("\t");5===e.length&&this.container.hasOwnProperty(e[4])&&(this.container[e[4]].rssi=e[2],this.container[e[4]].active=1,this.container[e[4]].freq=e[1])}t(this.container)}}i.NetworkContainer=n;class s{constructor(e){if(this.ssid=null,this.rssi=null,this.freq=null,this.active=null,this.networkID=null,this.tried=!1,e.charAt(0)>="0"&&e.charAt(0)<="9"){let t=e.split("\t");this.ssid=t[1],this.networkID=t[0]}}}i.NetworkProfile=s},{}],83:[function(e,t,i){"use strict";const n=e("./NetworkHelper"),s=e("../../../clients/SystemManagerClient");class o{constructor(){this.networkContainer=new n.NetworkContainer}getNetworks(e){s.default.instance.listNetworks(e)}getContainer(e){e(this.networkContainer)}updateProfiles(e,t){let i=this,n=e.split("\n");for(let s=0;s<n.length;++s)this.networkContainer.addNewNetworkProfile(n[s]);for(let o in this.networkContainer.container)e.indexOf(o)===-1&&delete this.networkContainer.container[o];t(i.networkContainer)}connectToNetwork(e){console.log("y")}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=o},{"../../../clients/SystemManagerClient":10,"./NetworkHelper":82}],84:[function(e,t,i){"use strict";const n=e("../../../clients/SystemManagerClient");class s{scanResults(e){n.default.instance.scanResults(e)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"../../../clients/SystemManagerClient":10}],85:[function(e,t,i){"use strict";const n=e("../../../clients/SystemManagerClient");class s{constructor(){this.listener=null}status(e){n.default.instance.wifiStatus(e)}listen(e,t){null===this.listener?this.listener=setInterval(()=>{n.default.instance.wifiStatus(t)},e):(clearInterval(this.listener),this.listener=setInterval(()=>{n.default.instance.wifiStatus(t)},e))}StopListener(){clearInterval(this.listener)}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{"../../../clients/SystemManagerClient":10}],86:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))(function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?s(e.value):new i(function(t){t(e.value)}).then(r,a)}c((n=n.apply(e,t||[])).next())})};class s{static get(e){return n(this,void 0,void 0,function*(){return new Promise((t,i)=>{e((e,n)=>{return e?i(e):void t(n)})})})}static get2(e){return n(this,void 0,void 0,function*(){return new Promise(t=>{e(e=>{t(e)})})})}static all(e,t){return n(this,void 0,void 0,function*(){let i=[];for(;e.length>0;){const n=yield Promise.all(e.splice(0,t));i=i.concat(n)}return i})}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=s},{}],87:[function(e,t,i){"use strict";class n{constructor(){this.initFunctions={},this.initialized=!1}register(e,t){return this.initialized&&(console.warn(`BackgroundUtilsManager is registering ${t} after initialization. Please consider how/when code is being included.`),e()),this.initFunctions.hasOwnProperty(t)?void console.error(`BackgroundUtilsManager is registering ${t} when that id has already been used. This callback will not be called.`):void(this.initFunctions[t]=e)}initAll(e){const t=Object.keys(this.initFunctions);for(let i=0;i<t.length;++i){const n=t[i],s=this.initFunctions[n];try{s(e)}catch(e){console.error(`Error when initializing ${n}:`),console.log("%c","color:red",e)}}}}Object.defineProperty(i,"__esModule",{value:!0}),i.default=new n},{}],88:[function(e,t,i){"use strict";function n(e,t){let i=new s(e);return i.toSyslog(),i}const s=e("jibo-log");i.createLog=n},{"jibo-log":void 0}],89:[function(e,t,i){"use strict";const n=e("jibo"),s=e("../services/wifi-service/WifiService"),o=e("../services/kb-service/KBService"),r=e("../clients/BodyClient"),a="/ota",c="OTA10",u="OTA1",l="OTA4",d="OTAX";class h{constructor(e){if(this._log=null,h._instance)throw new Error("OTAUpdater is a singleton");this._log=e,h._instance=this,this._resetDLStatus(),this._log.info("Initialized OTAUpdater")}static createInstance(e){return h.instance?h.instance:new h(e)}static get instance(){return h._instance}isReady(e){const t="http://localhost:"+o.default.instance.options.port;let i=null;try{i=n.kb.createModel(a,t)}catch(t){return void e(t)}i.loadRoot((t,i)=>{if(t||!i||!i.data){const t=new Error("Couldn't load OTA root KB on attempt install");return this._doLog(t),e(t)}if(r.default.instance.pluggedIn)s.default.instance.getCurrentNetwork((t,n)=>{if(t||!n||void 0===n.ssid){i.data.error=u;let n=new Error(i.data.error+": Couldn't start OTA process cause no WiFi: "+t);this._doLog(n),i.save(t=>{return t&&(n=new Error(i.data.error+": Couldn't save OTA wifi error status"),this._doLog(n)),e(n)})}else s.default.instance.verifyConnection(t=>{if(t){t.code?i.data.error=1===t.code?u:l:i.data.error=d;let n=new Error(i.data.error+": Couldn't start OTA process cause no internet: "+t);this._doLog(n),i.save(t=>{return t&&(n=new Error(i.data.error+": Couldn't save OTA internet error status"),this._doLog(n)),e(n)})}else e(null,i)})});else{i.data.error=c;let t=new Error(i.data.error+": Couldn't start OTA process cause not plugged in");i.save(n=>{return n&&(t=new Error(i.data.error+": Couldn't save OTA plug error status"),this._doLog(t)),e(t)})}})}getDownloadStatus(e){return 0===this._downloadStatus.updates.length?e(new Error("OTA download is not running")):void e(null,this._downloadStatus)}downloadAndInstall(e){this._resetDLStatus(),this._doLog("Starting ota update!"),this.isReady((t,i)=>{return t?void e(t):(e(),void this._startNextDownload((e,t)=>{return e?(this._resetDLStatus(),this._doLog(e),void s.default.instance.verifyConnection(e=>{e&&e.code?i.data.error=1===e.code?u:l:i.data.error=d,i.save(e=>{e&&this._doLog("Couldn't save OTA download error status")})})):(i.data.updatesAvailable=!1,void i.save(e=>{if(e){const e=new Error("Couldn't save OTA post-downloading status");return void this._doLog(e)}this.isReady(e=>{e||(this._doLog("Starting ota installation! C-ya on the flip side."),n.systemManager.installUpdates({ids:t},e=>{if(e)return void this._doLog(e)}))})}))}))})}_startNextDownload(e){n.systemManager.checkForUpdates((t,i)=>{if(this._resetDLStatus(),t||!i){const i=t?t:"Service temporarily unavailable.";return e(new Error(i))}const s=i.length;if(0===s)return e(new Error("No updates found."));let o=[],r=[];for(let a=0;a<s;a++)i[a].downloaded?r.push(i[a].id):0===o.length&&o.push(i[a].id);o.length>0?(this._doLog("Starting ota download: "+o),this._downloadStatus.updates=i.slice(),n.systemManager.downloadUpdates({ids:o},(t,i)=>{if(this._downloadStatus.status=Object.assign({},i),t||"failed"===i.status||i.error){this._resetDLStatus();const n=t||i.reason||i.error;return e(new Error("Error downloading OTA updates: "+n))}"finished"===i.status&&this._startNextDownload(e)})):(this._resetDLStatus(),e(null,r))})}_resetDLStatus(){this._downloadStatus={updates:[],status:null}}_doLog(e){this._log&&this._log.info(e)}}h._instance=null,Object.defineProperty(i,"__esModule",{value:!0}),i.default=h},{"../clients/BodyClient":8,"../services/kb-service/KBService":42,"../services/wifi-service/WifiService":79,jibo:void 0}],90:[function(e,t,i){"use strict";function n(e,t){return e?void s.systemManager.getVersion((i,n)=>{if(i)return void t(i);let s=void 0;o.satisfies(n,e)||(s="Current SSM version requires platform version "+e+" but your current version is "+n+"!"),t(s)}):void t()}const s=e("jibo");let o=e("semver");i.versionCheck=n},{jibo:void 0,semver:void 0}],91:[function(e,t,i){"use strict";function n(){e("./main-process/index")}let s=e("ws-without-native");GLOBAL.WebSocket=s;const o=e("./Factory"),r=e("jibo-service-framework"),a=e("./services/tts-service/TTSService"),c=e("./services/lps-service/LPSService"),u=e("./services/notifications-service/NotificationsService"),l=e("./services/asr-service/ASRService"),d=e("./services/body-service/BodyService"),h=e("./services/listen-service/ListenService"),f=e("./services/nlu-service/NLUService"),p=e("./services/listen-service/RuleManager"),m=e("./services/listen-service/GlobalListen"),g=e("./services/skills-service/SkillsService"),v=e("./services/media-service/MediaService"),_=e("./services/media-service/MediaManagerService"),S=e("./services/media-proxy/MediaProxyService"),b=e("./services/kb-service/KBService"),y=e("./services/kb-service/ASRLoopInformer"),w=e("./services/wifi-service/WifiService"),k=e("./services/scheduler-service/SchedulerService"),E=e("./services/dev-shell/DevShell"),R=e("./init/GetConfig"),T=e("./services/error-service/ErrorService");Object.defineProperty(i,"__esModule",{value:!0}),i.default={Factory:o.default,TTSService:a.default,RegistryClient:r.RegistryClient,HTTPWSService:r.HTTPWSService,HTTPService:r.HTTPService,NLUService:f.default,LPSService:c.default,NotificationsService:u.default,ASRService:l.default,BodyService:d.default,ListenService:h.default,SkillsService:g.default,RuleManager:p.default,GlobalListen:m.default,MediaService:v.default,MediaManagerService:_.default,MediaProxyService:S.default,KBService:b.default,ASRLoopInformer:y.default,WifiService:w.default,SchedulerService:k.default,createProxyServer:E.createProxyServer,GetConfig:R.default,ErrorService:T.default},i.start=n},{"./Factory":2,"./init/GetConfig":22,"./main-process/index":24,"./services/asr-service/ASRService":27,"./services/body-service/BodyService":30,"./services/dev-shell/DevShell":32,"./services/error-service/ErrorService":36,"./services/kb-service/ASRLoopInformer":40,"./services/kb-service/KBService":42,"./services/listen-service/GlobalListen":50,"./services/listen-service/ListenService":51,"./services/listen-service/RuleManager":52,"./services/lps-service/LPSService":57,"./services/media-proxy/MediaProxyService":59,"./services/media-service/MediaManagerService":60,"./services/media-service/MediaService":61,"./services/nlu-service/NLUService":62,"./services/notifications-service/NotificationsService":64,"./services/scheduler-service/SchedulerService":67,"./services/skills-service/SkillsService":72,"./services/tts-service/TTSService":77,"./services/wifi-service/WifiService":79,"jibo-service-framework":void 0,"ws-without-native":void 0}]},{},[91])(91)}); |