- // ==UserScript==
- // @name Torn Helper
- // @namespace Jebster.Torn
- // @author Jeggy
- // @description Adds extra information to different pages all around Torn.
- // @include *.torn.com/profiles.php?XID=*
- // @version 0.0.8
- // @require http://code.jquery.com/jquery-2.2.4.min.js
- // @require http://code.jquery.com/ui/1.12.1/jquery-ui.min.js
- // @resource jquery-ui http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/black-tie/jquery-ui.min.css
- // @resource jquery-base http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css
- // @grant GM_addStyle
- // @grant GM_getResourceText
- // ==/UserScript==
-
- GM_addStyle(GM_getResourceText('jquery-base'));
- GM_addStyle(GM_getResourceText('jquery-ui'));
-
- String.prototype.format = function() {
- var formatted = this;
- for (var i = 0; i < arguments.length; i++) {
- var regexp = new RegExp('\\{'+i+'\\}', 'gi');
- formatted = formatted.replace(regexp, arguments[i]);
- }
- return formatted;
- };
-
- var data = {};
-
- (function() {
- 'use strict';
-
- var site = window.location.pathname;
-
- loadData();
- saveOwnData();
-
- if(site.indexOf('profiles.php') > 0) profileView();
-
- loadAttackLog();
- })();
-
- function loadAttackLog(){
- var selections = 'attacks';
- if('attackLogLoad' in data)
- //if(data.attackLogLoad > new Date().getTime() + (60*60*6))
- logAttacks(false);
- else
- logAttacks(true);
- }
-
- function logAttacks(full){
- var selections = 'attacks' + (full ? 'full' : '');
- var url = 'https://api.torn.com/user/'+data.id+'?selections='+selections+'&key='+data.apikey;
- /*$.ajax({
- url: url,
- type: 'GET',
- success: function(d) {
- if(d.error) getApiKey();
- else{
- save();
- }
- }
- });*/
- }
-
- function profileView(){
- var userid = getParameterByName('XID');
- var userData = data[userid];
- var content =
- // profileViewSelectionPopUp()+ // TODO: Figoure out how to call tampermonkey function from the injected code.
- '<div id="compareStats">' +
- 'Loading...' +
- '<br />' +
- '</div>' +
- '<hr />' +
- '<b>Notes</b><br />' +
- getUserValue(userid, 'notes')+
- '<br />';
-
- var compareFunc = function(){$('#compareStats').replaceWith(compareTemplate(userid, data.userid));};
- apiUserStats(userid, compareFunc);
- apiUserStats(data.userid, compareFunc);
-
- var block = $(
- '<div class="profile-wrapper medals-wrapper m-top10">' +
- '<div class="menu-header">Torn Helper</div>' +
- '<div class="profile-container"> ' +
- '<div class="profile-container-description">'+content+'</div>' +
- '</div>' +
- '<div class="clear"></div></div>');
-
- $(block).insertAfter('.tutorial-cont + .profile-wrapper');
- }
-
- function profileViewSelectionPopUp(){
- var possibilities = possibleStats();
- var popupHtml = '<div><fieldset><legend>Select:</legend>';
- for(var p in possibilities){
- var o = possibilities[p];
- var checked = inArray(p, data.profileview.display) ? 'checked' : '';
-
- popupHtml += '<label for="checkbox'+p+'">'+o.display+'</label>: '+
- '<input type="checkbox" name="checkbox'+p+'" id="view'+p+'" '+checked+'> ';
- }
- popupHtml += '</fieldset></div>';
- var popup = popupWindow(
- {
- element: '#editProfileView',
- title: 'Edit Profile view'
- },
- popupHtml,
- [
- {
- 'display': 'Save',
- 'close': false, // default: true // TODO: Not working!
- 'callback': function(){
- for(var p in possibleStats()){
- alert(p);
- }
- $(this).dialog("close");
- }
- }
- ]
- );
-
- var button = '<div style="float:right">' +
- '<button id="editProfileView">Edit</button></div>';
-
- return button+popup;
- }
-
- /**
- * Example usage:
- * popupWindow(
- * { 'element': '#myDialogButton', 'title': 'Hello World' },
- * '<h3>Something</h3><input type="text" id="myfield" />',
- * [{'display': 'Save',
- * 'close': false, // default: true
- * callback: function(){var something = $("#myfield").val();}
- * }]);
- */
- function popupWindow(e, content, buttons){
- var script = '<script>$("'+e.element+'").click(function(){$("#dialog-message").dialog({'+
- 'modal: true,'+
- 'draggable: true,'+
- 'resizable: true,'+
- 'position: [\'center\'],'+
- 'show: \'blind\','+
- 'hide: \'blind\','+
- 'width: 400,'+
- 'buttons: [';
- var test = '';
- for(var i = 0; i < buttons.length; i++){
- var a = buttons[i].callback;
- script += '{';
- script += 'text: \''+buttons[i].display+'\',';
- script += 'id: \'dialogButton'+i+'\',';
- script += 'click: '+a;
- /*
- if('close' in buttons[i] || buttons[i].close)
- script += '$(this).dialog("close");';*/
- script += '}';
-
- // TODO: Support multiple buttons!
- }
- // todo: remove last char
- script += ']}';
- script += ');});'+test;
-
- script += '</script>';
-
- var html = '<div id="dialog-message" title="'+e.title+'" style="display: none;">';
- html += content;
- html += '</div>';
-
- return script+html;
- }
-
- function inArray(c, a){
- // Somehow $.inArray is not working? ?
- for(var i = 0; i < a.length; i++){
- if(c == a[i]) return true;
- }
- return false;
- }
-
- function getUserValue(userid, property){
- var user = data[userid];
- if(user){
- if($.isArray(property)){
- for(var i = 0; i < property.length; i++){
- user = user[property[i]];
- }
- return user;
- }else{
- var userData = user[property];
- if(userData){
- return userData;
- }
- }
- }
- return -1;
- }
-
- function setUserValue(userid, property, value){
- if(data[userid] === undefined) data[userid] = {};
- data[userid][property] = value;
- }
-
- function save(){
- localStorage.setItem('jebster.torn', JSON.stringify(data));
- }
-
- function saveOwnData(){
- // TODO: Maybe only save when needed
- var profileLink = $("#t-blue#h").context.URL.toString();
- var start = profileLink.indexOf('XID')+4;
- var end = profileLink.indexOf('&') ? profileLink.indexOf('&') - start : start - profileLink.length;
- var id = profileLink.substr(start, end);
- data.me = {'id': id};
- save();
- }
-
- function loadData(){
- data = localStorage.getItem('jebster.torn');
- if(data === undefined || data === null){
- // Default settings
- data = {
- profileview:{
- display: ['xanax','logins','refill','timeplayed']
- }
- };
- }else{
- data = JSON.parse(data);
- }
-
- if(data.apikey === undefined || data.apikey === ''){
- getApiKey();
- }
- }
-
- var asked = false;
- function getApiKey(){
- // Add some beautiful input/popup on the page itself
- if(asked) return; asked = true;
- var key = prompt('You API Key', 'key');
- if(!('me' in data)) data.me = {};
- data.pikey = key;
- console.log(data);
- save();
- }
-
- function apiUserStats(userid, cb){
- var lastRequest = getUserValue(userid, 'lastRequest');
- var now = new Date();
- if(lastRequest === 0 || lastRequest < now.getTime() - (60*60*5)){ // TODO:
- var selections = 'personalstats,basic';
- var url = 'https://api.torn.com/user/'+userid+'?selections='+selections+'&key='+data.apikey;
- $.ajax({
- url: url,
- type: 'GET',
- success: function(data) {
- if(data.error) getApiKey();
- else{
- setUserValue(userid, 'stats', data.personalstats);
- setUserValue(userid, 'lastRequest', now.getTime());
- setUserValue(userid, 'username', data.name);
- save();
- cb(data);
- }
- }
- });
- }else{
- cb(data[userid].stats);
- }
- }
-
- function compareTemplate(user1Id, user2Id){
- console.log(user1Id + ' : ' + user2Id);
- var css = '<style>'+
- '.tornHelper{' +
- 'min-width:200px;' +
- '}' +
- '</style>';
-
- var html = css+'<ul class="basic-list">' +
- '<li>' +
- '<div class="user-information-section left"><span class="bold"></span></div>' +
- '<div class="user-information-section left tornHelper"><span class="bold">'+getUserValue(user1Id, 'username')+'</span></div>' +
- '<div class="tornHelper"><span class="bold">'+getUserValue(user2Id, 'username')+' (You)</span></div>' +
- '</li>';
-
- var stats = possibleStats();
- for(var i = 0; i < data.profileview.display.length; i++){
- var display = stats[data.profileview.display[i]];
-
- var user1Value = getUserValue(user1Id, display.apiname);
- var user2Value = getUserValue(user2Id, display.apiname);
-
- if(display.extra){
- e1 = getUserValue(user1Id, display.extra.apiname);
- e2 = getUserValue(user2Id, display.extra.apiname);
- if(display.extra.format){
- e1 = '<span>{0}</span>'.format(display.extra.format(e1));
- e2 = '<span>{0}</span>'.format(display.extra.format(e2));
- }
-
- user1Value += e1;
- user2Value += e2;
- }
-
- html += '<li>' +
- '<div class="user-information-section left"><span class="bold">' +
- display.display +
- '</span></div>' +
- '<div class="user-information-section left tornHelper">' +
- user1Value +'</div>' +
- '<div class="tornHelper">'+user2Value+'</div>' +
- '</li>';
- }
- html += '</ul>';
- return html;
- }
-
- function possibleStats(){
- return {
- xanax:{apiname:['stats','xantaken'], display: 'Xanax taken'},
- logins:{apiname:['stats','logins'], display: 'Logins'},
- timeplayed:{apiname:['stats','useractivity'], display: 'Time played'},
- refills:{apiname:['stats','refills'], display: 'Refills'}
- };
- }
-
- function removeFirstAndLastLine(text){
- var lines = text.split('\n');
- lines.splice(0,1);
- lines.splice(-1,1);
- var newtext = lines.join('\n');
- }
-
- function formatSeconds(s){
- var minutes = Math.floor(s/60)%60;
- var hours = Math.floor(s/(60*60))%24;
- var days = Math.floor(s/(60*60*24));
- var seconds = s%60;
-
- return '{0}d {1}h {2}m {3}s'.format(days, hours, minutes, seconds);
- }
-
- // Taken from: http://stackoverflow.com/a/15724300/1832471
- function getCookieValue(name) {
- var nameEQ = name + "=";
- var ca = document.cookie.split(';');
- for(var i=0;i < ca.length;i++) {
- var c = ca[i];
- while (c.charAt(0)==' ') c = c.substring(1,c.length);
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
- }
- return null;
- }
-
- // Taken from: http://stackoverflow.com/a/901144/1832471
- function getParameterByName(name, url) {
- if (!url) {
- url = window.location.href;
- }
- name = name.replace(/[\[\]]/g, "\\$&");
- var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
- results = regex.exec(url);
- if (!results) return null;
- if (!results[2]) return '';
- return decodeURIComponent(results[2].replace(/\+/g, " "));
- }