All files / src/init init.js

68.13% Statements 62/91
40.79% Branches 31/76
85.71% Functions 6/7
68.13% Lines 62/91
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                                                                                                                                                                                                                                                                                          31x                   159x           159x             159x         159x           159x         159x       159x         159x       159x                           159x                                                                                 159x               159x         159x         159x               159x                       159x           159x                       159x             159x 159x                                                                     159x 159x           159x                             159x             159x                       159x               159x           159x             159x               159x               159x                 159x         159x             159x         159x                 159x           159x 159x                 159x     159x           159x           159x                                                                                                                                                 159x                         159x         159x         159x         159x         159x         159x         159x         159x                                 159x             159x 477x 477x             159x         159x                 159x 1749x 1749x               31x                
/**
 * Imports the config module
 * @module config
 */
import config from "../config.js";
 
/**
 * AmplitudeJS Core Module
 * @module core/Core
 */
import Core from "../core/core.js";
 
/**
 * AmplitudeJS SoundCloud Module
 * @module soundcloud/SoundCloud
 */
import SoundCloud from "../soundcloud/soundcloud.js";
 
/**
 * Imports the utilities used by the main module.
 */
/**
 * AmplitudeJS Config State Module
 * @module utilities/ConfigState
 */
import ConfigState from "../utilities/configState.js";
 
/**
 * AmplitudeJS Debug Module
 * @module utilities/Debug
 */
import Debug from "../utilities/debug.js";
 
/**
 * AmplitudeJS Checks Module
 * @module utilities/Checks
 */
import Checks from "../utilities/checks.js";
 
/**
 * AmplitudeJS Shuffler Module
 * @module utilities/Shuffler
 */
import Shuffler from "../utilities/shuffler.js";
 
/**
 * AmplitudeJS Events Module
 * @module events/Events
 */
import Events from "../events/events.js";
 
/**
 * AmplitudeJS FX Module
 * @module fx/Fx
 */
import Fx from "../fx/fx.js";
 
/**
 * AmplitudeJS Visualizations Module
 * @module fx/Visualizations
 */
import Visualizations from "../fx/visualizations.js";
 
/**
 * AmplitudeJS WaveForm Module
 * @module fx/WaveForm
 */
import WaveForm from "../fx/waveform.js";
 
/**
 * AmplitudeJS Audio Navigation Module.
 * @module utilities/AudioNavigation
 */
import AudioNavigation from "../utilities/audioNavigation.js";
 
/**
 * AmplitudeJS Callbacks Module
 * @module utilities/Callbacks
 */
import Callbacks from "../utilities/callbacks.js";
 
/**
 * AmplitudeJS Playlists Initializer Module
 * @module init/Playlists
 */
import PlaylistsInitializer from "./playlists.js";
 
/**
 * Imports the AmplitudeJS Shuffle Elements
 * @module visual/ShuffleElements
 */
import ShuffleElements from "../visual/shuffleElements.js";
 
/**
 * Imports the AmplitudeJS Mute Elements
 * @module visual/MuteElements
 */
import MuteElements from "../visual/muteElements.js";
 
/**
 * Imports the AmplitudeJS Volume Slider
 * @module visual/VolumeSliderElements
 */
import VolumeSliderElements from "../visual/volumeSliderElements.js";
 
/**
 * Imports the AmplitudeJS Time Elements
 * @module visual/TimeElements
 */
import TimeElements from "../visual/timeElements.js";
 
/**
 * Imports the AmplitudeJS Play/Pause Elements Module.
 * @module visual/PlayPauseElements
 */
import PlayPauseElements from "../visual/playPauseElements.js";
 
/**
 * Imports the AmplitudeJS MetaData Elements Module.
 * @module visual/MetaDataElements
 */
import MetaDataElements from "../visual/metaDataElements.js";
 
/**
 * Imports the AmplitudeJS PlaybackSpeedElements Module.
 * @module visual/PlayBackSpeedElements
 */
import PlaybackSpeedElements from "../visual/playbackSpeedElements.js";
 
/**
 * Imports the AmplitudeJS Repeat Element
 * @module visual/RepeatElements
 */
import RepeatElements from "../visual/repeatElements.js";
 
/**
 * AmplitudeJS Initializer Module. Helps with the handling of all of the
 * initialization for AmplitudeJS.
 *
 * @module init/Initializer
 */
let Initializer = (function() {
  /**
   * The main init function.  The user will call this through
   * Amplitude.init({}) and pass in their settings.
   *
   * Public Accessor: Amplitude.init( user_config_json )
   * @access public
   * @param {object} userConfig - A JSON object of user defined values that help configure and initialize AmplitudeJS.
   */
  function initialize(userConfig) {
    let ready = false;
 
    /*
			Reset the config on init so we have a clean slate. This is if the
			user has to re-init.
		*/
    ConfigState.resetConfig();
 
    /*
			Initialize event handlers on init. This will clear any old
			event handlers on the amplitude element and re-bind what is
			necessary.
		*/
    Events.initialize();
 
    /*
      Initialize the callbacks we listen to for the audio object.
    */
    Callbacks.initialize();
 
    /*
			Initializes debugging right away so we can use it for the rest
			of the configuration.
		*/
    config.debug = userConfig.debug != undefined ? userConfig.debug : false;
 
    /*
			Checks to see if the user has songs defined.
		*/
    Eif (userConfig.songs) {
      /*
				Checks to see if the user has some songs in the songs array.
			*/
      Eif (userConfig.songs.length != 0) {
        /*
					Copies over the user defined songs. and prepares
					Amplitude for the rest of the configuration.
				*/
        config.songs = userConfig.songs;
        /*
					Flag amplitude as ready.
				*/
        ready = true;
      } else {
        Debug.writeMessage("Please add some songs, to your songs object!");
      }
    } else {
      Debug.writeMessage(
        "Please provide a songs object for AmplitudeJS to run!"
      );
    }
 
    /*
			Initializes the audio context. In this method it checks to see if the
			user wants to use visualizations or not before proceeding.
		*/
    Iif (Fx.webAudioAPIAvailable()) {
      /*
        Configure the Web Audio API If It's available.
      */
      Fx.configureWebAudioAPI();
 
      /*
        Set the user waveform settings if provided.
      */
      if (
        userConfig.waveforms != undefined &&
        userConfig.waveforms.sample_rate != undefined
      ) {
        config.waveforms.sample_rate = userConfig.waveforms.sample_rate;
      }
 
      /*
        Initialize the waveform.
      */
      WaveForm.init();
 
      /*
        If the user is registering visualizations on init,
        we set them right away.
      */
      if (
        userConfig.visualizations != undefined &&
        userConfig.visualizations.length > 0
      ) {
        /*
              Iterate over all of the visualizations and
              register them in our player.
            */
        for (let i = 0; i < userConfig.visualizations.length; i++) {
          Visualizations.register(
            userConfig.visualizations[i].object,
            userConfig.visualizations[i].params
          );
        }
      }
    } else {
      Debug.writeMessage(
        "The Web Audio API is not available on this platform. We are using your defined backups!"
      );
    }
 
    /*
      Initialize default live settings
    */
    initializeDefaultLiveSettings();
 
    /*
			When the preliminary config is ready, we are ready to proceed.
		*/
    Eif (ready) {
      /*
				Copies over the soundcloud information to the global config
				which will determine where we go from there.
			*/
      config.soundcloud_client =
        userConfig.soundcloud_client != undefined
          ? userConfig.soundcloud_client
          : "";
 
      /*
				Checks if we want to use the art loaded from soundcloud.
			*/
      config.soundcloud_use_art =
        userConfig.soundcloud_use_art != undefined
          ? userConfig.soundcloud_use_art
          : "";
 
      /*
				If the user provides a soundcloud client then we assume that
				there are URLs in their songs that will reference SoundCloud.
				We then copy over the user config they provided to the
				temp_user_config so we don't mess up the global or their configs
				and load the soundcloud information.
			*/
      let tempUserConfig = {};
 
      /*
        If there's a soundcloud_client key set, we load the SoundCloud data
        for all of the songs in the array.
      */
      Iif (config.soundcloud_client != "") {
        tempUserConfig = userConfig;
 
        /*
					Load up SoundCloud for use with AmplitudeJS.
				*/
        SoundCloud.loadSoundCloud(tempUserConfig);
      } else {
        /*
					The user is not using Soundcloud with Amplitude at this point
					so we just finish the configuration with the users's preferences.
				*/
        setConfig(userConfig);
      }
    }
 
    /*
			Debug out what was initialized with AmplitudeJS.
		*/
    Debug.writeMessage("Initialized With: ");
    Debug.writeMessage(config);
  }
 
  /**
   * Rebinds all of the elements in the display.
   *
   * Public Accessor: Amplitude.rebindDisplay()
   * @access public
   */
  function rebindDisplay() {
    AmplitudeEvents.initializeEvents();
    AmplitudeVisualSync.displaySongMetadata();
  }
 
  /**
   * Finishes the initalization of the config. Takes all of the user defined
   * parameters and makes sure they override the defaults. The important
   * config information is assigned in the publicInit() function.
   *
   * This function can be called from 2 different locations:
   * 	1. Right away on init after the important settings are defined.
   *
   * 	2. After all of the Soundcloud URLs are resolved properly and
   *	 	soundcloud is configured.  We will need the proper URLs from Soundcloud
   * 		to stream through Amplitude so we get those right away before we
   * 		set the information and the active song
   *
   * @access public
   * @param {object} userConfig - A JSON object of user defined values that help configure and initialize AmplitudeJS.
   */
  function setConfig(userConfig) {
    /*
      Checks if the user has any playlists defined. If they do
      we have to initialize the functionality for the playlists.
    */
    Eif (userConfig.playlists && countPlaylists(userConfig.playlists) > 0) {
      PlaylistsInitializer.initialize(userConfig.playlists);
    }
 
    /*
			Check to see if the user entered a start song
		*/
    Iif (userConfig.start_song != undefined && userConfig.starting_playlist) {
      /*
				Ensure what has been entered is an integer.
			*/
      if (Checks.isInt(userConfig.start_song)) {
        AudioNavigation.changeSong(
          config.songs[userConfig.start_song],
          userConfig.start_song
        );
      } else {
        Debug.writeMessage(
          "You must enter an integer index for the start song."
        );
      }
    } else {
      AudioNavigation.changeSong(config.songs[0], 0);
    }
 
    /*
      If the shuffle is on by default, shuffle the songs and
      switch to the shuffled song.
    */
    Iif (userConfig.shuffle_on != undefined && userConfig.shuffle_on) {
      config.shuffle_on = true;
      Shuffler.shuffleSongs();
 
      AudioNavigation.changeSong(config.shuffle_list[0], 0);
    }
 
    /*
			Allows the user to set whether they want to continue to the next song
			when the current song finishes or not. In any scenario that's not a playlist,
			contining to the next song may not be desired.
		*/
    config.continue_next =
      userConfig.continue_next != undefined ? userConfig.continue_next : true;
 
    /*
			If the user defined a playback speed, we copy over their
			preference here, otherwise we default to normal playback
			speed of 1.0.
		*/
    config.playback_speed =
      userConfig.playback_speed != undefined ? userConfig.playback_speed : 1.0;
 
    /*
			Sets the audio playback speed.
		*/
    Core.setPlaybackSpeed(config.playback_speed);
 
    /*
			If the user wants the song to be pre-loaded for instant
			playback, they set it to true. By default it's set to just
			load the metadata.
		*/
    config.audio.preload =
      userConfig.preload != undefined ? userConfig.preload : "auto";
 
    /*
			Initializes the user defined callbacks. This should be a JSON
			object that contains a key->value store of the callback name
			and the name of the function the user needs to call.
		*/
    config.callbacks =
      userConfig.callbacks != undefined ? userConfig.callbacks : {};
 
    /*
			Initializes the user defined key bindings. This should be a JSON
			object that contains a key->value store of the key event number
			pressed and the method to be run.
		*/
    config.bindings =
      userConfig.bindings != undefined ? userConfig.bindings : {};
 
    /*
			The user can define a starting volume in a range of 0-100 with
			0 being muted and 100 being the loudest. After the config is set
			Amplitude sets the active song's volume to the volume defined
			by the user.
		*/
    config.volume = userConfig.volume != undefined ? userConfig.volume : 50;
 
    /*
			Sets the delay between songs if the user has it set. This should be in MS.
		*/
    config.delay = userConfig.delay != undefined ? userConfig.delay : 0;
 
    /*
			The user can set the volume increment and decrement values between 1 and 100
			for when the volume up or down button is pressed.  The default is an increase
			or decrease of 5.
		*/
    config.volume_increment =
      userConfig.volume_increment != undefined
        ? userConfig.volume_increment
        : 5;
 
    config.volume_decrement =
      userConfig.volume_decrement != undefined
        ? userConfig.volume_decrement
        : 5;
 
    /*
			Set the volume to what is defined in the config. The user can define this,
			so we should set it up that way.
		*/
    Core.setVolume(config.volume);
 
    /*
			If the user defines default album art, this image will display if the active
			song doesn't have album art defined.
		*/
    Eif (userConfig.default_album_art != undefined) {
      config.default_album_art = userConfig.default_album_art;
    } else {
      config.default_album_art = "";
    }
 
    /*
			If the user defines default playlist art, this image will display if the user
			tries to set up a playlist meta data image tag but doesn't have one defined.
		*/
    Iif (userConfig.default_playlist_art != undefined) {
      config.default_playlist_art = userConfig.default_playlist_art;
    } else {
      config.default_playlist_art = "";
    }
 
    /*
      Initialize the visual elements
    */
    initializeElements();
 
    /*
			If the user has selected a starting playlist, we need to set the starting playlist
			and sync the visuals
		*/
    Iif (
      userConfig.starting_playlist != undefined &&
      userConfig.starting_playlist != ""
    ) {
      /*
				Set the active playlist to the starting playlist by the user
			*/
      config.active_playlist = userConfig.starting_playlist;
 
      /*
				Check if the user defined a song to start with in the playlist.
			*/
      if (
        userConfig.starting_playlist_song != undefined &&
        userConfig.starting_playlist_song != ""
      ) {
        /*
					Ensure the song is a valid index.
				*/
        if (
          typeof userConfig.playlists[userConfig.starting_playlist].songs[
            parseInt(userConfig.starting_playlist_song)
          ] != undefined
        ) {
          /*
						Set the player to the song defined by the user.
					*/
          AudioNavigation.changeSongPlaylist(
            config.active_playlist,
            userConfig.playlists[userConfig.starting_playlist].songs[
              parseInt(userConfig.starting_playlist_song)
            ],
            parseInt(userConfig.starting_playlist_song)
          );
        } else {
          /*
						Set the player to the first song in the playlist
					*/
          AudioNavigation.changeSongPlaylist(
            config.active_playlist,
            userConfig.playlists[userConfig.starting_playlist].songs[0],
            0
          );
          /*
						Debug that the song index doesn't exist
					*/
          Debug.writeMessage(
            "The index of " +
              userConfig.starting_playlist_song +
              " does not exist in the playlist " +
              userConfig.starting_playlist
          );
        }
      } else {
        /*
					Set the player to the first song in the playlist
				*/
        AudioNavigation.changeSong(
          config.active_playlist,
          userConfig.playlists[userConfig.starting_playlist].songs[0],
          0
        );
      }
 
      /*
				Sync the main and song play pause buttons.
			*/
      PlayPauseElements.sync();
    }
 
    /*
			Run after init callback
		*/
    Callbacks.run("initialized");
  }
 
  /**
   * Initializes all of the elements on the page to the default starting point
   * to build from there.
   *
   * @access private
   */
  function initializeElements() {
    /*
			Visually sync the shuffle statuses
		*/
    ShuffleElements.syncMain();
 
    /*
			Sync Mute Elements.
		*/
    MuteElements.setMuted(config.volume == 0 ? true : false);
 
    /*
			Sync Volume Slider Elements
		*/
    VolumeSliderElements.sync();
 
    /*
			Syncs all of the playback speed elements.
		*/
    PlaybackSpeedElements.sync();
 
    /*
			Syncs all of the visual time elements to 00.
		*/
    TimeElements.resetCurrentTimes();
 
    /*
			Sets all of the play pause buttons to pause.
		*/
    PlayPauseElements.syncToPause();
 
    /*
			Sets the meta data for the songs automatically.
		*/
    MetaDataElements.syncMetaData();
 
    /*
			Sets the repeat buttons automatically.
		*/
    RepeatElements.syncRepeatSong();
  }
 
  /**
   * Counts the number of playlists the user has configured. This ensures
   * that the user has at least 1 playlist so we can validate the songs
   * defined in the playlist are correct and they didn't enter an invalid
   * ID.
   *
   * @access private
   * @param {object} playlists 	-
   */
  function countPlaylists(playlists) {
    /*
			Initialize the placeholders to iterate through the playlists
			and find out how many we have to account for.
		*/
    let size = 0,
      key;
 
    /*
			Iterate over playlists and if the user has the playlist defined,
			increment the size of playlists.
		*/
    for (key in playlists) {
      Eif (playlists.hasOwnProperty(key)) {
        size++;
      }
    }
 
    /*
			Debug how many playlists are in the config.
		*/
    Debug.writeMessage("You have " + size + " playlist(s) in your config");
 
    /*
			Return the number of playlists in the config.
		*/
    return size;
  }
 
  /**
   * Intializes the default live settings for all of the songs.
   *
   * @access private
   */
  function initializeDefaultLiveSettings() {
    for (let i = 0; i < config.songs.length; i++) {
      Eif (config.songs[i].live == undefined) {
        config.songs[i].live = false;
      }
    }
  }
 
  /*
		Returns the publicly accessible methods
	*/
  return {
    initialize: initialize,
    setConfig: setConfig,
    rebindDisplay: rebindDisplay
  };
})();
 
export default Initializer;