PIlfer / gymscraping-gymhuntr

// ==UserScript==
// @name         gymscraping-gymhuntr
// @namespace    http://tampermonkey.net/
// @version      0.4
// @description  try to take over the world!
// @author       You
// @license  MIT
// @require http://code.jquery.com/jquery-1.12.4.min.js
// @require https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js
// @match        *gymhuntr.com*
// @grant        none
// ==/UserScript==

var spacer = Array(30).join("#");

// download a file on html5 ready browsers
var showDownloadButton = function(){
  if(window.DOWNLOADBUTTON_SHOWN == true) return;
  window.DOWNLOADBUTTON_SHOWN = true;
  var button = document.createElement("button");
  button.innerHTML = "Download Gyms CSV";
  button.style = "top:60px;right:0;position:absolute;margin:20px;z-index: 9999; background: #000;color: #fff;border: 1px solid #fff;padding: 8px;";
  document.body.appendChild(button);
  $(button).click(function(){
    if(window.CSV_GYMS){
      ohmylog("Gymscraping: Clicked the download button");
      var address = window.location.hash.substr(1)
      var filename = "gyms" + ( address ? "_" + address : "") + "_" + new Date().getTime() + ".csv";
      var blob = new Blob([CSV_GYMS], {
        type: "text/plain;charset=utf-8"
      });
      saveAs(blob, filename);
    }
  });
};

(function() {
    'use strict';
    // save log and dir
    ohmylog = window.ohmylog = console.log;
    ohmydir = window.ohmydir = console.dir;
    // initialize csv
    window.CSV_GYMS = "";
    // download button still not shown
    window.DOWNLOADBUTTON_SHOWN = false;
    (function() {
       var origOpen = XMLHttpRequest.prototype.open;
       // add our hanldler as a listener to every XMLHttpRequest
       XMLHttpRequest.prototype.open = function() {
         this.addEventListener('load', function(xhr) {
           ohmylog("Gymscraping: Received response of some kind");
           if(this.responseText.indexOf("gyms") > 0){
               var json = JSON.parse(this.responseText);
               var gyms = json.gyms;
               ohmylog("Gymscraping: Received response with " + gyms.length + " gyms");
               if(gyms.length>0){
                 var csv = window.CSV_GYMS;
                 ohmylog('Gymscraping: Action!');
                 for(var j = 0; j < gyms.length; j++){
                     var gym = gyms[j];
                     ohmylog("Gymscraping: Gym info: " + gym);
                     // append a row to the csv if not already there
                     var row = gym.gym_name + "\t" + gym.longitude + "\t"+ gym.latitude;
                     if(csv.indexOf(row) == -1){
                         csv = csv + row +"\n";
                     }
                 }
                 window.CSV_GYMS = csv;
                 showDownloadButton();
                 ohmylog('Gymscraping: ended!');
               }
           }
         });
         origOpen.apply(this, arguments);
       };
    })();
})();