MarioG67 / TTS Steam Workshop Downloader

// ==UserScript==
// @author         Reiis (originally Sycam Inc (origionally Alvaro))
// @name           TTS Steam Workshop Downloader
// @description    Adds an extra button to download and convert TTS workshop items
// @include        *steamcommunity.com/sharedfiles/filedetails/?id=*
// @include        *steamcommunity.com/workshop/filedetails/?id=*
// @require        http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
// @require        http://idr.altervista.org/bson.js
// @grant          GM_xmlhttpRequest
// @version        2.1
// @license        MIT
// @namespace      https://openuserjs.org/users/MarioG67
// ==/UserScript==

var patt = new RegExp("[0-9]{2,15}");
var id = patt.exec(document.URL);
var baseURL = "http://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v0001/";
var baseURLCtn = "http://api.steampowered.com/ISteamRemoteStorage/GetCollectionDetails/v0001/";

if (document.URL.indexOf("steamcommunity.com") != -1) {
	if (document.URL.indexOf("workshop") == -1) {
		addWorkshopBtn(id);
	}
}

function fix_data(data) {
	for (var k in data) {
		var v = data[k];
		if (v == null || v == undefined) {
			delete data[k];
		} else if (typeof v === 'object') {
			fix_data(v);
		}
	}
	
	return data;
}

// http://stackoverflow.com/a/18197341
function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

function downloadBson(url, id) {
	GM_xmlhttpRequest({
		method: "POST",
		url: url,
		data: "itemcount=1&publishedfileids[0]=" + id + "&format=json",
		headers: {
			"Content-Type": "application/x-www-form-urlencoded"
		},
		onload: function (response) {
			//console.log(response.responseText);
			//debugger;
			data = jQuery.parseJSON(response.responseText);
			console.log(data);
			var filedetails = data.response.publishedfiledetails[0];
			var fileurl = filedetails.file_url;
			
			GM_xmlhttpRequest({
				method: "GET",
				url: fileurl,
				onload: function (response) {
					var resp = response.response;
					var bb = new ArrayBuffer(resp.length);
					
					for (var i = 0; i < resp.length; i++) {
						bb[i] = resp.charCodeAt(i) & 0xff;
					}
					
					var BSON = require('bson').BSON;
					var db = BSON.deserialize(bb);
					var stringdata = JSON.stringify(fix_data(db), null, 2);
					console.log(stringdata);
					
					var filename = filedetails.title + ' (' + publishedfileid + ').json';
					
					download(filename, stringdata);
				},
				onerror: function (reponse) {
					//alert('error');
					console.log(reponse);
				},
				overrideMimeType: 'text/plain; charset=x-user-defined'
			});
		},
		onerror: function (reponse) {
			//alert('error');
			console.log(reponse);
		}
	});
}


function addWorkshopBtn(id) {
	var element = document.getElementById("AddToCollectionBtn");
	var button = document.createElement('span');
	button.setAttribute('class', 'general_btn share tooltip');
	//button.setAttribute('href', baseURLCtn + id);

	button.innerHTML = '<span id="SubscribeItemOptionAdd3"><span>Get TTS json</span></span>';
	// Append the element after the real subscribe button
	if (element.nextSibling) {
		element.parentNode.insertBefore(button, element.nextSibling);
	} else {
		element.parentNode.appendChild(button);
	}
	//downloadBson(baseURL, id);
	
	
	$("#SubscribeItemOptionAdd3").click(function (e) {
		e.preventDefault(); //stop the browser from following
		
		downloadBson(baseURL, id);
	});
	
	// Change the stupid text to the left of it
	document.querySelectorAll(".game_area_purchase_game")[0].getElementsByTagName('h1')[0].setAttribute('style', 'width: 300px;');
}