@sebbo2002/node-pyatv 8.0.1-develop.5 → 8.1.0-develop.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- "use strict";var M=Object.create;var F=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var z=(t,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!Y.call(t,n)&&n!==s&&F(t,n,{get:()=>e[n],enumerable:!(i=B(e,n))||i.enumerable});return t};var Q=(t,e,s)=>(s=t!=null?M(H(t)):{},z(e||!t||!t.__esModule?F(s,"default",{value:t,enumerable:!0}):s,t));var X=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,y=X();var $=Q(require("semver"),1),C=require("path"),J=require("url"),G=require("fs");var b=(n=>(n.music="music",n.tv="tv",n.video="video",n.unknown="unknown",n))(b||{}),O=(o=>(o.idle="idle",o.loading="loading",o.paused="paused",o.playing="playing",o.seeking="seeking",o.stopped="stopped",o))(O||{}),k=(i=>(i.all="all",i.track="track",i.off="off",i))(k||{}),x=(i=>(i.albums="albums",i.songs="songs",i.off="off",i))(x||{}),_=(s=>(s.on="on",s.off="off",s))(_||{}),D=(i=>(i.focued="focused",i.focused="focused",i.unfocused="unfocused",i))(D||{});var j=(u=>(u.down="down",u.home="home",u.homeHold="home_hold",u.left="left",u.menu="menu",u.next="next",u.pause="pause",u.play="play",u.playPause="play_pause",u.previous="previous",u.right="right",u.select="select",u.skipBackward="skip_backward",u.skipForward="skip_forward",u.stop="stop",u.suspend="suspend",u.topMenu="top_menu",u.up="up",u.volumeDown="volume_down",u.volumeUp="volume_up",u.wakeup="wakeup",u.turnOff="turn_off",u.turnOn="turn_on",u))(j||{});var U=require("child_process");var E=[];function m(){let t="?";for(let e=0;e<1e3;e+=1)if(t=Math.round(Math.random()*(e+6)*36).toString(36).toUpperCase(),!E.includes(t)){E.push(t);break}return t}function c(t){t&&E.includes(t)&&E.splice(E.indexOf(t),1)}function d(t,e,s){if(s.debug){let i=typeof s.debug=="function"?s.debug:console.log,n=!process.env.NO_COLOR&&!s.noColors,r=[n?"\x1B[0m":"",n?"\x1B[90m":"","[node-pyatv][",n?"\x1B[37m":"",t,n?"\x1B[90m":"","] ",n?"\x1B[0m":"",e];i.apply(null,[r.join("")])}}function Z(t,e){return t==="atvremote"&&typeof e.atvremotePath=="string"?e.atvremotePath:t==="atvscript"&&typeof e.atvscriptPath=="string"?e.atvscriptPath:t}function L(t,e,s,i){let n=Z(e,i),r=typeof i.spawn=="function"?i.spawn:U.spawn;d(t,`${n} ${s.join(" ")}`,i);let o=r(n,s,{env:process.env}),a=h=>d(t,`stdout: ${String(h).trim()}`,i),p=h=>d(t,`stderr: ${String(h).trim()}`,i),l=h=>d(t,`error: ${String(h).trim()}`,i),V=h=>{d(t,`${n} exited with code: ${h}`,i),o.stdout&&o.stdout.off("data",a),o.stderr&&o.stderr.off("data",p),o.off("error",l),o.off("close",V)};return o.stdout&&o.stdout.on("data",a),o.stderr&&o.stderr.on("data",p),o.on("error",l),o.on("close",V),o}async function g(t,e,s,i){let n={stdout:"",stderr:"",code:0};if(await new Promise((r,o)=>{let a=L(t,e,s,i),p=v=>n.stdout+=String(v).trim(),l=v=>n.stderr+=String(v).trim(),V=v=>o(v instanceof Error?v:new Error(String(v))),h=v=>{n.code=v,a.stdout&&a.stdout.off("data",p),a.stderr&&a.stderr.off("data",l),a.off("error",V),a.off("close",h),r(void 0)};a.stdout&&a.stdout.on("data",p),a.stderr&&a.stderr.on("data",l),a.on("error",V),a.on("close",h)}),n.stderr.length>0){let r=`Unable to execute request ${t}: ${n.stderr}`;throw d(t,r,i),new Error(r)}if(e==="atvscript")try{return i.allowMultipleResponses?n.stdout.split(`
2
- `).filter(r=>r.trim().length>0).map(r=>JSON.parse(r)):JSON.parse(n.stdout)}catch(r){let o=`Unable to parse result ${t} json: ${r}`;throw d(t,o,i),new Error(o)}return n.stdout}function f(t={}){let e=[];return t.hosts?e.push("-s",t.hosts.join(",")):t.host&&e.push("-s",t.host),t.id&&e.push("-i",t.id),t.protocol&&e.push("--protocol",t.protocol),t.dmapCredentials&&e.push("--dmap-credentials",t.dmapCredentials),t.mrpCredentials&&e.push("--mrp-credentials",t.mrpCredentials),t.airplayCredentials&&e.push("--airplay-credentials",t.airplayCredentials),t.companionCredentials&&e.push("--companion-credentials",t.companionCredentials),t.raopCredentials&&e.push("--raop-credentials",t.raopCredentials),e}function P(t,e,s,i,n){if(typeof t[s]=="string"){e[i]=t[s];return}n(`No ${i} value found in input (${JSON.stringify(t)})`)}function T(t,e,s){let i=r=>d(e,r,s),n={dateTime:null,hash:null,mediaType:null,deviceState:null,title:null,artist:null,album:null,genre:null,totalTime:null,position:null,shuffle:null,repeat:null,app:null,appId:null,powerState:null,volume:null,focusState:null,outputDevices:null};if(!t||typeof t!="object")return n;if(t.exception){let r="Got pyatv Error: "+t.exception;throw t.stacktrace&&(r+=`
1
+ "use strict";var B=Object.create;var L=Object.defineProperty;var q=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var Q=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of H(e))!z.call(s,n)&&n!==t&&L(s,n,{get:()=>e[n],enumerable:!(i=q(e,n))||i.enumerable});return s};var X=(s,e,t)=>(t=s!=null?B(Y(s)):{},Q(e||!s||!s.__esModule?L(t,"default",{value:s,enumerable:!0}):t,s));var Z=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,y=Z();var C=X(require("semver"),1),j=require("path"),J=require("url"),M=require("fs");var b=(n=>(n.music="music",n.tv="tv",n.video="video",n.unknown="unknown",n))(b||{}),O=(o=>(o.idle="idle",o.loading="loading",o.paused="paused",o.playing="playing",o.seeking="seeking",o.stopped="stopped",o))(O||{}),k=(i=>(i.all="all",i.track="track",i.off="off",i))(k||{}),x=(i=>(i.albums="albums",i.songs="songs",i.off="off",i))(x||{}),_=(t=>(t.on="on",t.off="off",t))(_||{}),R=(i=>(i.focued="focused",i.focused="focused",i.unfocused="unfocused",i))(R||{});var F=(l=>(l.down="down",l.home="home",l.homeHold="home_hold",l.left="left",l.menu="menu",l.next="next",l.pause="pause",l.play="play",l.playPause="play_pause",l.previous="previous",l.right="right",l.select="select",l.skipBackward="skip_backward",l.skipForward="skip_forward",l.stop="stop",l.suspend="suspend",l.topMenu="top_menu",l.up="up",l.volumeDown="volume_down",l.volumeUp="volume_up",l.wakeup="wakeup",l.turnOff="turn_off",l.turnOn="turn_on",l))(F||{});var U=require("child_process");var D=[];function m(){let s="?";for(let e=0;e<1e3;e+=1)if(s=Math.round(Math.random()*(e+6)*36).toString(36).toUpperCase(),!D.includes(s)){D.push(s);break}return s}function c(s){s&&D.includes(s)&&D.splice(D.indexOf(s),1)}function p(s,e,t){if(t.debug){let i=typeof t.debug=="function"?t.debug:console.log,n=!process.env.NO_COLOR&&!t.noColors,r=[n?"\x1B[0m":"",n?"\x1B[90m":"","[node-pyatv][",n?"\x1B[37m":"",s,n?"\x1B[90m":"","] ",n?"\x1B[0m":"",e];i.apply(null,[r.join("")])}}function K(s,e){return s==="atvremote"&&typeof e.atvremotePath=="string"?e.atvremotePath:s==="atvscript"&&typeof e.atvscriptPath=="string"?e.atvscriptPath:s}function I(s,e,t,i){let n=K(e,i),r=typeof i.spawn=="function"?i.spawn:U.spawn;p(s,`${n} ${t.join(" ")}`,i);let o=r(n,t,{env:process.env}),a=h=>p(s,`stdout: ${String(h).trim()}`,i),d=h=>p(s,`stderr: ${String(h).trim()}`,i),u=h=>p(s,`error: ${String(h).trim()}`,i),V=h=>{p(s,`${n} exited with code: ${h}`,i),o.stdout&&o.stdout.off("data",a),o.stderr&&o.stderr.off("data",d),o.off("error",u),o.off("close",V)};return o.stdout&&o.stdout.on("data",a),o.stderr&&o.stderr.on("data",d),o.on("error",u),o.on("close",V),o}async function P(s,e,t,i){let n={stdout:"",stderr:"",code:0};if(await new Promise((r,o)=>{let a=I(s,e,t,i),d=v=>n.stdout+=String(v).trim(),u=v=>n.stderr+=String(v).trim(),V=v=>o(v instanceof Error?v:new Error(String(v))),h=v=>{n.code=v,a.stdout&&a.stdout.off("data",d),a.stderr&&a.stderr.off("data",u),a.off("error",V),a.off("close",h),r(void 0)};a.stdout&&a.stdout.on("data",d),a.stderr&&a.stderr.on("data",u),a.on("error",V),a.on("close",h)}),n.stderr.length>0){let r=`Unable to execute request ${s}: ${n.stderr}`;throw p(s,r,i),new Error(r)}if(e==="atvscript")try{return i.allowMultipleResponses?n.stdout.split(`
2
+ `).filter(r=>r.trim().length>0).map(r=>JSON.parse(r)):JSON.parse(n.stdout)}catch(r){let o=`Unable to parse result ${s} json: ${r}`;throw p(s,o,i),new Error(o)}return n.stdout}function g(s={}){let e=[];return s.hosts?e.push("-s",s.hosts.join(",")):s.host&&e.push("-s",s.host),s.id&&e.push("-i",s.id),s.protocol&&e.push("--protocol",s.protocol),s.dmapCredentials&&e.push("--dmap-credentials",s.dmapCredentials),s.mrpCredentials&&e.push("--mrp-credentials",s.mrpCredentials),s.airplayCredentials&&e.push("--airplay-credentials",s.airplayCredentials),s.companionCredentials&&e.push("--companion-credentials",s.companionCredentials),s.raopCredentials&&e.push("--raop-credentials",s.raopCredentials),e}function f(s,e,t,i,n){if(typeof s[t]=="string"){e[i]=s[t];return}n(`No ${i} value found in input (${JSON.stringify(s)})`)}function E(s,e,t,i,n){if(typeof s[t]=="number"){e[i]=s[t];return}n(`No ${i} value found in input (${JSON.stringify(s)})`)}function T(s,e,t){let i=r=>p(e,r,t),n={dateTime:null,hash:null,mediaType:null,deviceState:null,title:null,artist:null,album:null,genre:null,totalTime:null,position:null,shuffle:null,repeat:null,app:null,appId:null,powerState:null,volume:null,focusState:null,outputDevices:null,contentIdentifier:null,episodeNumber:null,seasonNumber:null,seasonName:null};if(!s||typeof s!="object")return n;if(s.exception){let r="Got pyatv Error: "+s.exception;throw s.stacktrace&&(r+=`
3
3
 
4
4
  pyatv Stacktrace:
5
- `+t.stacktrace),new Error(r)}if(typeof t.datetime=="string"){let r=new Date(t.datetime);isNaN(r.getTime())?i(`Invalid datetime value ${t.datetime}, ignore attribute`):n.dateTime=r}else i(`No datetime value found in input (${JSON.stringify(t)})`);return P(t,n,"hash","hash",i),typeof t.media_type=="string"?Object.keys(b).map(o=>String(o)).includes(t.media_type)?n.mediaType=b[t.media_type]:i(`Unsupported mediaType value ${t.media_type}, ignore attribute`):i(`No mediaType value found in input (${JSON.stringify(t)})`),typeof t.device_state=="string"?Object.keys(O).map(o=>String(o)).includes(t.device_state)?n.deviceState=O[t.device_state]:i(`Unsupported deviceState value ${t.device_state}, ignore attribute`):i(`No deviceState value found in input (${JSON.stringify(t)})`),P(t,n,"title","title",i),P(t,n,"artist","artist",i),P(t,n,"album","album",i),P(t,n,"genre","genre",i),typeof t.total_time=="number"?n.totalTime=t.total_time:i(`No totalTime value found in input (${JSON.stringify(t)})`),typeof t.position=="number"?n.position=t.position:i(`No position value found in input (${JSON.stringify(t)})`),typeof t.shuffle=="string"?Object.keys(x).map(o=>String(o)).includes(t.shuffle)?n.shuffle=x[t.shuffle]:i(`Unsupported shuffle value ${t.shuffle}, ignore attribute`):i(`No shuffle value found in input (${JSON.stringify(t)})`),typeof t.repeat=="string"?Object.keys(k).map(o=>String(o)).includes(t.repeat)?n.repeat=k[t.repeat]:i(`Unsupported repeat value ${t.repeat}, ignore attribute`):i(`No repeat value found in input (${JSON.stringify(t)})`),P(t,n,"app","app",i),P(t,n,"app_id","appId",i),typeof t.power_state=="string"?Object.keys(_).map(o=>String(o)).includes(t.power_state)?n.powerState=_[t.power_state]:i(`Unsupported powerState value ${t.power_state}, ignore attribute`):i(`No powerState value found in input (${JSON.stringify(t)})`),typeof t.volume=="number"&&(n.volume=t.volume),typeof t.focus_state=="string"?Object.keys(D).map(o=>String(o)).includes(t.focus_state)?n.focusState=D[t.focus_state]:i(`Unsupported focusState value ${t.focus_state}, ignore attribute`):i(`No focusState value found in input (${JSON.stringify(t)})`),Array.isArray(t.output_devices)&&(n.outputDevices=t.output_devices),n}function I(t,e){return!!(Array.isArray(t)&&Array.isArray(e)&&JSON.stringify(t.sort((s,i)=>s.identifier<i.identifier?-1:1))===JSON.stringify(e.sort((s,i)=>s.identifier<i.identifier?-1:1)))}var w=class{values;constructor(e){this.values=Object.assign({},e,{key:e.key})}get key(){return this.values.key}get oldValue(){return this.values.old}get newValue(){return this.values.new}get value(){return this.values.new}get device(){return this.values.device}};var W=require("events");var A=class extends W.EventEmitter{options;state;device;pyatv;timeout;listenerState;constructor(e,s,i){super(),this.state=e,this.device=s,this.options=Object.assign({},i),this.listenerState=0}applyStateAndEmitEvents(e){let s=Object.keys(this.state);s=s.filter(i=>!["powerState","focusState","outputDevices","volume"].includes(i)),"powerState"in e&&e.powerState&&(s=["powerState"]),"focusState"in e&&e.focusState&&(s=["focusState"]),"outputDevices"in e&&e.outputDevices&&(s=["outputDevices"]),"volume"in e&&e.volume!==null&&(s=["volume"]),Object.entries(e).find(([i,n])=>!["result","dateTime"].includes(i)&&n!==null)&&s.forEach(i=>{let n=this.state[i],r=e[i];if(n===void 0||r===void 0||n===r||i==="outputDevices"&&I(n,r))return;let o=new w({key:i,old:n,new:r,device:this.device});this.state[i]=e[i];try{this.emit("update:"+i,o),this.emit("update",o)}catch(a){this.emit("error",a)}})}parsePushUpdate(e,s){let i;try{i=JSON.parse(s)}catch(n){let r=`Unable to parse stdout json: ${n}`;d(e,r,this.options),this.emit("error",new Error(r));return}this.applyPushUpdate(i,e),this.listenerState===1&&(this.listenerState=2,this.checkListener())}applyPushUpdate(e,s){try{let i=T(e,s,this.options);this.applyStateAndEmitEvents(i)}catch(i){this.emit("error",i)}}checkListener(){if(this.listenerState===0&&this.listenerCount()===0&&this.timeout)clearTimeout(this.timeout),this.timeout=void 0;else if(this.listenerState===0&&this.listenerCount()>0){let e=m();d(e,`Start listeing to events from device ${this.options.name}`,this.options),this.startListening(e),c(e)}else if([1,2].includes(this.listenerState)&&this.listenerCount()===0){let e=m();d(e,`Stop listening to events from device ${this.options.name}`,this.options),this.stopListening(e).catch(s=>d(e,`Unable to stop listeing: ${s}`,this.options)).finally(()=>c(e))}}startListening(e){if(this.listenerState!==0)return;this.listenerState=1;let s=new Date().getTime(),i=f(this.options);if(this.pyatv=L(e,"atvscript",[...i,"push_updates"],this.options),!this.pyatv)throw new Error("Unable to start listener: Unable to start atvscript");let n=p=>{d(e,`Got error from child process: ${p}`,this.options),this.emit("error",p)},r=p=>{let l=new Error(`Got stderr output from pyatv: ${p}`);d(e,p.toString(),this.options),this.emit("error",l)},o=p=>{String(p).split(`
6
- `).map(l=>l.trim()).filter(Boolean).forEach(l=>{d(e,`> ${l}`,this.options),this.parsePushUpdate(e,l)})},a=p=>{this.pyatv!==void 0&&(this.listenerState=0,d(e,`Listening with atvscript exited with code ${p}`,this.options),this.timeout!==void 0&&(clearTimeout(this.timeout),this.timeout=void 0),this.pyatv.stdout&&this.pyatv.stdout.off("data",o),this.pyatv.stderr&&this.pyatv.stderr.off("data",r),this.pyatv.off("error",n),this.pyatv.off("close",a),this.listenerCount()>0&&new Date().getTime()-s<3e4?(d(e,`Wait 15s and restart listeing to events from device ${this.options.name}`,this.options),this.timeout=setTimeout(()=>{this.checkListener()},15e3)):this.listenerCount()>0&&(d(e,`Restart listeing to events from device ${this.options.name}`,this.options),this.checkListener()),c(e))};this.pyatv.on("error",n),this.pyatv.on("close",a),this.pyatv.stdout&&this.pyatv.stdout.on("data",o),this.pyatv.stderr&&this.pyatv.stderr.on("data",r)}async stopListening(e){if(!(this.listenerState!==1&&this.listenerState!==2)){if(this.listenerState=3,this.pyatv===void 0)throw new Error("Unable to stop listening due to internal error: state is stopping, but there's no child process. This should never happen, please report this.");this.pyatv.stdin&&(d(e,"Pressing enter to close atvscript\u2026",this.options),this.pyatv.stdin.write(`
7
- `),await new Promise(s=>this.timeout=setTimeout(s,250))),this.listenerState===3&&this.pyatv&&this.pyatv.kill(),this.listenerState=0}}addListener(e,s){return super.addListener(e,s),this.checkListener(),this}on(e,s){return super.on(e,s),this.checkListener(),this}once(e,s){return super.once(e,i=>{s(i),setTimeout(()=>this.checkListener(),0)}),this.checkListener(),this}prependListener(e,s){return super.prependListener(e,s),this.checkListener(),this}off(e,s){return super.off(e,s),this.checkListener(),this}removeAllListeners(e){return super.removeAllListeners(e),this.checkListener(),this}removeListener(e,s){return super.removeListener(e,s),this.checkListener(),this}listenerCount(e){return e!==void 0?super.listenerCount(e):this.eventNames().map(s=>this.listenerCount(s)).reduce((s,i)=>s+i,0)}};var N=class{options;state;events;constructor(e){this.options=Object.assign({},e),this.state=T({},"",{}),this.events=new A(this.state,this,this.options)}get name(){return this.options.name}get host(){return this.options.host}get id(){return this.options.id}get allIDs(){return this.options.allIDs}get protocol(){return this.options.protocol}get mac(){return this.options.mac}get model(){return this.options.model}get modelName(){return this.options.modelName}get os(){return this.options.os}get version(){return this.options.version}get services(){return this.options.services}get debug(){return this.options.debug}set debug(e){typeof e=="function"?this.options.debug=e:this.options.debug=!!e||void 0}toJSON(){return{name:this.name,host:this.host,id:this.id,protocol:this.protocol}}toString(){return`NodePyATVDevice(${this.name}, ${this.host})`}async getState(e={}){if(this.state?.dateTime&&new Date().getTime()-this.state.dateTime.getTime()<(e.maxAge||5e3)){let i=null;return this.state.position&&this.state.dateTime&&(i=Math.round(this.state.position+(new Date().getTime()-this.state.dateTime.getTime())/1e3)),Object.assign({},this.state,{position:i})}let s=m();try{let i=f(this.options),n=await g(s,"atvscript",[...i,"playing"],this.options),r=T(n,s,this.options);return this.applyState(r),r}finally{c(s)}}clearState(){this.applyState(T({},"",{}))}applyState(e){this.events.applyStateAndEmitEvents(e)}async getDateTime(e={}){return(await this.getState(e)).dateTime}async getHash(e={}){return(await this.getState(e)).hash}async getMediaType(e={}){return(await this.getState(e)).mediaType}async getDeviceState(e={}){return(await this.getState(e)).deviceState}async getTitle(e={}){return(await this.getState(e)).title}async getArtist(e={}){return(await this.getState(e)).artist}async getAlbum(e={}){return(await this.getState(e)).album}async getGenre(e={}){return(await this.getState(e)).genre}async getTotalTime(e={}){return(await this.getState(e)).totalTime}async getPosition(e={}){return(await this.getState(e)).position}async getShuffle(e={}){return(await this.getState(e)).shuffle}async getRepeat(e={}){return(await this.getState(e)).repeat}async getApp(e={}){return(await this.getState(e)).app}async getAppId(e={}){return(await this.getState(e)).appId}async listApps(){let e=m(),s=f(this.options),i=await g(e,"atvremote",[...s,"app_list"],this.options);if(typeof i!="string"||!i.startsWith("App: "))throw new Error("Unexpected atvremote response: "+i);c(e);let n=/(.+) \(([^)]+)\)$/i;return i.substring(5).split(", App: ").map(o=>{let a=o.match(n);if(a!==null)return{id:a[2],name:a[1],launch:()=>this.launchApp(a[2])}}).filter(Boolean)}async _pressKeyWithScript(e){let s=m(),i=f(this.options),n=await g(s,"atvscript",[...i,e],this.options);if(typeof n!="object"||n.result!=="success")throw new Error(`Unable to parse pyatv response: ${JSON.stringify(n,null," ")}`);c(s)}async _pressKeyWithRemote(e){let s=m(),i=f(this.options);await g(s,"atvremote",[...i,e],this.options),c(s)}async pressKey(e){let s=Object.entries(j).find(([n])=>e===n);if(!s)throw new Error(`Unsupported key value ${e}!`);let i=s[1];["turnOn","turnOff"].includes(e)?await this._pressKeyWithRemote(i):await this._pressKeyWithScript(i)}async down(){await this._pressKeyWithScript("down")}async home(){await this._pressKeyWithScript("home")}async homeHold(){await this._pressKeyWithScript("home_hold")}async left(){await this._pressKeyWithScript("left")}async menu(){await this._pressKeyWithScript("menu")}async next(){await this._pressKeyWithScript("next")}async pause(){await this._pressKeyWithScript("pause")}async play(){await this._pressKeyWithScript("play")}async playPause(){await this._pressKeyWithScript("play_pause")}async previous(){await this._pressKeyWithScript("previous")}async right(){await this._pressKeyWithScript("right")}async select(){await this._pressKeyWithScript("select")}async skipBackward(){await this._pressKeyWithScript("skip_backward")}async skipForward(){await this._pressKeyWithScript("skip_forward")}async stop(){await this._pressKeyWithScript("stop")}async suspend(){await this._pressKeyWithScript("suspend")}async topMenu(){await this._pressKeyWithScript("top_menu")}async up(){await this._pressKeyWithScript("up")}async volumeDown(){await this._pressKeyWithScript("volume_down")}async volumeUp(){await this._pressKeyWithScript("volume_up")}async wakeup(){await this._pressKeyWithScript("wakeup")}async turnOff(){await this._pressKeyWithRemote("turn_off")}async turnOn(){await this._pressKeyWithRemote("turn_on")}async launchApp(e){await this._pressKeyWithRemote("launch_app="+e)}addListener(e,s){return this.events.addListener(e,s),this}emit(e,s){return this.events.emit(e,s)}eventNames(){return this.events.eventNames()}getMaxListeners(){return this.events.getMaxListeners()}listenerCount(e){return this.events.listenerCount(e)}listeners(e){return this.events.listeners(e)}off(e,s){return this.events.off(e,s),this}on(e,s){return this.events.on(e,s),this}once(e,s){return this.events.once(e,s),this}prependListener(e,s){return this.events.prependListener(e,s),this}prependOnceListener(e,s){return this.events.prependOnceListener(e,s),this}rawListeners(e){return this.events.rawListeners(e)}removeAllListeners(e){return this.events.removeAllListeners(e),this}removeListener(e,s){return this.events.removeListener(e,s),this}setMaxListeners(e){return this.events.setMaxListeners(e),this}};var S=class t{options={};static async check(e={}){let s=await this.version(e);if(!s.pyatv)throw new Error("Unable to find pyatv. Is it installed?");if($.default.lt(s.pyatv,"0.6.0"))throw new Error("Found pyatv, but unforunately it's too old. Please update pyatv.");try{await this.find(e)}catch(i){throw new Error(`Unable to scan for devices: ${String(i).replace("Error: ","")}`)}}static async version(e={}){let s=m(),i=null,n=null;try{i=await g(s,"atvremote",["--version"],e)}catch(r){d(s,`Unable to get pyatv version due to ${r}`,e)}i&&i.substr(0,10)==="atvremote "&&(i=i.substr(10)),$.default.valid(i)||(d(s,`String "${i}" is not a valid pyatv version, set it to null`,e),i=null);try{let r=(0,C.join)((0,C.dirname)((0,J.fileURLToPath)(y)),"..","..","package.json");n=JSON.parse(await G.promises.readFile(r,"utf8"))?.version||null}catch(r){d(s,`Unable to get module version due to ${r}`,e)}return n&&!$.default.valid(n)&&(d(s,`String "${n}" is not a valid module version, set it to null`,e),n=null),c(s),{pyatv:i,module:n}}static async find(e={},s){let i=m(),n=f(e),r=[],o=[],a=await g(i,"atvscript",[...n,"scan"],{...e||{},allowMultipleResponses:!0});for(let p of a)if(typeof p=="object"&&"result"in p&&p.result==="failure")o.push(p);else if(typeof p=="object"&&"result"in p&&p.result==="success"&&Array.isArray(p.devices))r.push(...p.devices.map(l=>this.device(Object.assign({},e,{host:l.address,id:l.identifier,allIDs:l.all_identifiers,name:l.name,mac:l.device_info?.mac||void 0,model:l.device_info?.model,modelName:l.device_info?.model_str,os:l.device_info?.operating_system,version:l.device_info?.version,services:l.services}))));else throw new Error(`Unable to parse pyatv response: ${JSON.stringify(p,null," ")}`);if(c(i),s)return{devices:r,errors:o};if(!r.length&&o.length)throw new Error(`Unable to find any devices, but received ${o.length} error${o.length!==1?"s":""}: ${JSON.stringify(o,null," ")}`);return r}static device(e){return new N(e)}constructor(e={}){this.options=Object.assign({},e)}async check(e={}){return t.check(Object.assign({},this.options,e))}async version(e={}){return t.version(Object.assign({},this.options,e))}async find(e={}){return t.find(Object.assign({},this.options,e))}device(e){return t.device(Object.assign({},this.options,e))}};(async()=>{try{await S.check(),console.log(""),console.log("\u2714 node-pyatv seems to be ready to use!"),console.log(" Thank you and have a great day. Or night. Whatever."),console.log("")}catch(t){console.log(""),console.log("#".repeat(60)),console.log("#"+" ".repeat(58)+"#"),console.log("# \u26A0 Warning: node-pyatv is not ready to be used!"+" ".repeat(10)+"#"),console.log("#"+" ".repeat(58)+"#"),console.log("# To use the JavaScript module, pyatv >= 0.6.0 must be #"),console.log("# installed. Unfortunately this could not be found. During #"),console.log("# the check following error message was reported: #"),console.log("#"+" ".repeat(58)+"#"),console.log(String(t).replace("Error: ","").replace(/(.{1,54})/g,`$1
5
+ `+s.stacktrace),new Error(r)}if(typeof s.datetime=="string"){let r=new Date(s.datetime);isNaN(r.getTime())?i(`Invalid datetime value ${s.datetime}, ignore attribute`):n.dateTime=r}else i(`No datetime value found in input (${JSON.stringify(s)})`);return f(s,n,"hash","hash",i),typeof s.media_type=="string"?Object.keys(b).map(o=>String(o)).includes(s.media_type)?n.mediaType=b[s.media_type]:i(`Unsupported mediaType value ${s.media_type}, ignore attribute`):i(`No mediaType value found in input (${JSON.stringify(s)})`),typeof s.device_state=="string"?Object.keys(O).map(o=>String(o)).includes(s.device_state)?n.deviceState=O[s.device_state]:i(`Unsupported deviceState value ${s.device_state}, ignore attribute`):i(`No deviceState value found in input (${JSON.stringify(s)})`),f(s,n,"title","title",i),f(s,n,"artist","artist",i),f(s,n,"album","album",i),f(s,n,"genre","genre",i),E(s,n,"total_time","totalTime",i),E(s,n,"position","position",i),typeof s.shuffle=="string"?Object.keys(x).map(o=>String(o)).includes(s.shuffle)?n.shuffle=x[s.shuffle]:i(`Unsupported shuffle value ${s.shuffle}, ignore attribute`):i(`No shuffle value found in input (${JSON.stringify(s)})`),typeof s.repeat=="string"?Object.keys(k).map(o=>String(o)).includes(s.repeat)?n.repeat=k[s.repeat]:i(`Unsupported repeat value ${s.repeat}, ignore attribute`):i(`No repeat value found in input (${JSON.stringify(s)})`),f(s,n,"app","app",i),f(s,n,"app_id","appId",i),typeof s.power_state=="string"?Object.keys(_).map(o=>String(o)).includes(s.power_state)?n.powerState=_[s.power_state]:i(`Unsupported powerState value ${s.power_state}, ignore attribute`):i(`No powerState value found in input (${JSON.stringify(s)})`),E(s,n,"volume","volume",i),typeof s.focus_state=="string"?Object.keys(R).map(o=>String(o)).includes(s.focus_state)?n.focusState=R[s.focus_state]:i(`Unsupported focusState value ${s.focus_state}, ignore attribute`):i(`No focusState value found in input (${JSON.stringify(s)})`),Array.isArray(s.output_devices)&&(n.outputDevices=s.output_devices),f(s,n,"content_identifier","contentIdentifier",i),E(s,n,"episode_number","episodeNumber",i),E(s,n,"season_number","seasonNumber",i),f(s,n,"season_name","seasonName",i),n}function W(s,e){return!!(Array.isArray(s)&&Array.isArray(e)&&JSON.stringify(s.sort((t,i)=>t.identifier<i.identifier?-1:1))===JSON.stringify(e.sort((t,i)=>t.identifier<i.identifier?-1:1)))}var N=class{values;constructor(e){this.values=Object.assign({},e,{key:e.key})}get key(){return this.values.key}get oldValue(){return this.values.old}get newValue(){return this.values.new}get value(){return this.values.new}get device(){return this.values.device}};var G=require("events");var A=class extends G.EventEmitter{options;state;device;pyatv;timeout;listenerState;constructor(e,t,i){super(),this.state=e,this.device=t,this.options=Object.assign({},i),this.listenerState=0}applyStateAndEmitEvents(e){let t=Object.keys(this.state);t=t.filter(i=>!["powerState","focusState","outputDevices","volume"].includes(i)),"powerState"in e&&e.powerState&&(t=["powerState"]),"focusState"in e&&e.focusState&&(t=["focusState"]),"outputDevices"in e&&e.outputDevices&&(t=["outputDevices"]),"volume"in e&&e.volume!==null&&(t=["volume"]),Object.entries(e).find(([i,n])=>!["result","dateTime"].includes(i)&&n!==null)&&t.forEach(i=>{let n=this.state[i],r=e[i];if(n===void 0||r===void 0||n===r||i==="outputDevices"&&W(n,r))return;let o=new N({key:i,old:n,new:r,device:this.device});this.state[i]=e[i];try{this.emit("update:"+i,o),this.emit("update",o)}catch(a){this.emit("error",a)}})}parsePushUpdate(e,t){let i;try{i=JSON.parse(t)}catch(n){let r=`Unable to parse stdout json: ${n}`;p(e,r,this.options),this.emit("error",new Error(r));return}this.applyPushUpdate(i,e),this.listenerState===1&&(this.listenerState=2,this.checkListener())}applyPushUpdate(e,t){try{let i=T(e,t,this.options);this.applyStateAndEmitEvents(i)}catch(i){this.emit("error",i)}}checkListener(){if(this.listenerState===0&&this.listenerCount()===0&&this.timeout)clearTimeout(this.timeout),this.timeout=void 0;else if(this.listenerState===0&&this.listenerCount()>0){let e=m();p(e,`Start listeing to events from device ${this.options.name}`,this.options),this.startListening(e),c(e)}else if([1,2].includes(this.listenerState)&&this.listenerCount()===0){let e=m();p(e,`Stop listening to events from device ${this.options.name}`,this.options),this.stopListening(e).catch(t=>p(e,`Unable to stop listeing: ${t}`,this.options)).finally(()=>c(e))}}startListening(e){if(this.listenerState!==0)return;this.listenerState=1;let t=new Date().getTime(),i=g(this.options);if(this.pyatv=I(e,"atvscript",[...i,"push_updates"],this.options),!this.pyatv)throw new Error("Unable to start listener: Unable to start atvscript");let n=d=>{p(e,`Got error from child process: ${d}`,this.options),this.emit("error",d)},r=d=>{let u=new Error(`Got stderr output from pyatv: ${d}`);p(e,d.toString(),this.options),this.emit("error",u)},o=d=>{String(d).split(`
6
+ `).map(u=>u.trim()).filter(Boolean).forEach(u=>{p(e,`> ${u}`,this.options),this.parsePushUpdate(e,u)})},a=d=>{this.pyatv!==void 0&&(this.listenerState=0,p(e,`Listening with atvscript exited with code ${d}`,this.options),this.timeout!==void 0&&(clearTimeout(this.timeout),this.timeout=void 0),this.pyatv.stdout&&this.pyatv.stdout.off("data",o),this.pyatv.stderr&&this.pyatv.stderr.off("data",r),this.pyatv.off("error",n),this.pyatv.off("close",a),this.listenerCount()>0&&new Date().getTime()-t<3e4?(p(e,`Wait 15s and restart listeing to events from device ${this.options.name}`,this.options),this.timeout=setTimeout(()=>{this.checkListener()},15e3)):this.listenerCount()>0&&(p(e,`Restart listeing to events from device ${this.options.name}`,this.options),this.checkListener()),c(e))};this.pyatv.on("error",n),this.pyatv.on("close",a),this.pyatv.stdout&&this.pyatv.stdout.on("data",o),this.pyatv.stderr&&this.pyatv.stderr.on("data",r)}async stopListening(e){if(!(this.listenerState!==1&&this.listenerState!==2)){if(this.listenerState=3,this.pyatv===void 0)throw new Error("Unable to stop listening due to internal error: state is stopping, but there's no child process. This should never happen, please report this.");this.pyatv.stdin&&(p(e,"Pressing enter to close atvscript\u2026",this.options),this.pyatv.stdin.write(`
7
+ `),await new Promise(t=>this.timeout=setTimeout(t,250))),this.listenerState===3&&this.pyatv&&this.pyatv.kill(),this.listenerState=0}}addListener(e,t){return super.addListener(e,t),this.checkListener(),this}on(e,t){return super.on(e,t),this.checkListener(),this}once(e,t){return super.once(e,i=>{t(i),setTimeout(()=>this.checkListener(),0)}),this.checkListener(),this}prependListener(e,t){return super.prependListener(e,t),this.checkListener(),this}off(e,t){return super.off(e,t),this.checkListener(),this}removeAllListeners(e){return super.removeAllListeners(e),this.checkListener(),this}removeListener(e,t){return super.removeListener(e,t),this.checkListener(),this}listenerCount(e){return e!==void 0?super.listenerCount(e):this.eventNames().map(t=>this.listenerCount(t)).reduce((t,i)=>t+i,0)}};var w=class{options;state;events;constructor(e){this.options=Object.assign({},e),this.state=T({},"",{}),this.events=new A(this.state,this,this.options)}get name(){return this.options.name}get host(){return this.options.host}get id(){return this.options.id}get allIDs(){return this.options.allIDs}get protocol(){return this.options.protocol}get mac(){return this.options.mac}get model(){return this.options.model}get modelName(){return this.options.modelName}get os(){return this.options.os}get version(){return this.options.version}get services(){return this.options.services}get debug(){return this.options.debug}set debug(e){typeof e=="function"?this.options.debug=e:this.options.debug=!!e||void 0}toJSON(){return{name:this.name,host:this.host,id:this.id,protocol:this.protocol}}toString(){return`NodePyATVDevice(${this.name}, ${this.host})`}async getState(e={}){if(this.state?.dateTime&&new Date().getTime()-this.state.dateTime.getTime()<(e.maxAge||5e3)){let i=null;return this.state.position&&this.state.dateTime&&(i=Math.round(this.state.position+(new Date().getTime()-this.state.dateTime.getTime())/1e3)),Object.assign({},this.state,{position:i})}let t=m();try{let i=g(this.options),n=await P(t,"atvscript",[...i,"playing"],this.options),r=T(n,t,this.options);return this.applyState(r),r}finally{c(t)}}clearState(){this.applyState(T({},"",{}))}applyState(e){this.events.applyStateAndEmitEvents(e)}async getDateTime(e={}){return(await this.getState(e)).dateTime}async getHash(e={}){return(await this.getState(e)).hash}async getMediaType(e={}){return(await this.getState(e)).mediaType}async getDeviceState(e={}){return(await this.getState(e)).deviceState}async getTitle(e={}){return(await this.getState(e)).title}async getArtist(e={}){return(await this.getState(e)).artist}async getAlbum(e={}){return(await this.getState(e)).album}async getGenre(e={}){return(await this.getState(e)).genre}async getTotalTime(e={}){return(await this.getState(e)).totalTime}async getPosition(e={}){return(await this.getState(e)).position}async getShuffle(e={}){return(await this.getState(e)).shuffle}async getRepeat(e={}){return(await this.getState(e)).repeat}async getApp(e={}){return(await this.getState(e)).app}async getAppId(e={}){return(await this.getState(e)).appId}async getPowerState(e={}){return this.getState(e).then(t=>t.powerState)}async getVolume(e={}){return this.getState(e).then(t=>t.volume)}async getFocusState(e={}){return this.getState(e).then(t=>t.focusState)}async getOutputDevices(e={}){return this.getState(e).then(t=>t.outputDevices)}async getContentIdentifier(e={}){return this.getState(e).then(t=>t.contentIdentifier)}async getEpisodeNumber(e={}){return this.getState(e).then(t=>t.episodeNumber)}async getSeasonNumber(e={}){return this.getState(e).then(t=>t.seasonNumber)}async getSeasonName(e={}){return this.getState(e).then(t=>t.seasonName)}async listApps(){let e=m(),t=g(this.options),i=await P(e,"atvremote",[...t,"app_list"],this.options);if(typeof i!="string"||!i.startsWith("App: "))throw new Error("Unexpected atvremote response: "+i);c(e);let n=/(.+) \(([^)]+)\)$/i;return i.substring(5).split(", App: ").map(o=>{let a=o.match(n);if(a!==null)return{id:a[2],name:a[1],launch:()=>this.launchApp(a[2])}}).filter(Boolean)}async _pressKeyWithScript(e){let t=m(),i=g(this.options),n=await P(t,"atvscript",[...i,e],this.options);if(typeof n!="object"||n.result!=="success")throw new Error(`Unable to parse pyatv response: ${JSON.stringify(n,null," ")}`);c(t)}async _pressKeyWithRemote(e){let t=m(),i=g(this.options);await P(t,"atvremote",[...i,e],this.options),c(t)}async pressKey(e){let t=Object.entries(F).find(([n])=>e===n);if(!t)throw new Error(`Unsupported key value ${e}!`);let i=t[1];["turnOn","turnOff"].includes(e)?await this._pressKeyWithRemote(i):await this._pressKeyWithScript(i)}async down(){await this._pressKeyWithScript("down")}async home(){await this._pressKeyWithScript("home")}async homeHold(){await this._pressKeyWithScript("home_hold")}async left(){await this._pressKeyWithScript("left")}async menu(){await this._pressKeyWithScript("menu")}async next(){await this._pressKeyWithScript("next")}async pause(){await this._pressKeyWithScript("pause")}async play(){await this._pressKeyWithScript("play")}async playPause(){await this._pressKeyWithScript("play_pause")}async previous(){await this._pressKeyWithScript("previous")}async right(){await this._pressKeyWithScript("right")}async select(){await this._pressKeyWithScript("select")}async skipBackward(){await this._pressKeyWithScript("skip_backward")}async skipForward(){await this._pressKeyWithScript("skip_forward")}async stop(){await this._pressKeyWithScript("stop")}async suspend(){await this._pressKeyWithScript("suspend")}async topMenu(){await this._pressKeyWithScript("top_menu")}async up(){await this._pressKeyWithScript("up")}async volumeDown(){await this._pressKeyWithScript("volume_down")}async volumeUp(){await this._pressKeyWithScript("volume_up")}async wakeup(){await this._pressKeyWithScript("wakeup")}async turnOff(){await this._pressKeyWithRemote("turn_off")}async turnOn(){await this._pressKeyWithRemote("turn_on")}async launchApp(e){await this._pressKeyWithRemote("launch_app="+e)}addListener(e,t){return this.events.addListener(e,t),this}emit(e,t){return this.events.emit(e,t)}eventNames(){return this.events.eventNames()}getMaxListeners(){return this.events.getMaxListeners()}listenerCount(e){return this.events.listenerCount(e)}listeners(e){return this.events.listeners(e)}off(e,t){return this.events.off(e,t),this}on(e,t){return this.events.on(e,t),this}once(e,t){return this.events.once(e,t),this}prependListener(e,t){return this.events.prependListener(e,t),this}prependOnceListener(e,t){return this.events.prependOnceListener(e,t),this}rawListeners(e){return this.events.rawListeners(e)}removeAllListeners(e){return this.events.removeAllListeners(e),this}removeListener(e,t){return this.events.removeListener(e,t),this}setMaxListeners(e){return this.events.setMaxListeners(e),this}};var S=class s{options={};static async check(e={}){let t=await this.version(e);if(!t.pyatv)throw new Error("Unable to find pyatv. Is it installed?");if(C.default.lt(t.pyatv,"0.6.0"))throw new Error("Found pyatv, but unforunately it's too old. Please update pyatv.");try{await this.find(e)}catch(i){throw new Error(`Unable to scan for devices: ${String(i).replace("Error: ","")}`)}}static async version(e={}){let t=m(),i=null,n=null;try{i=await P(t,"atvremote",["--version"],e)}catch(r){p(t,`Unable to get pyatv version due to ${r}`,e)}i&&i.substr(0,10)==="atvremote "&&(i=i.substr(10)),C.default.valid(i)||(p(t,`String "${i}" is not a valid pyatv version, set it to null`,e),i=null);try{let r=(0,j.join)((0,j.dirname)((0,J.fileURLToPath)(y)),"..","..","package.json");n=JSON.parse(await M.promises.readFile(r,"utf8"))?.version||null}catch(r){p(t,`Unable to get module version due to ${r}`,e)}return n&&!C.default.valid(n)&&(p(t,`String "${n}" is not a valid module version, set it to null`,e),n=null),c(t),{pyatv:i,module:n}}static async find(e={},t){let i=m(),n=g(e),r=[],o=[],a=await P(i,"atvscript",[...n,"scan"],{...e||{},allowMultipleResponses:!0});for(let d of a)if(typeof d=="object"&&"result"in d&&d.result==="failure")o.push(d);else if(typeof d=="object"&&"result"in d&&d.result==="success"&&Array.isArray(d.devices))r.push(...d.devices.map(u=>this.device(Object.assign({},e,{host:u.address,id:u.identifier,allIDs:u.all_identifiers,name:u.name,mac:u.device_info?.mac||void 0,model:u.device_info?.model,modelName:u.device_info?.model_str,os:u.device_info?.operating_system,version:u.device_info?.version,services:u.services}))));else throw new Error(`Unable to parse pyatv response: ${JSON.stringify(d,null," ")}`);if(c(i),t)return{devices:r,errors:o};if(!r.length&&o.length)throw new Error(`Unable to find any devices, but received ${o.length} error${o.length!==1?"s":""}: ${JSON.stringify(o,null," ")}`);return r}static device(e){return new w(e)}constructor(e={}){this.options=Object.assign({},e)}async check(e={}){return s.check(Object.assign({},this.options,e))}async version(e={}){return s.version(Object.assign({},this.options,e))}async find(e={}){return s.find(Object.assign({},this.options,e))}device(e){return s.device(Object.assign({},this.options,e))}};(async()=>{try{await S.check(),console.log(""),console.log("\u2714 node-pyatv seems to be ready to use!"),console.log(" Thank you and have a great day. Or night. Whatever."),console.log("")}catch(s){console.log(""),console.log("#".repeat(60)),console.log("#"+" ".repeat(58)+"#"),console.log("# \u26A0 Warning: node-pyatv is not ready to be used!"+" ".repeat(10)+"#"),console.log("#"+" ".repeat(58)+"#"),console.log("# To use the JavaScript module, pyatv >= 0.6.0 must be #"),console.log("# installed. Unfortunately this could not be found. During #"),console.log("# the check following error message was reported: #"),console.log("#"+" ".repeat(58)+"#"),console.log(String(s).replace("Error: ","").replace(/(.{1,54})/g,`$1
8
8
  `).split(`
9
9
  `).map(e=>e.trim()).filter(e=>!!e).map(e=>`# > ${e}${" ".repeat(55-e.length)}#`).join(`
10
10
  `)),console.log("#"+" ".repeat(58)+"#"),console.log("# You can probably find more information here: #"),console.log("# https://github.com/sebbo2002/node-pyatv #"),console.log("#"+" ".repeat(58)+"#"),console.log("#".repeat(60)),console.log("")}})();