Waniarik / OG-SoundAlert

// ==UserScript==
// @name        OG-SoundAlert
// @description Create sound alert and fire web notification on Ogame when an attacke/spy is detected.
// @include     *.ogame*gameforge.com/game/index.php*
// @author      Draym, Waniarik
// @copyright   2019, Draym (draymlab.fr)
// @license     MIT
// @version     2.0.0.3.2
// @updateURL https://openuserjs.org/meta/Waniarik/OG-SoundAlert.meta.js
// @downloadURL https://openuserjs.org/install/Waniarik/OG-SoundAlert.user.js
// @grant          GM_getValue
// @grant          GM_setValue
// @grant          GM_addStyle
// ==/UserScript==

// ==OpenUserJS==
// @author Waniarik
// ==/OpenUserJS==

// DISCLAIMER:
// This script is against Ogame rules, use at your own risk - !!YOU MAY GET BANNED!!

// I would like to honor great work on this script by Draym, i just needed to update the script so I could use it on speed server, thus my changes.
// Changelog by Waniarik
// 2.0.0.3.1
// - replace expired alarm sound link (with stargate alarm cuz I just like it)
// - add sound for long time attack (#attack_alert.today) with parameter for different alarm sound
// - sound alarm is now playing in loop
// - rework random time
// 2.0.0.3.2
// - reload only on the main (overview) page
// - add volume parameter
// - hitting switch button will disable playing audio immedialy
// - different sound when being spied

(function () {
  'use strict';

  /* **************************************************************/
  /* ******************** PARAMETERS ******************************/
  /* **************************************************************/
  var sa_sound_today = 'https://raw.githubusercontent.com/RafaelDeJongh/cap_resources/91fa2364909fced146c9fb8c89b87494751b8303/sound/janus/janus_wall_tone_3.wav';
  var sa_sound_soon = 'https://raw.githubusercontent.com/RafaelDeJongh/cap_resources/91fa2364909fced146c9fb8c89b87494751b8303/sound/alarm/sgc_alarm.wav';
  var sa_sound_spy = 'https://raw.githubusercontent.com/RafaelDeJongh/cap_resources/91fa2364909fced146c9fb8c89b87494751b8303/sound/janus/janus_wall_tone_1.wav';
  var sa_minutes = 1; // something superior to 1. A random seconds will be added to it.
  var sa_random = 20; // random pick seconds within this number
  var sa_volume = 40; // volume of sound in percentage

  /* **************************************************************/
  /* ********************** SCRIPT ********************************/
  /* **************************************************************/
  var $ = unsafeWindow.$;
  var sa_eventAlert = document.createElement('audio');
  sa_eventAlert.volume = (sa_volume / 100);
  var sa_time = ((sa_minutes * 60) + (Math.floor(Math.random() * sa_random))) * 1000;
  var sa_context = new AudioContext();
  var sa_notificationDetails = {
    title: 'Ogame Alert',
    text: 'You are under attack on Ogame',
    timeout: 15000,
    icon: 'https://is4-ssl.mzstatic.com/image/thumb/Purple91/v4/31/2d/98/312d98f7-b935-69b3-596e-2159d13c0865/mzl.kxpdlefq.png/246x0w.jpg',
    onclick: function () {
      window.focus();
    }
  };

  function sa_playAlert() {
    sa_context.resume().then(() => {
      sa_eventAlert.preload = 'auto';
      GM_notification(sa_notificationDetails);
      if (typeof sa_eventAlert.loop == 'boolean')
      {
          sa_eventAlert.loop = true;
      }
      else
      {
          sa_eventAlert.addEventListener('ended', function() {
              this.currentTime = 0;
              this.play();
          }, false);
      }
      sa_eventAlert.play();
      console.log('Playback resumed successfully');
    });
  }

  function sa_reload() {
    setTimeout(function () {
      if (GM_getValue('sa_toggleOn') === true && (/component=overview/.test(location.href))) {
        location.reload();
      }
    }, sa_time);
  }

  function sa_checkAlerts() {
    if ($('#attack_alert').hasClass("soon") || $('#attack_alert').hasClass("today")) {
      var events = document.getElementsByClassName('eventFleet');
      var attack = false;
      for (i = 0; i < events.length; i++) {
        if (events[i].innerHTML.match('hostile') && events[i].getAttribute('data-mission-type') == 1) {
          if ($('#attack_alert').hasClass("soon")) {
            sa_eventAlert.src = sa_sound_soon;
            sa_playAlert();
          } else if ($('#attack_alert').hasClass("today")) {
            sa_eventAlert.src = sa_sound_today;
            sa_playAlert();
          }
          attack = true;
          break;
        }
      }
      if (attack === false) {
        sa_eventAlert.src = sa_sound_spy;
        sa_playAlert();
      }
    }
  }

  /*--- Cross-browser Shim code follows:*/
  function sa_shim_GM_notification() {
    if (typeof GM_notification === "function") {
      return;
    }
    window.GM_notification = function (ntcOptions) {
      checkPermission();

      function askPermission() {
        Notification.requestPermission(function (permission) {
          console.log("New permission: ", permission);
          checkPermission();
        });
      }

      function checkPermission() {
        if (Notification.permission === "granted") {
          fireNotice();
        }
        else if (Notification.permission === "denied") {
          console.log("User has denied notifications for this page/site!");
          askPermission();
        }
        else {
          askPermission();
        }
      }

      function fireNotice() {
        if (!ntcOptions.title) {
          console.log("Title is required for notification");
          return;
        }
        if (ntcOptions.text && !ntcOptions.body) {
          ntcOptions.body = ntcOptions.text;
        }
        var ntfctn = new Notification(ntcOptions.title, ntcOptions);

        if (ntcOptions.onclick) {
          ntfctn.onclick = ntcOptions.onclick;
        }
        if (ntcOptions.timeout) {
          setTimeout(function () {
            ntfctn.close();
          }, ntcOptions.timeout);
        }
      }
    }
  }

  /* **************************************************************/
  /* ********************* STARTUP ********************************/
  /* **************************************************************/
  function launch() {
    sa_shim_GM_notification();
    sa_checkAlerts();
    sa_reload();
  }

  /* **************************************************************/
  /* *********************** GUI **********************************/
  /* **************************************************************/
  function sa_drawMenu() {}

  unsafeWindow.sa_handleClick = function (cb) {
    GM_setValue('sa_toggleOn', cb.checked);
    let isToggle = GM_getValue("sa_toggleOn");
    if (!isToggle) {
      sa_eventAlert.pause();
    }

    if (isToggle) {
      launch();
    }
  }

  if (!/page=empire/.test(location.href)) {
    var aff_option = `
<span class="menu_icon">
<label class="tooltipRight js_hideTipOnMobile sa-switch">
<input id="cbActiveSA" type="checkbox" onclick="sa_handleClick(this);">
<span class="sa-slider round"></span>
</label>
</span>
<a id="drawOptionSA" class="menubutton" href="#" accesskey="" target="_self">
<span  class="textlabel">Alert
</span></a>`;
    var tableau = document.createElement("li");
    tableau.innerHTML = aff_option;
    /*tableau.className += "custom-option";*/
    tableau.id = 'option-SoundAlert';
    document.getElementById('menuTable').appendChild(tableau);

    let isToggle = GM_getValue("sa_toggleOn");
    $("#cbActiveSA").prop('checked', isToggle ? isToggle : false);
    document.getElementById('drawOptionSA').addEventListener("click", function (event) {
      sa_drawMenu();
    }, true);

    if (isToggle) {
      launch();
    }
  }
  /* **************************************************************/
  /* ************************ CSS *********************************/
  /* **************************************************************/

  GM_addStyle(`
/*** THEME ***/
#menuTable > .custom-option {
margin-top: 10px !important;
margin-bottom: 10px !important;
}
#menuTable > .custom-option ~ .custom-option {
margin-top: -10px !important;
margin-bottom: 10px !important;
}
.custom-option a span {
color: #68a2ff !important;
}

/*** TOGGLE SWITCH ***/
.sa-switch {
  position: relative;
  display: inline-block;
  width: 30px;
  height: 17px;
  margin-top: 5px;
}
.sa-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}
.sa-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ff4949;
  -webkit-transition: .4s;
  transition: .4s;
}
.sa-slider:before {
  position: absolute;
  content: "";
  height: 13px;
  width: 13px;
  left: 2px;
  bottom: 2px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}
input:checked + .sa-slider {
  background-color: #0664b0;
}
input:focus + .sa-slider {
  box-shadow: 0 0 1px #0664b0;
}
input:checked + .sa-slider:before {
  -webkit-transform: translateX(13px);
  -ms-transform: translateX(13px);
  transform: translateX(13px);
}
.sa-slider.round {
  border-radius: 17px;
}
.sa-slider.round:before {
  border-radius: 50%;
}
`);
})();