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)
|
||
|
|
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
|
||
|
|
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;brea
|
||
|
|
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.mockErrorR
|
||
|
|
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 med
|
||
|
|
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.inc
|
||
|
|
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=[];Obj
|
||
|
|
`)}),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:
|
||
|
|
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
|