User:Dagger/Widget drafts/API preferences.js

From Guild Wars 2 Wiki
Jump to navigationJump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
// This should be in the HTML part of a widget, but since I don't have widget edit permissions...
$(function() {
  if (!$('#api-preferences').length) return;
  
  var fieldset = $('<fieldset/>');
  fieldset.append($('<legend>API settings</legend>'));
  fieldset.append($('<label for="api-key">Key: </label>'));
  var keyInput = $('<input/>', {
    id: "api-key",
    value: localStorage.getItem("api-key"),
    style: "width: 40em;",
  });
  fieldset.append(keyInput);
  fieldset.append($('<button id="api-setkey">Save</button>'));
  fieldset.append($('<br/>'));
  fieldset.append("The key must have the following permissions: account, inventories, characters, wallet, unlocks, progression.");

  $('#api-preferences').append(fieldset);
});

// And this shouldn't be in any of the widgets.
$(function() {
  // Add link to preferences.
  mw.util.addPortletLink("p-navigation", 
    mw.util.wikiGetlink("User:Dagger/API settings"),
    "Set an API key", "t-apisettings", null, null, null);
});

// Aha. Code that should be in the widget.
$(function() {
  $("button#api-setkey").on("click", function(evt) {
    var key = $("#api-key").val()
    if (!key) {
      localStorage.removeItem("api-key");
      localStorage.removeItem("api-key-permissions");
      for (var key in localStorage)
        if (key.match(/^api-cache-/)) localStorage.removeItem(key);
      alert("API key and local cache cleared.");
    } else {
      evt.target.setAttribute("disabled", "true");
      $.getJSON("https://api.guildwars2.com/v2/tokeninfo?access_token="+key).then(function(info) {
        var perms = info.permissions;
        localStorage.setItem("api-key", $("#api-key").val());
        localStorage.setItem("api-key-permissions", JSON.stringify(perms));

        var required = ["account", "inventories", "characters", "wallet", "unlocks", "progression"];
        if (!required.every(function(p) { return perms.indexOf(p) != -1 })) {
          alert("Some of the required permissions are missing from this key. Some features will fail to work.");
        } else {
          alert("Key saved.");
        }
        evt.target.removeAttribute("disabled");
      }, function onFail(f) {
        alert("Couldn't verify that the API key was valid.");
        evt.target.removeAttribute("disabled");
        if (console && console.log) console.log("Error", f);
      });
    }
  });
});