diegokfu / SG Bot

// ==UserScript==
// @name        SG Bot
// @namespace   SGB
// @icon        http://www.steamgifts.com/favicon.ico?v=9
// @updateURL https://openuserjs.org/src/scripts/diegokfu/SG_Bot.user.js
// @downloadURL https://openuserjs.org/src/scripts/diegokfu/SG_Bot.user.js
// @match      *://www.steamgifts.com*
// @version     0.4
// @grant       none
// @require     https://gist.githubusercontent.com/arantius/3123124/raw/grant-none-shim.js
// @author      Diego Ferreira
// ==/UserScript==

var currentPoints=parseInt(document.getElementsByClassName("nav__points")[0].innerHTML);

var MaximumPointstoEnter=(currentPoints > 70) ? parseInt(currentPoints/10) : 7;
var MaximumTimetoEnter=300;
var MaximumEntriesToEnter=900;

var BotActive=true;

var Comentarios=["Thanks mate :)","hope you have a nice day! :)", "Thanks for sharing!", "Thx:D", "thanks dude!", "ty :3", "thx", "TEXT you for the giveaway (۶•̀ᴗ•́)۶" ,"Thanks!", "Thank you for this chance! :D", "ty for giveaway :3", "Thank you!", "Thank you very much ^^", "You are awesome! Thanks a lot! ;)", "Obrigado. Thanks. Danke. 고맙습니다 Gracias. Merci. Grazie. ありがとうございました спасибо 谢谢 Teşekkür ederim dziękuję :)", "Thanks for the awesome giveaway!"];

var xsrf = $('input[type=hidden][name=xsrf_token]').val();
var loggedin = ($('.nav__sits').length > 0) ? false : true;
var GiveawaysToEnter=[];

setInterval(refreshP,60*1000);

var html='<div class="nav__button-container" style="padding:0px; margin:auto 70px 0px 0px;"><div class="nav__relative-dropdown is-hidden"><div class="nav__absolute-dropdown">';
html+='<a class="nav__row" href="http://www.steamgifts.com/giveaways/entered"><i class="icon-grey fa fa-fw fa-edit"></i><div class="nav__row__summary"><p class="nav__row__summary__name">Contador de Sorteios</p><p class="nav__row__summary__description">Entrou em um total de <span id="GiveawayCounter">'+number_format(GM_getValue("GiveawaysCount" ,0), 0)+'</span> Sorteios.</p></div></a>';
html+='<a class="nav__row" href="#"><i class="fa fa-fw fa-info-circle" style="color:lightblue"></i><div class="nav__row__summary"><p class="nav__row__summary__name">Configurações</p><p class="nav__row__summary__description">Entrando em Sorteios de até <span id="PointsCounter">'+MaximumPointstoEnter+'</span> pontos.</p></div></a>';
//html+='<a id="syncsteam" class="nav__row" href="#"><i class="icon-green fa fa-fw fa-refresh"></i><div class="nav__row__summary"><p class="nav__row__summary__name">Sincronizar conta com Steam</p><p class="nav__row__summary__description">Sincronizar conta Steam em 1 Clique.</p></div></a>';
html+='</div></div><div id="sgbot" class="nav__button">SteamGift Bot</div> <div class="nav__button nav__button--is-dropdown-arrow"><i class="fa fa-angle-down"></i></div></div>';
$(".nav__right-container").before(html);
$("#syncsteam").click(sync);

function number_format( numero, decimal, decimal_separador, milhar_separador ){	
    numero = (numero + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+numero) ? 0 : +numero,
        prec = !isFinite(+decimal) ? 0 : Math.abs(decimal),
        sep = (typeof milhar_separador === 'undefined') ? ',' : milhar_separador,
        dec = (typeof decimal_separador === 'undefined') ? '.' : decimal_separador,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix para IE: parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }

    return s.join(dec);
}

function secLeft(ExpireDate){
  var curDate=new Date(); curDate=new Date(curDate.toGMTString());
  ExpireDate=new Date(ExpireDate);
  var secLeft=(ExpireDate.getTime() - curDate.getTime()) / (1000 * 1 * 1 * 1);
  return secLeft;
}

function doThanksComment(giveaway){ 
  var comentario=Comentarios[Math.floor(Math.random()*Comentarios.length)];
  $.ajax({
    url: "http://www.steamgifts.com/giveaway/"+giveaway,
    type: "POST",
    data: "xsrf_token="+xsrf+"&do=comment_new&parent_id=&description="+comentario,
    success: function(e) {
      //success
    }
  });
}

if(document.location.href.toLowerCase().indexOf("giveaways/won") > -1){
  $(".table__column--width-small.text-center.table__column--gift-feedback").click(sync);
}

function sync(){
  $.ajax({
      url: "/ajax.php",
      type: "POST",
      dataType: "json",
      data: "xsrf_token="+xsrf+"&do=sync",
      success: function(e) {
        if(e.msg.toLowerCase().indexOf("success") > -1){
        //alert("Conta sincronizada com sucesso!");
      } else {
       // alert("Ocorreu algum erro ao sincronizar, tente mais tarde :c");
      }
      }
  });
}

function refreshP(){
  $.ajax({
      url: "/ajax.php",
      type: "POST",
      dataType: "json",
      data: "xsrf_token="+xsrf+"&do=entry_insert",
      success: function(e) {
        if($(".nav__points").text()!=e.points){
          $(".nav__points").text(e.points);
          currentPoints=parseInt(e.points);
          MaximumPointstoEnter=(currentPoints > 70) ? parseInt(currentPoints/10) : 7;
        }
      }
  });
}
           

function AlreadyEnter(code){
  if(GM_getValue("enteredGiveaways") == null){ GM_setValue("enteredGiveaways","[]"); }
  var enteredGiveaways = JSON.parse(GM_getValue("enteredGiveaways"));
  var Entered=false;
  for(var x=0; x < enteredGiveaways.length; x++){
    if(enteredGiveaways[x] != undefined && enteredGiveaways[x].code == code){
      Entered=true;
    }
  }
  return Entered;
}

function removeEnteredFromCode(code){
  if(GM_getValue("enteredGiveaways") == null){ GM_setValue("enteredGiveaways","[]"); }
  var enteredGiveaways = JSON.parse(GM_getValue("enteredGiveaways"));
  for(var x=0;x<enteredGiveaways.length;x++){
    if(enteredGiveaways[x] != undefined && enteredGiveaways[x].code == code){
      enteredGiveaways.splice(x,1);
    }
  }
  GM_setValue("enteredGiveaways", JSON.stringify(enteredGiveaways));
}

function removeGiveawayToEnterFromCode(code){
  for(var x=0;x<GiveawaysToEnter.length;x++){
    if(GiveawaysToEnter[x] != undefined && GiveawaysToEnter[x].code == code){
      GiveawaysToEnter.splice(x,1);
    }
  }
}



function expireGiveaways(){
  if(GM_getValue("enteredGiveaways") == null){ GM_setValue("enteredGiveaways","[]"); }
  var enteredGiveaways = JSON.parse(GM_getValue("enteredGiveaways"));
 // console.log('antes',enteredGiveaways);
  for(var x=0;x<enteredGiveaways.length;x++){
    if(enteredGiveaways[x] != undefined){
      var curDate=new Date(); curDate=new Date(curDate.toGMTString());
      var ExpireDate=enteredGiveaways[x].expireDate;
      if(secLeft(ExpireDate) <= 0){
        removeEnteredFromCode(enteredGiveaways[x].code);
      }
    }
  }
 // console.log('dps',enteredGiveaways);
  GM_setValue("enteredGiveaways", JSON.stringify(enteredGiveaways));
}

function getEnteredGiveawayFromCode(code){
  if(GM_getValue("enteredGiveaways") == null){ GM_setValue("enteredGiveaways","[]"); }
  var enteredGiveaways = JSON.parse(GM_getValue("enteredGiveaways"));
  for(var x=0; x < enteredGiveaways.length; x++){
    if(enteredGiveaways[x].code == code){
      return enteredGiveaways[x];
    }
  }
  return null;
}

function pushNew(code, expireDate){
  if(GM_getValue("enteredGiveaways") == null){ GM_setValue("enteredGiveaways","[]"); }
  var enteredGiveaways = JSON.parse(GM_getValue("enteredGiveaways"));  
  enteredGiveaways.push( { code:code, expireDate:expireDate } );
  GM_setValue("GiveawaysCount", parseInt(parseInt(GM_getValue("GiveawaysCount" , 0))+1));
  $("#GiveawayCounter").html(number_format(GM_getValue("GiveawaysCount" ,0), 0));
  GM_setValue("enteredGiveaways", JSON.stringify(enteredGiveaways));
  //console.log('entered',enteredGiveaways.length);
}

function enterGiveaway(code, expireDate, url){ 
  $.ajax({
    url: "http://www.steamgifts.com/ajax.php",
    type: "POST",
    dataType: "json",
    data: "xsrf_token="+xsrf+"&do=entry_insert&code="+code,
    success: function(e) {
      if(e.type == "success"){
        currentPoints=e.points;
        MaximumPointstoEnter=(currentPoints > 70) ? parseInt(currentPoints/10) : 7;
        $("#PointsCounter").html(MaximumPointstoEnter);
        pushNew(code, expireDate);
        doThanksComment(url); //if(Math.random() < .6){ doThanksComment(url); }
        document.getElementsByClassName("nav__points")[0].innerHTML=currentPoints;
      }
    }
  });
}

function leaveGiveaway(code){
  if(GM_getValue("enteredGiveaways") == null){ GM_setValue("enteredGiveaways","[]"); }
  var enteredGiveaways = JSON.parse(GM_getValue("enteredGiveaways"));
  $.ajax({
    url: "/ajax.php",
    type: "POST",
    dataType: "json",
    data: "xsrf_token="+xsrf+"&do=entry_delete&code="+code,
    success: function(e) {
      currentPoints=e.points;
      MaximumPointstoEnter=(currentPoints > 70) ? parseInt(currentPoints/10) : 7;
      $("#PointsCounter").html(MaximumPointstoEnter);
      if(e.type == success){
        if(enteredGiveaways.indexOf(code) != -1){
          enteredGiveaways.splice(enteredGiveaways.indexOf(code),1);
          GM_setValue("enteredGiveaways", JSON.stringify(enteredGiveaways));
        }
        //e.entry_count
      }
    }
  });
}

function sortGiveaways(array){
  array.sort(function (a, b) {
    if (a.left > b.left) {
      return 1;
    }
    if (a.left< b.left) {
      return -1;
    }
    // a must be equal to b
    return 0;
  });
  array.sort(function (a, b) {
    if (a.points > b.points) {
      return 1;
    }
    if (a.points < b.points) {
      return -1;
    }
    // a must be equal to b
    return 0;
  });
  
  return array;
}

function newGiveawayToEnter(GameCode, Points, secLeft, ExpireDate, GameURL){
  var push=true;
  for(var x=0; x < GiveawaysToEnter.length; x++){
    if(GiveawaysToEnter[x] != undefined && GiveawaysToEnter[x].code == GameCode){
      push=false;
    }
  }
  if(push){
    GiveawaysToEnter.push( { left:secLeft, points:Points, code:GameCode, ExpireDate:ExpireDate, URL:GameURL } );
  }
}

function checkForGiveaways(){ if(!BotActive){return;}
  $.get("http://www.steamgifts.com/giveaways/search?page=1", function(r, textStatus){
    var xmlString = r
    , parser = new DOMParser()
    , doc = parser.parseFromString(xmlString, "text/html");
   
    for(var x=0; x < doc.getElementsByClassName("giveaway__summary").length; x++){
      var Copies=1;
      var Points=0;
      for(var i=0; i < doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].getElementsByTagName("span").length; i++){
        if(doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].getElementsByTagName("span")[i].innerHTML != undefined && doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].getElementsByTagName("span")[i].innerHTML.indexOf("P)") > -1){
          Points=parseInt(doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].getElementsByTagName("span")[i].innerHTML.replace("(", ""));
        }
        
        if(doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].getElementsByTagName("span")[i].innerHTML != undefined && doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].getElementsByTagName("span")[i].innerHTML.indexOf("Copies)") > -1){
          Copies=parseInt(doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].getElementsByTagName("span")[i].innerHTML.replace("(", ""));
        }
      }
      
      var Game=doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].childNodes[1].innerHTML;
      var GameCode=doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].childNodes[1].href.split("/giveaway/")[1].split("/")[0];
      var GameURL=doc.getElementsByClassName("giveaway__summary")[x].childNodes[1].childNodes[1].href.split("/giveaway/")[1];
      
      var EndTime=doc.getElementsByClassName("giveaway__summary")[x].childNodes[3].childNodes[1].childNodes[2].title;
      var curDate=new Date(); curDate=new Date(curDate.toGMTString());
      var ExpireDate=new Date(EndTime.replace("pm"," pm").replace("am"," am").replace("Today, ", curDate.toDateString()+" "));
      var secLeft=(ExpireDate.getTime() - curDate.getTime()) / (1000 * 1 * 1 * 1);
      
      var Entries=parseFloat(doc.getElementsByClassName("giveaway__summary")[x].childNodes[5].childNodes[1].childNodes[2].innerHTML.replace(",", "."));
      Entries=parseInt(parseInt(Entries.toString().replace(".",""))/Copies);
      
      if(secLeft > 0 && secLeft <= MaximumTimetoEnter && Entries <= MaximumEntriesToEnter && currentPoints >= Points && Points <= MaximumPointstoEnter && !AlreadyEnter(GameCode)){
        newGiveawayToEnter(GameCode, Points, secLeft, ExpireDate, GameURL);
      } else if(Points < 2){
        newGiveawayToEnter(GameCode, Points, secLeft, ExpireDate, GameURL);
      }
    }
    var array=sortGiveaways(GiveawaysToEnter);
    for(var x=0; x<array.length;x++){
      if(array[x] != undefined && !AlreadyEnter(array[x].code)){
        enterGiveaway(array[x].code, array[x].ExpireDate, array[x].URL);
      }
    }
    currentPoints=doc.getElementsByClassName("nav__points")[0].innerHTML;
    MaximumPointstoEnter=(currentPoints > 70) ? parseInt(currentPoints/10) : 7;
    $("#PointsCounter").html(MaximumPointstoEnter);
  });
}

if(BotActive && loggedin){
  setInterval(checkForGiveaways,30*1000);
  setInterval(expireGiveaways,60*1000);
  checkForGiveaways();
}