All files device.ts

98.28% Statements 114/116
94.87% Branches 37/39
98.46% Functions 64/65
98.28% Lines 114/116

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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681    1x                         1x 1x                     1x           83x 83x 83x                                 6x             6x             4x             4x                 12x                   4x 1x     3x                     3x                           1x                               22x 2x 2x 2x           2x     20x 20x   20x 20x 20x   20x 20x                 1x       21x                 1x 1x                 1x 1x                 1x 1x                 1x 1x                 3x 3x                 1x 1x                 1x 1x                 1x 1x                 1x 1x                 1x 1x                 1x 1x                 1x 1x                 1x 1x                 1x 1x       23x 23x   23x 23x 1x     22x                                       3x 25x   3x 1x     2x 2x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x               1x                     2x 2x                   1x               1x               1x                 4x                       3x                     9x 9x                     9x 9x                       10x 10x                 1x 1x                 1x 1x                 3x                       2x 2x                     1x 1x                        
'use strict';
 
import {
    NodePyATVDeviceOptions,
    NodePyATVDeviceState,
    NodePyATVExecutableType,
    NodePyATVGetStateOptions,
    NodePyATVInternalKeys, NodePyATVKeys,
    NodePyATVMediaType,
    NodePyATVProtocol,
    NodePyATVRepeatState,
    NodePyATVShuffleState,
    NodePyATVState
} from './types';
 
import {addRequestId, getParamters, parseState, removeRequestId, request} from './tools';
import NodePyATVDeviceEvents from './device-events';
import NodePyATVDeviceEvent from './device-event';
import { EventEmitter } from 'events';
 
/**
 * Represents an Apple TV. Use [[getState]] to query the current state (e.g. media
 * type and title). You can also use the attribute methods (e.g. [[getTitle]] to get
 * the state. If you want realtime updates, subscribe to it's events with an
 * `EventEmitter` like API, so for example by using [[on]], [[once]] or [[addListener]].
 * It's also possible to send key commands by using [[pressKey]] or methods like [[pause]].
 */
export default class NodePyATVDevice implements EventEmitter{
    private readonly options: NodePyATVDeviceOptions;
    private readonly state: NodePyATVState;
    private readonly events: NodePyATVDeviceEvents;
 
    constructor(options: NodePyATVDeviceOptions) {
        this.options = Object.assign({}, options);
        this.state = parseState({}, '', {});
        this.events = new NodePyATVDeviceEvents(this.state, this, this.options);
 
        // @todo basic validation
    }
 
    /**
     * Get the name of the Apple TV.
     *
     * ```typescript
     * import pyatv from '@sebbo2002/node-pyatv';
     * const devices = await pyatv.find();
     * devices.forEach(device =>
     *     console.log(device.name)
     * );
     * ```
     */
    get name(): string {
        return this.options.name;
    }
 
    /**
     * Get the IP address of the Apple TV.
     */
    get host(): string {
        return this.options.host;
    }
 
    /**
     * Get the ID of the Apple TV.
     */
    get id(): string | undefined {
        return this.options.id;
    }
 
    /**
     * Get the used protocol to connect to the Apple TV.
     */
    get protocol(): NodePyATVProtocol | undefined {
        return this.options.protocol;
    }
 
    /**
     * Returns true, if debugging is enabled. Returns the custom
     * logging method, if one was specified. Otherwise, if debug
     * log is disabled, returns undefined.
     */
    get debug(): true | ((msg: string) => void) | undefined {
        return this.options.debug;
    }
 
    /**
     * Enable or disable debugging or set a custom
     * debugging method to use.
     *
     * @param debug
     */
    set debug(debug: true | ((msg: string) => void) | undefined) {
        if (typeof debug === 'function') {
            this.options.debug = debug;
        }
        else {
            this.options.debug = Boolean(debug) || undefined;
        }
    }
 
    /**
     * Returns an object with `name`, `host`, `id` and `protocol`.
     * Can be used to initiate a new device instance.
     *
     * @category Basic
     */
    toJSON(): { name: string; host: string; id: string | undefined; protocol: NodePyATVProtocol | undefined } {
        return {
            name: this.name,
            host: this.host,
            id: this.id,
            protocol: this.protocol
        };
    }
 
    /**
     * Returns a string. Just for debugging, etc.
     *
     * @category Basic
     */
    toString(): string {
        return `NodePyATVDevice(${this.name}, ${this.host})`;
    }
 
    /**
     * Returns an [[NodePyATVState]] object representing the current state
     * of the device. Has an internal cache, which has a default TTL of 5s.
     * You can change this default value by passing the `maxAge` option.
     *
     * ```typescript
     * await device.getState({maxAge: 10000}); // cache TTL: 10s
     * ```
     *
     * @param options
     * @category State
     */
    async getState(options: NodePyATVGetStateOptions = {}): Promise<NodePyATVState> {
        if (this.state?.dateTime && new Date().getTime() - this.state.dateTime.getTime() < (options.maxAge || 5000)) {
            let position = null;
            Eif (this.state.position && this.state.dateTime) {
                position = Math.round(
                    this.state.position +
                    ((new Date().getTime() - this.state.dateTime.getTime()) / 1000)
                );
            }
 
            return Object.assign({}, this.state, {position});
        }
 
        const id = addRequestId();
        const parameters = getParamters(this.options);
 
        const result = await request(id, NodePyATVExecutableType.atvscript, [...parameters, 'playing'], this.options);
        const newState = parseState(result, id, this.options);
        this.applyState(newState);
 
        removeRequestId(id);
        return newState;
    }
 
    /**
     * Removes the state node-pyatv cached for this device.
     *
     * @category State
     */
    clearState(): void {
        this.applyState(parseState({}, '', {}));
    }
 
    private applyState(newState: NodePyATVState): void {
        this.events.applyStateAndEmitEvents(newState);
    }
 
    /**
     * Get the date and time when the state was last updated.
     * @param options
     * @category State
     */
    async getDateTime(options: NodePyATVGetStateOptions = {}): Promise<Date | null> {
        const state = await this.getState(options);
        return state.dateTime;
    }
 
    /**
     * Get the hash of the current media
     * @param options
     * @category State
     */
    async getHash(options: NodePyATVGetStateOptions = {}): Promise<string | null> {
        const state = await this.getState(options);
        return state.hash;
    }
 
    /**
     * Get the media type of the current media
     * @param options
     * @category State
     */
    async getMediaType(options: NodePyATVGetStateOptions = {}): Promise<NodePyATVMediaType | null> {
        const state = await this.getState(options);
        return state.mediaType;
    }
 
    /**
     * Get the state of this device (e.g. playing, etc.)
     * @param options
     * @category State
     */
    async getDeviceState(options: NodePyATVGetStateOptions = {}): Promise<NodePyATVDeviceState | null> {
        const state = await this.getState(options);
        return state.deviceState;
    }
 
    /**
     * Returns the title of the current playing media
     * @param options
     * @category State
     */
    async getTitle(options: NodePyATVGetStateOptions = {}): Promise<string | null> {
        const state = await this.getState(options);
        return state.title;
    }
 
    /**
     * Returns the artist of the current playing media
     * @param options
     * @category State
     */
    async getArtist(options: NodePyATVGetStateOptions = {}): Promise<string | null> {
        const state = await this.getState(options);
        return state.artist;
    }
 
    /**
     * Returns the album of the current playing media
     * @param options
     * @category State
     */
    async getAlbum(options: NodePyATVGetStateOptions = {}): Promise<string | null> {
        const state = await this.getState(options);
        return state.album;
    }
 
    /**
     * Returns the genre of the current playing media
     * @param options
     * @category State
     */
    async getGenre(options: NodePyATVGetStateOptions = {}): Promise<string | null> {
        const state = await this.getState(options);
        return state.genre;
    }
 
    /**
     * Returns the media length of the current playing media
     * @param options
     * @category State
     */
    async getTotalTime(options: NodePyATVGetStateOptions = {}): Promise<number | null> {
        const state = await this.getState(options);
        return state.totalTime;
    }
 
    /**
     * Returns the title of the current playing media
     * @param options
     * @category State
     */
    async getPosition(options: NodePyATVGetStateOptions = {}): Promise<number | null> {
        const state = await this.getState(options);
        return state.position;
    }
 
    /**
     * Returns the shuffle state
     * @param options
     * @category State
     */
    async getShuffle(options: NodePyATVGetStateOptions = {}): Promise<NodePyATVShuffleState | null> {
        const state = await this.getState(options);
        return state.shuffle;
    }
 
    /**
     * Returns the repeat state
     * @param options
     * @category State
     */
    async getRepeat(options: NodePyATVGetStateOptions = {}): Promise<NodePyATVRepeatState | null> {
        const state = await this.getState(options);
        return state.repeat;
    }
 
    /**
     * Returns the currently used app
     * @param options
     * @category State
     */
    async getApp(options: NodePyATVGetStateOptions = {}): Promise<string | null> {
        const state = await this.getState(options);
        return state.app;
    }
 
    /**
     * Returns the id of the currently used app
     * @param options
     * @category State
     */
    async getAppId(options: NodePyATVGetStateOptions = {}): Promise<string | null> {
        const state = await this.getState(options);
        return state.appId;
    }
 
    private async _pressKey(key: NodePyATVInternalKeys) {
        const id = addRequestId();
        const parameters = getParamters(this.options);
 
        const result = await request(id, NodePyATVExecutableType.atvscript, [...parameters, key], this.options);
        if (typeof result !== 'object' || result.result !== 'success') {
            throw new Error(`Unable to parse pyatv response: ${JSON.stringify(result, null, '  ')}`);
        }
 
        removeRequestId(id);
    }
 
    /**
     * Send a key press to the Apple TV
     *
     * ```typescript
     * await device.pressKey(NodePyATVKeys.home);
     * ```
     *
     * <br />
     *
     * ```javascript
     * await device.pressKey('home');
     * ```
     *
     * @param key
     * @category Control
     */
    async pressKey(key: NodePyATVKeys): Promise<void> {
        const internalKeyEntry = Object.entries(NodePyATVInternalKeys)
            .find(([k]) => key === k);
 
        if(!internalKeyEntry) {
            throw new Error(`Unsupported key value ${key}!`);
        }
 
        const internalKey = internalKeyEntry[1];
        await this._pressKey(internalKey);
    }
 
    /**
     * Send the "down" command
     * @category Control
     */
    async down(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.down);
    }
 
    /**
     * Send the "home" command
     * @category Control
     */
    async home(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.home);
    }
 
    /**
     * Send the "homeHold" command
     * @category Control
     */
    async homeHold(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.homeHold);
    }
 
    /**
     * Send the "left" command
     * @category Control
     */
    async left(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.left);
    }
 
    /**
     * Send the "menu" command
     * @category Control
     */
    async menu(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.menu);
    }
 
    /**
     * Send the "next" command
     * @category Control
     */
    async next(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.next);
    }
 
    /**
     * Send the "pause" command
     * @category Control
     */
    async pause(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.pause);
    }
 
    /**
     * Send the "play" command
     * @category Control
     */
    async play(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.play);
    }
 
    /**
     * Send the "playPause" command
     * @category Control
     */
    async playPause(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.playPause);
    }
 
    /**
     * Send the "previous" command
     * @category Control
     */
    async previous(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.previous);
    }
 
    /**
     * Send the "right" command
     * @category Control
     */
    async right(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.right);
    }
 
    /**
     * Send the "select" command
     * @category Control
     */
    async select(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.select);
    }
 
    /**
     * Send the "skipBackward" command
     * @category Control
     */
    async skipBackward(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.skipBackward);
    }
 
    /**
     * Send the "skipForward" command
     * @category Control
     */
    async skipForward(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.skipForward);
    }
 
    /**
     * Send the "stop" command
     * @category Control
     */
    async stop(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.stop);
    }
 
    /**
     * Send the "suspend" command
     * @category Control
     */
    async suspend(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.suspend);
    }
 
    /**
     * Send the "topMenu" command
     * @category Control
     */
    async topMenu(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.topMenu);
    }
 
    /**
     * Send the "up" command
     * @category Control
     */
    async up(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.up);
    }
 
    /**
     * Send the "volumeDown" command
     * @category Control
     */
    async volumeDown(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.volumeDown);
    }
 
    /**
     * Send the "volumeUp" command
     * @category Control
     */
    async volumeUp(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.volumeUp);
    }
 
    /**
     * Send the "wakeup" command
     * @category Control
     */
    async wakeup(): Promise<void> {
        await this._pressKey(NodePyATVInternalKeys.wakeup);
    }
 
    /**
     * Add an event listener. Will start the event subscription with the
     * Apple TV as long as there are listeners for any event registered.
     * @param event
     * @param listener
     * @category Event
     */
    addListener(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        this.events.addListener(event, listener);
        return this;
    }
 
    /**
     * Emit an event.
     * @param event
     * @param payload
     * @category Event
     */
    emit(event: string | symbol, payload: NodePyATVDeviceEvent): boolean {
        return this.events.emit(event, payload);
    }
 
    /**
     * Get all event names which are currently known.
     * @category Event
     */
    eventNames(): Array<string | symbol> {
        return this.events.eventNames();
    }
 
    /**
     * Get max number of listeners allowed
     * @category Event
     */
    getMaxListeners(): number {
        return this.events.getMaxListeners();
    }
 
    /**
     * Get number of listeners for event
     * @param event
     * @category Event
     */
    listenerCount(event: string | symbol): number {
        return this.events.listenerCount(event);
    }
 
    /**
     * Get listeners for event. Will also return
     * node-pyatv wrappers (e.g. once)
     *
     * @param event
     * @category Event
     */
    // eslint-disable-next-line @typescript-eslint/ban-types
    listeners(event: string | symbol): Function[] {
        return this.events.listeners(event);
    }
 
    /**
     * Remove an event listener. Will stop the event subscription with the
     * Apple TV if this was the last event listener.
     * @param event
     * @param listener
     * @category Event
     */
    off(event: string | symbol, listener: (event: NodePyATVDeviceEvent | Error) => void): this {
        this.events.off(event, listener);
        return this;
    }
 
    /**
     * Add an event listener. Will start the event subscription with the
     * Apple TV as long as there are listeners for any event registered.
     * @param event
     * @param listener
     * @category Event
     */
    on(event: string | symbol, listener: (event: NodePyATVDeviceEvent | Error) => void): this {
        this.events.on(event, listener);
        return this;
    }
 
    /**
     * Add an event listener. Will start the event subscription with the
     * Apple TV as long as there are listeners for any event registered.
     * Removes the listener automatically after the first occurrence.
     * @param event
     * @param listener
     * @category Event
     */
    once(event: string | symbol, listener: (event: NodePyATVDeviceEvent | Error) => void): this {
        this.events.once(event, listener);
        return this;
    }
 
    /**
     * @param event
     * @param listener
     * @category Event
     */
    prependListener(event: string | symbol, listener: (event: NodePyATVDeviceEvent | Error) => void): this {
        this.events.prependListener(event, listener);
        return this;
    }
 
    /**
     * @param event
     * @param listener
     * @category Event
     */
    prependOnceListener(event: string | symbol, listener: (event: NodePyATVDeviceEvent | Error) => void): this {
        this.events.prependOnceListener(event, listener);
        return this;
    }
 
    /**
     * @param event
     * @category Event
     */
    // eslint-disable-next-line @typescript-eslint/ban-types
    rawListeners(event: string | symbol): Function[] {
        return this.events.rawListeners(event);
    }
 
    /**
     * Removes all listeners, either for the given event or
     * for every event. Will stop the event subscription with
     * the Apple TV if this was the last event listener.
     *
     * @param event
     * @category Event
     */
    removeAllListeners(event?: string | symbol): this {
        this.events.removeAllListeners(event);
        return this;
    }
 
    /**
     * Remove an event listener. Will stop the event subscription with the
     * Apple TV if this was the last event listener.
     * @param event
     * @param listener
     * @category Event
     */
    removeListener(event: string | symbol, listener: (event: NodePyATVDeviceEvent) => void): this {
        this.events.removeListener(event, listener);
        return this;
    }
 
    /**
     * @param n
     * @category Event
     */
    setMaxListeners(n: number): this {
        this.events.setMaxListeners(n);
        return this;
    }
}