All files tools.ts

99.42% Statements 170/171
90.29% Branches 93/103
100% Functions 24/24
99.37% Lines 157/158

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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366    1x                   1x     1x   1x 104x   104x 110x 110x 104x 104x       104x     1x 111x 92x       1x 2066x 9x 9x   9x                       9x       1x 92x 4x   88x 3x     85x       1x           88x 88x   88x 88x         88x 88x 88x     88x 88x   88x 88x   88x 88x     88x 88x     88x 88x   88x 88x     88x 88x   88x     1x           70x           70x 70x     70x 70x 70x     70x 70x   70x 70x   70x 70x     70x 70x 70x     70x 70x   70x 70x     70x 70x     65x 2x 2x 2x   63x 50x 50x     1x 1x 1x       13x     1x 74x   74x 1x   73x 62x   74x 1x   74x 1x   74x 1x   74x 1x   74x 1x     74x                   833x 35x 35x     798x     1x 1711x 120x                                 120x 1x       119x 9x 9x 8x     1x       110x       119x     119x 24x 6x 5x     1x     113x       119x 36x 6x 5x     1x     113x       119x     119x     119x     119x     119x 5x     114x       119x 5x     114x       119x 18x 6x 5x     1x     113x       119x 18x 6x 5x     1x     113x       119x 119x     119x 2x 1x 1x           118x     119x    
'use strict';
 
import {
    NodePyATVDeviceState,
    NodePyATVExecutableType,
    NodePyATVFindAndInstanceOptions,
    NodePyATVInstanceOptions,
    NodePyATVInternalState,
    NodePyATVMediaType, NodePyATVPowerState, NodePyATVRepeatState, NodePyATVShuffleState,
    NodePyATVState
} from './types';
 
import {ChildProcess, spawn, SpawnOptions} from 'child_process';
import {FakeChildProcess} from './fake-spawn';
 
const requestIds: string[] = [];
 
export function addRequestId(): string {
    let id = '?';
 
    for (let i = 0; i < 1000; i += 1) {
        id = Math.round(Math.random() * (i + 6) * 36).toString(36).toUpperCase();
        if (!requestIds.includes(id)) {
            requestIds.push(id);
            break;
        }
    }
 
    return id;
}
 
export function removeRequestId(id: string | undefined): void {
    if (id && requestIds.includes(id)) {
        requestIds.splice(requestIds.indexOf(id), 1);
    }
}
 
export function debug(id: string, message: string, options: NodePyATVInstanceOptions): void {
    if (options.debug) {
        const log = typeof options.debug === 'function' ? options.debug : console.log;
        const enableColors = !process.env.NO_COLOR && !options.noColors;
 
        const parts = [
            enableColors ? '\x1b[0m' : '', // Color Reset
            enableColors ? '\x1b[90m' : '', // Grey
            '[node-pyatv][',
            enableColors ? '\x1b[37m' : '', // Light Grey
            id,
            enableColors ? '\x1b[90m' : '', // Grey
            '] ',
            enableColors ? '\x1b[0m' : '', // Color Reset
            message
        ];
 
        log.apply(null, [parts.join('')]);
    }
}
 
export function getExecutable(executable: NodePyATVExecutableType, options: NodePyATVInstanceOptions): string {
    if (executable === NodePyATVExecutableType.atvremote && typeof options.atvremotePath === 'string') {
        return options.atvremotePath;
    }
    else if (executable === NodePyATVExecutableType.atvscript && typeof options.atvscriptPath === 'string') {
        return options.atvscriptPath;
    }
    else {
        return executable;
    }
}
 
export function execute(
    requestId: string,
    executableType: NodePyATVExecutableType,
    parameters: string[],
    options: NodePyATVInstanceOptions
): ChildProcess | FakeChildProcess {
    const executable = getExecutable(executableType, options);
    const mySpawn: ((command: string, args: Array<string>, options: SpawnOptions) => (ChildProcess | FakeChildProcess)) = typeof options.spawn === 'function' ? options.spawn : spawn;
 
    debug(requestId, `${executable} ${parameters.join(' ')}`, options);
    const child = mySpawn(executable, parameters, {
        env: process.env
    });
 
    /* eslint-disable @typescript-eslint/no-explicit-any*/
    const onStdOut = (data: any) => debug(requestId, `stdout: ${String(data).trim()}`, options);
    const onStdErr = (data: any) => debug(requestId, `stderr: ${String(data).trim()}`, options);
    const onError = (data: any) => debug(requestId, `error: ${String(data).trim()}`, options);
    /* eslint-enable @typescript-eslint/no-explicit-any*/
 
    const onClose = (code: number) => {
        debug(requestId, `${executable} exited with code: ${code}`, options);
 
        Eif (child.stdout) {
            child.stdout.off('data', onStdOut);
        }
        Eif (child.stderr) {
            child.stderr.off('data', onStdErr);
        }
 
        child.off('error', onError);
        child.off('close', onClose);
    };
 
    Eif (child.stdout) {
        child.stdout.on('data', onStdOut);
    }
    Eif (child.stderr) {
        child.stderr.on('data', onStdErr);
    }
 
    child.on('error', onError);
    child.on('close', onClose);
 
    return child;
}
 
export async function request(
    requestId: string,
    executableType: NodePyATVExecutableType,
    parameters: string[],
    options: NodePyATVInstanceOptions
): Promise<string|Record<string,unknown>> {
    const result = {
        stdout: '',
        stderr: '',
        code: 0
    };
 
    await new Promise((resolve, reject) => {
        const pyatv = execute(requestId, executableType, parameters, options);
 
        /* eslint-disable @typescript-eslint/no-explicit-any*/
        const onStdOut = (data: any) => result.stdout += String(data).trim();
        const onStdErr = (data: any) => result.stderr += String(data).trim();
        const onError = (data: any) => reject(data instanceof Error ? data : new Error(String(data)));
        /* eslint-enable @typescript-eslint/no-explicit-any*/
 
        const onClose: (code: number) => void = (code: number) => {
            result.code = code;
 
            Eif (pyatv.stdout) {
                pyatv.stdout.off('data', onStdOut);
            }
            Eif (pyatv.stderr) {
                pyatv.stderr.off('data', onStdErr);
            }
 
            pyatv.off('error', onError);
            pyatv.off('close', onClose);
            resolve(undefined);
        };
 
        Eif (pyatv.stdout) {
            pyatv.stdout.on('data', onStdOut);
        }
        Eif (pyatv.stderr) {
            pyatv.stderr.on('data', onStdErr);
        }
 
        pyatv.on('error', onError);
        pyatv.on('close', onClose);
    });
 
    if (result.stderr.length > 0) {
        const msg = `Unable to execute request ${requestId}: ${result.stderr}`;
        debug(requestId, msg, options);
        throw new Error(msg);
    }
    if (executableType === NodePyATVExecutableType.atvscript) {
        try {
            return JSON.parse(result.stdout);
        }
        catch (error) {
            const msg = `Unable to parse result ${requestId} json: ${error}`;
            debug(requestId, msg, options);
            throw new Error(msg);
        }
    }
 
    return result.stdout;
}
 
export function getParamters(options: NodePyATVFindAndInstanceOptions = {}): string[] {
    const parameters: string[] = [];
 
    if (options.hosts) {
        parameters.push('-s', options.hosts.join(','));
    }
    else if (options.host) {
        parameters.push('-s', options.host);
    }
    if (options.id) {
        parameters.push('-i', options.id);
    }
    if (options.protocol) {
        parameters.push('--protocol', options.protocol);
    }
    if (options.dmapCredentials) {
        parameters.push('--dmap-credentials', options.dmapCredentials);
    }
    if (options.mrpCredentials) {
        parameters.push('--mrp-credentials', options.mrpCredentials);
    }
    if (options.airplayCredentials) {
        parameters.push('--airplay-credentials', options.airplayCredentials);
    }
 
    return parameters;
}
 
function parseStateStringAttr(
    input: NodePyATVInternalState,
    output: NodePyATVState,
    inputAttr: ('hash' | 'title' | 'album' | 'artist' | 'genre' | 'app' | 'app_id'),
    outputAttr: ('hash' | 'title' | 'album' | 'artist' | 'genre' | 'app' | 'appId'),
    d: (msg: string) => void
): void {
    if (typeof input[inputAttr] === 'string') {
        output[outputAttr] = input[inputAttr] as string;
        return;
    }
 
    d(`No ${outputAttr} value found in input (${JSON.stringify(input)})`);
}
 
export function parseState(input: NodePyATVInternalState, id: string, options: NodePyATVInstanceOptions): NodePyATVState {
    const d = (msg: string) => debug(id, msg, options);
    const result: NodePyATVState = {
        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
    };
    if (!input || typeof input !== 'object') {
        return result;
    }
 
    // datetime
    if (typeof input.datetime === 'string') {
        const date = new Date(input.datetime);
        if (!isNaN(date.getTime())) {
            result.dateTime = date;
        }
        else {
            d(`Invalid datetime value ${input.datetime}, ignore attribute`);
        }
    }
    else {
        d(`No datetime value found in input (${JSON.stringify(input)})`);
    }
 
    // hash
    parseStateStringAttr(input, result, 'hash', 'hash', d);
 
    // mediaType
    if(typeof input.media_type === 'string') {
        const validValues = Object.keys(NodePyATVMediaType).map(o => String(o));
        if (validValues.includes(input.media_type)) {
            result.mediaType = NodePyATVMediaType[input.media_type as NodePyATVMediaType];
        }
        else {
            d(`Unsupported mediaType value ${input.media_type}, ignore attribute`);
        }
    } else {
        d(`No mediaType value found in input (${JSON.stringify(input)})`);
    }
 
    // deviceState
    if(typeof input.device_state === 'string') {
        const validValues = Object.keys(NodePyATVDeviceState).map(o => String(o));
        if (validValues.includes(input.device_state)) {
            result.deviceState = NodePyATVDeviceState[input.device_state as NodePyATVDeviceState];
        }
        else {
            d(`Unsupported deviceState value ${input.device_state}, ignore attribute`);
        }
    } else {
        d(`No deviceState value found in input (${JSON.stringify(input)})`);
    }
 
    // title
    parseStateStringAttr(input, result, 'title', 'title', d);
 
    // artist
    parseStateStringAttr(input, result, 'artist', 'artist', d);
 
    // album
    parseStateStringAttr(input, result, 'album', 'album', d);
 
    // genre
    parseStateStringAttr(input, result, 'genre', 'genre', d);
 
    // totalTime
    if (typeof input.total_time === 'number') {
        result.totalTime = input.total_time;
    }
    else {
        d(`No totalTime value found in input (${JSON.stringify(input)})`);
    }
 
    // position
    if (typeof input.position === 'number') {
        result.position = input.position;
    }
    else {
        d(`No position value found in input (${JSON.stringify(input)})`);
    }
 
    // shuffle
    if(typeof input.shuffle === 'string') {
        const validValues = Object.keys(NodePyATVShuffleState).map(o => String(o));
        if (validValues.includes(input.shuffle)) {
            result.shuffle = NodePyATVShuffleState[input.shuffle as NodePyATVShuffleState];
        }
        else {
            d(`Unsupported shuffle value ${input.shuffle}, ignore attribute`);
        }
    } else {
        d(`No shuffle value found in input (${JSON.stringify(input)})`);
    }
 
    // repeat
    if(typeof input.repeat === 'string') {
        const validValues = Object.keys(NodePyATVRepeatState).map(o => String(o));
        if (validValues.includes(input.repeat)) {
            result.repeat = NodePyATVRepeatState[input.repeat as NodePyATVRepeatState];
        }
        else {
            d(`Unsupported repeat value ${input.repeat}, ignore attribute`);
        }
    } else {
        d(`No repeat value found in input (${JSON.stringify(input)})`);
    }
 
    // app
    parseStateStringAttr(input, result, 'app', 'app', d);
    parseStateStringAttr(input, result, 'app_id', 'appId', d);
 
    // powerState
    if(typeof input.power_state === 'string') {
        const validValues = Object.keys(NodePyATVPowerState).map(o => String(o));
        Eif (validValues.includes(input.power_state)) {
            result.powerState = NodePyATVPowerState[input.power_state as NodePyATVPowerState];
        }
        else {
            d(`Unsupported powerState value ${input.power_state}, ignore attribute`);
        }
    } else {
        d(`No powerState value found in input (${JSON.stringify(input)})`);
    }
 
    return result;
}