All files device-events.ts

94.07% Statements 127/135
81.48% Branches 44/54
93.33% Functions 28/30
93.98% Lines 125/133

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289    1x                   1x   1x 1x           1x                 83x   83x 83x 83x 83x       31x     465x     465x   465x 401x     64x               64x   64x 64x 64x     1x               11x 11x     1x 1x 1x 1x     10x   10x 2x 2x         10x 10x       68x 8x 8x   60x 18x 18x   18x 18x   42x       15x 15x   15x   10x         18x       18x   18x 18x 18x   18x 1x 1x       18x 1x 1x 1x       18x 11x   11x   11x   18x 18x         18x 18x 18x 7x 7x     18x 18x   18x 18x   18x 18x     18x 3x   3x       15x         18x     18x 18x   18x 18x   18x 18x         15x             15x 15x             15x 15x 15x   15x     10x 7x     10x 10x       2x 2x 2x       19x 19x 19x       10x 10x 10x   10x 10x       2x 2x 2x       9x 9x 9x       2x 2x 2x       12x 12x 12x       200x 78x     122x 70x 70x      
'use strict';
 
import {
    NodePyATVDeviceOptions,
    NodePyATVExecutableType,
    NodePyATVInternalState,
    NodePyATVListenerState,
    NodePyATVState,
    NodePyATVStateIndex
} from './types';
import {ChildProcess} from 'child_process';
 
import {EventEmitter} from 'events';
import NodePyATVDevice from './device';
import NodePyATVDeviceEvent from './device-event';
import {addRequestId, debug, execute, getParamters, parseState, removeRequestId} from './tools';
import {FakeChildProcess} from './fake-spawn';
 
/**
 * @internal
 */
export default class NodePyATVDeviceEvents extends EventEmitter {
    private readonly options: NodePyATVDeviceOptions;
    private readonly state: NodePyATVState;
    private readonly device: NodePyATVDevice;
    private pyatv: ChildProcess | FakeChildProcess | undefined;
    private timeout: NodeJS.Timeout | undefined;
    private listenerState: NodePyATVListenerState;
 
    constructor(state: NodePyATVState, device: NodePyATVDevice, options: NodePyATVDeviceOptions) {
        super();
 
        this.state = state;
        this.device = device;
        this.options = Object.assign({}, options);
        this.listenerState = NodePyATVListenerState.stopped;
    }
 
    applyStateAndEmitEvents(newState: NodePyATVState): void {
        Object.keys(this.state).forEach((key: string) => {
 
            // @ts-ignore
            const oldValue = this.state[key];
 
            // @ts-ignore
            const newValue = newState[key];
 
            if(oldValue === undefined || newValue === undefined || oldValue === newValue) {
                return;
            }
 
            const event = new NodePyATVDeviceEvent({
                key: key as NodePyATVStateIndex,
                old: oldValue,
                new: newValue,
                device: this.device
            });
 
            // @ts-ignore
            this.state[key] = newState[key];
 
            try {
                this.emit('update:' + key, event);
                this.emit('update', event);
            }
            catch(error) {
                this.emit('error', error);
            }
        });
    }
 
    private parsePushUpdate(reqId: string, data: string): void {
        let json: NodePyATVInternalState;
 
        try {
            json = JSON.parse(data);
        }
        catch(error) {
            const msg = `Unable to parse stdout json: ${error}`;
            debug(reqId, msg, this.options);
            this.emit('error', new Error(msg));
            return;
        }
 
        this.applyPushUpdate(json, reqId);
 
        if(this.listenerState === NodePyATVListenerState.starting) {
            this.listenerState = NodePyATVListenerState.started;
            this.checkListener();
        }
    }
 
    private applyPushUpdate(update: NodePyATVInternalState, reqId: string): void {
        const newState = parseState(update, reqId, this.options);
        this.applyStateAndEmitEvents(newState);
    }
 
    private checkListener(): void {
        if(this.listenerState === NodePyATVListenerState.stopped && this.listenerCount() === 0 && this.timeout) {
            clearTimeout(this.timeout);
            this.timeout = undefined;
        }
        else if(this.listenerState === NodePyATVListenerState.stopped && this.listenerCount() > 0) {
            const id = addRequestId();
            debug(id, `Start listeing to events from device ${this.options.name}`, this.options);
 
            this.startListening(id);
            removeRequestId(id);
        }
        else if(
            [NodePyATVListenerState.starting, NodePyATVListenerState.started].includes(this.listenerState) &&
            this.listenerCount() === 0
        ) {
            const id = addRequestId();
            debug(id, `Stop listening to events from device ${this.options.name}`, this.options);
 
            this.stopListening(id)
                .catch(error => debug(id, `Unable to stop listeing: ${error}`, this.options))
                .finally(() => removeRequestId(id));
        }
    }
 
    private startListening(reqId: string): void {
        Iif(this.listenerState !== NodePyATVListenerState.stopped) {
            return;
        }
 
        this.listenerState = NodePyATVListenerState.starting;
 
        const listenStart = new Date().getTime();
        const parameters = getParamters(this.options);
        this.pyatv = execute(reqId, NodePyATVExecutableType.atvscript, [...parameters, 'push_updates'], this.options);
 
        const onError = (error: Error) => {
            debug(reqId, `Got error from child process: ${error}`, this.options);
            this.emit('error', error);
        };
 
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const onStdErr = (data: any) => {
            const error = new Error(`Got stderr output from pyatv: ${data}`);
            debug(reqId, data.toString(), this.options);
            this.emit('error', error);
        };
 
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const onStdOut = (data: any) => {
            String(data)
                .split('\n')
                .map(s => s.trim())
                .filter(Boolean)
                .forEach(s => this.parsePushUpdate(reqId, s));
        };
        const onClose = (code: number) => {
            Iif(this.pyatv === undefined) {
                // this should never happen… :/
                return;
            }
 
            this.listenerState = NodePyATVListenerState.stopped;
            debug(reqId, `Listening with atvscript exited with code ${code}`, this.options);
            if(this.timeout !== undefined) {
                clearTimeout(this.timeout);
                this.timeout = undefined;
            }
 
            Eif (this.pyatv.stdout) {
                this.pyatv.stdout.off('data', onStdOut);
            }
            Eif (this.pyatv.stderr) {
                this.pyatv.stderr.off('data', onStdErr);
            }
            this.pyatv.off('error', onError);
            this.pyatv.off('close', onClose);
 
 
            if(this.listenerCount() > 0 && new Date().getTime() - listenStart < 30000) {
                debug(reqId, `Wait 15s and restart listeing to events from device ${this.options.name}`, this.options);
 
                this.timeout = setTimeout(() => {
                    this.checkListener();
                }, 15000);
            }
            else Iif(this.listenerCount() > 0) {
                debug(reqId, `Restart listeing to events from device ${this.options.name}`, this.options);
                this.checkListener();
            }
 
            removeRequestId(reqId);
        };
 
        this.pyatv.on('error', onError);
        this.pyatv.on('close', onClose);
 
        Eif (this.pyatv.stdout) {
            this.pyatv.stdout.on('data', onStdOut);
        }
        Eif (this.pyatv.stderr) {
            this.pyatv.stderr.on('data', onStdErr);
        }
    }
 
    protected async stopListening(reqId: string): Promise<void> {
        Iif(
            this.listenerState !== NodePyATVListenerState.starting &&
            this.listenerState !== NodePyATVListenerState.started
        ) {
            return;
        }
 
        this.listenerState = NodePyATVListenerState.stopping;
        Iif(this.pyatv === undefined) {
            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.'
            );
        }
 
        Eif(this.pyatv.stdin) {
            debug(reqId, 'Pressing enter to close atvscript…', this.options);
            this.pyatv.stdin.write('\n');
 
            await new Promise(cb => this.timeout = setTimeout(cb, 250));
        }
 
        if(this.listenerState === NodePyATVListenerState.stopping && this.pyatv) {
            this.pyatv.kill();
        }
 
        this.listenerState = NodePyATVListenerState.stopped;
        return;
    }
 
    addListener(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        super.addListener(event, listener);
        this.checkListener();
        return this;
    }
 
    on(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        super.on(event, listener);
        this.checkListener();
        return this;
    }
 
    once(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        super.once(event, (event: NodePyATVDeviceEvent) => {
            listener(event);
            setTimeout(() => this.checkListener(), 0);
        });
        this.checkListener();
        return this;
    }
 
    prependListener(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        super.prependListener(event, listener);
        this.checkListener();
        return this;
    }
 
    off(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        super.off(event, listener);
        this.checkListener();
        return this;
    }
 
    removeAllListeners(event?: string | symbol): this {
        super.removeAllListeners(event);
        this.checkListener();
        return this;
    }
 
    removeListener(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        super.removeListener(event, listener);
        this.checkListener();
        return this;
    }
 
    listenerCount(event?: string | symbol): number {
        if(event !== undefined) {
            return super.listenerCount(event);
        }
 
        return this.eventNames()
            .map(event => this.listenerCount(event))
            .reduce((a, b) => a + b, 0);
    }
}