Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function handleDisconnect() {
- db = mysql.createConnection(db_config); // Recreate the connection, since
- // the old one cannot be reused.
- db.connect(function(err) { // The server is either down
- if(err) { // or restarting (takes a while sometimes).
- console.log('error when connecting to db:', err);
- setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
- } // to avoid a hot loop, and to allow our node script to
- }); // process asynchronous requests in the meantime.
- // If you're also serving http, display a 503 error.
- db.on('error', function(err) {
- console.log('db error', err);
- if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
- handleDisconnect(); // lost due to either server restart, or a
- } else { // connnection idle timeout (the wait_timeout
- throw err; // server variable configures this)
- }
- });
- }
- handleDisconnect();
- var fs = require('fs');
- var ini = require('ini');
- var path_to_config = "/home/jackpot/config/config.ini";
- var config = ini.parse(fs.readFileSync(path_to_config, 'utf-8'));
- /* SETINGS */
- var userlogin = config.ACCOUNT.account_name;
- var userpass = config.ACCOUNT.account_pass;
- var userssfn = 'files/'+config.ACCOUNT.account_ssfn;
- var setnickname = config.ACCOUNT.account_nick;
- var twoFactorData;
- var min_sum = config.LIMITS.min_sum;
- var min_sum_per_item = config.LIMITS.min_sum_per_item;
- var commis_ratio = config.LIMITS.commis_ratio;
- var max_items_per_user = config.LIMITS.max_items_per_user;
- var passsite = config.REDIS.redis_password;
- var ban_items = []; // запрет вещи
- var ban_hash_items = [];
- var fake_steamids = [];
- var reboot_required = 0;
- // ADMINS //
- //var admins = ['76561198004730960']; // STEAMID администраторов
- var admins = [config.ACCOUNT.account_admin_steamid];
- //var admins = [];
- var tester = [];
- var app_game = 730; // ИГРА 730 - CS, 570 - DOTA 2
- var main_url = config.SYSTEM.mainhost;
- var prefix = config.REDIS.redis_prefix;
- var port_list = config.SYSTEM.port;
- var used_offersid = [];
- var used_fake_offers = [];
- // Количество игроков онлайн
- var online = 0;
- /* LIBS*/
- var app = require('http').createServer();
- var io = require('socket.io')(app);
- app.listen(8080);
- /* LIBS
- var app = require('http').createServer();
- var io = require('socket.io')(app, {path: "/io"});
- /* STEAM libs */
- var Steam = require('steam');
- var SteamTradeOffers = require('steam-tradeoffers');
- var getSteamAPIKey = require('steam-web-api-key');
- var SteamApi = require('steam-api');
- var InventoryWrapper;
- var steamClient = new Steam.SteamClient();
- var steamUser = new Steam.SteamUser(steamClient);
- var steamFriends = new Steam.SteamFriends(steamClient);
- var SteamWeb = require('steam-weblogon');
- var steamWeb = new SteamWeb(steamClient, steamUser);
- var offers = new SteamTradeOffers();
- /* TWO FACTOR libs */
- var SteamTotp = require('steam-totp');
- var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
- var SteamMobileConfirmations;
- var SteamID;
- var sha = require('crypto').createHash('sha1');
- sha.update(fs.readFileSync(userssfn));
- sha = new Buffer(sha.digest(), 'binary');
- /* PUB/SUB */
- var EventEmitter = require('events').EventEmitter;
- var pubsub = new EventEmitter();
- /* REDIS */
- var redis = require("redis"),
- client1 = redis.createClient();
- client1.auth(config.REDIS.redis_password);
- var request = require('request');
- /* GLOBAL VAR */
- /* раунд */
- var timeoutId; // таймер
- var start_date; // время начала
- var timeset; // тек вермя
- var accept_trade = false; // Рычаг трейда
- var with_com = false; // Была ли комиссия?
- var gameshowitem = true; // прошло ли 60 сек. после начала игры и можно ли показывать (отослать) предметы на сайт?
- var spec_rate = 0; // Определяющая ставка. Значение, выше которого ставить нельзя. Определяется первой ставкой игры
- var offer_trad = [];
- // Максимальное количество вещей в раунде
- var maxItemsCount = config.LIMITS.max_items;
- // Проверка на "переданность предмета"
- var arrayIdItemsInOffers = []; // Массив ID предметов, которые когда-то были добавлены в обмен и переданы
- var roundTimer = 0; // Таймер раунда. Сбрасывается при окончании раунда.
- var inv_tries = 0;
- var inv_code = -1;
- var glob_items = []; // массив всех вещей за раунд
- var ima_gamers = []; // массив чуваков в раунде
- var steamid_items = {}; // массив чуваков (их steamid), в котором указано количество предметов каждого игрока
- var progress_bar = 0; // Сколько вещей
- var money_round = 0.0; // Денег
- var points_round = 0; // Количество поинтов
- var n_game = 0; // Номер игры
- /* статистика день */
- var niti_games = 0; // Кол-во игр за сегодня
- var niti_jackpots = 0; // Кол-во денег за сегодня
- var niti_djackpots = 0; // Самый крупный джекпот
- var niti_ulogin = {}; // кол-во посетителей за день
- var niti_ulogin_n = 0;
- /* other var */
- var arr_prof = {}; // Список профилей, чьих оффер в обработке
- var site_hash = '';
- var site_unhash = 0;
- var stats = {};
- var last_winner = {};
- var chatmsgs = "";
- /* MAIN FUNCTION */
- /*
- *Установить статистику
- *@var action - действие, API
- *@var info - информация, если есть
- */
- function generateHash() {
- var hash_length = 64;
- var hash = '';
- for(i=0;i<64;i++) {hash +=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)];}
- return hash;
- }
- function filterNick(string) {
- if(config.SYSTEM.mainhost) {
- string = string.replace(/cs(.*)(?!\ )(.*)(\.|\:)(com|ua|ru|org|net|one|us|biz)/ig,config.SYSTEM.mainhost.toUpperCase());
- }
- return string;
- }
- function escapeHtml(unsafe) {
- return unsafe
- .replace(/&/g, "&")
- .replace(/</g, "<")
- .replace(/>/g, ">")
- .replace(/"/g, """)
- .replace(/'/g, "'");
- }
- /*
- *@func arr_prof_add - добавляем юзера в обработку, чтобы не обрабатывать 2 оффера от одного юзера
- *@func arr_prof_del - аналогичная
- */
- function arr_prof_add(id) {
- arr_prof[id] = id;
- }
- function arr_prof_del(id) {
- delete arr_prof[id];
- }
- /*
- *@func time - возвращает текущ время
- */
- function time(){
- return parseInt(new Date().getTime()/1000);
- }
- /*
- * Foreach
- */
- function forEach(data, callback){
- for(var key in data){
- if(data.hasOwnProperty(key)){
- callback(key, data[key]);
- }
- }
- }
- /*
- * Проверка на сущ эл в массиве
- */
- function in_array(value, array)
- {
- for(var i = 0; i < array.length; i++)
- if(array[i] == value)
- return true;
- return false;
- }
- function explode( delimiter, string ) { // Split a string by string
- var emptyArray = { 0: '' };
- if ( arguments.length != 2
- || typeof arguments[0] == 'undefined'
- || typeof arguments[1] == 'undefined' )
- {
- return null;
- }
- if ( delimiter === ''
- || delimiter === false
- || delimiter === null )
- {
- return false;
- }
- if ( typeof delimiter == 'function'
- || typeof delimiter == 'object'
- || typeof string == 'function'
- || typeof string == 'object' )
- {
- return emptyArray;
- }
- if ( delimiter === true ) {
- delimiter = '1';
- }
- return string.toString().split ( delimiter.toString() );
- }
- /* РАБОТА С API */
- /*
- *Получаем информацию о юзере из бд
- *@var steamid - ID юзера
- *@var callback - callback функция
- */
- function getlink(steamid, callback) { // получаем ссылку
- db.query('SELECT * FROM users WHERE steamid = ?',[steamid],function(err,rows){
- if(err) throw err;
- if(rows.length == 1) { // если есть информация
- console.log("[ %s ] Offerlink: \x1b[34m"+rows[0].link+"\x1b[0m", logTime());
- callback(rows[0]); // вызываем каллбэк функцию
- } else {
- console.log("[ %s ] Cannot get link: \x1b[34m"+"\x1b[0m", logTime());
- io.emit('info', { msg: "bot_winner_no_link", action: "show" });
- // Начинаем новый раунд
- startNewRound();
- }
- });
- }
- /*
- * Установка чемпиона в БД
- *@var items - предметы, которые пользователь выиграл
- *@var set_chemp - информация о пользователе
- */
- function set_chemp(items, set_chemp, status, errorcode, reboot) {
- var itemsr = JSON.stringify(items);
- client1.set(prefix + ":items_to_offer", itemsr);
- //set_chemp = JSON.stringify(set_chemp);
- client1.set(prefix + ":set_chemp", set_chemp);
- var code = 0;
- console.log(set_chemp.id);
- console.log(set_chemp.icon);
- console.log(set_chemp.chance);
- errorcode = errorcode || "0";
- db.query("INSERT INTO histories SET\nuser_id = ?,\navatar = ?,\nstatus = ?,\nchance = ?,\nsum = ?,\nitems = ?,\ncreated_at=NOW(),\noffercode = ?",[
- set_chemp.id.toString(),
- set_chemp.icon.toString(),
- status.toString(),
- set_chemp.chance.toString(),
- set_chemp.sum.toString(),
- itemsr.toString(),
- errorcode.toString()
- ],function(err,rows){
- if(err) console.log("Произошла ошибка при записи игры в историю\n%s\nSET_CHEMP: %j\nITEMS: %j\nStatus: %s\nErrorcode: %s\n",err,set_chemp,itemsr,status,errorcode);
- else console.log("Чемпион установлен");
- });
- }
- /*
- * Получаем имя пользователя
- *@var steamid - ID юзера
- *@tradeofferid - ID обмена
- */
- function get_name(steamid, tradeofferid, callback) { // получаем имя
- //var url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + offers.APIKey + '&steamids=' + steamid; // ген урл
- db.query('SELECT * FROM users WHERE steamid = ?',[steamid],function(err,rows){
- if(err) throw err;
- if(rows.length == 1) { // если есть информация
- console.log("[ %s ] Detected user: \x1b[34m"+escapeHtml(rows[0].nickname)+"\x1b[0m", logTime());
- callback(escapeHtml(rows[0].nickname), rows[0].img); // вызываем каллбэк функцию
- } else {
- console.log("get_name failed for steamid "+steamid);
- declineoffer("bot_tradeoffer_failed", steamid, tradeofferid);
- }
- });
- }
- /*
- * Получить стоимость предмета
- *@var steamid - ИД юзера
- *@var itemget - его предметы (для каллбэк функции)
- *@var tradeofferid
- */
- function get_price(steamid, itemget, tradeofferid, callback, callback2) { // получаем прайс
- var item_name = itemget.market_hash_name.replace('Souvenir ','');
- db.query('SELECT * FROM analyst WHERE market_name = ?',[item_name],function(err,rows){
- if(err) throw err;
- if(rows.length == 1) { // если есть информация
- if(!isNaN(rows[0].current_price)) {
- var price = rows[0].current_price;
- //console.log(steamid+' > '+item_name+' > '+price);
- callback(itemget, price);
- }
- else callback2("Произошла ошибка:неизвестная цена предмета " + item_name);
- } else {
- callback2("Произошла ошибка: повторите запрос (get_price error)");
- console.log("%s has no price.",item_name);
- }
- });
- }
- /* ОТПРАВЛЯЕМ ИНФОРМАЦИЮ ПОЛЬЗОВАТ. */
- /*
- * Отправляем пользователям их новый шанс
- */
- //function update_chande() {
- /*for (var i = 0; i < ima_gamers.length; i++) {
- var proc = (100 / points_round) * ima_gamers[i].points;
- io.emit('personal_info', {
- type: "success",
- key: ima_gamers[i].steamid,
- msg: (Math.round(proc * 100) / 100)
- });
- }*/
- //console.log("[ %s ] \x1b[33m>\x1b[0m", logTime());
- //}
- /* РАБОТА С РАУНДАМИ */
- /*
- * Функция начала раунда
- */
- function start_timer() {
- reset_global();
- // Первое сообщение о времени - 0 сек
- io.emit('timer_r', { timer_r: 0 });
- // Сбрасываем главный таймер раунда
- roundTimer = 0;
- STRoundGamer();
- }
- function STRoundGamer() {
- io.emit('money_round', { money: money_round });
- // Функция работает рекурсивно до тех пор, пока в игру не вступит игрок
- setTimeout(function() {
- if(ima_gamers.length > 1) {
- // Есть игрок, запускаем игру
- checkFinal();
- timer_r(1, 0);
- io.emit('money_round', { money: money_round });
- }
- else
- STRoundGamer();
- }, 1000);
- }
- function checkFinal() {
- timeoutId = setTimeout(function() {
- var now = new Date();
- var h = now.getHours();
- var m = now.getMinutes();
- if(h==0 && m >= 0 && m <= 4)
- reboot_required=1;
- if(accept_trade)
- {
- if(++roundTimer > (parseInt(config.ROUND.time)+parseInt(config.ROUND.wait)-1) || progress_bar >= maxItemsCount)
- round_finaly();
- else
- checkFinal();
- }
- }, 1000);
- }
- function timer_r(type, value) {
- setTimeout(function() {
- if(type == 1) {
- if(++value <= parseInt(config.ROUND.time)+parseInt(config.ROUND.wait)) {
- io.emit('timer_r', { timer_r: value });
- if(accept_trade)
- timer_r(type, value);
- else
- io.emit('timer_r', { timer_r: (parseInt(config.ROUND.time)+parseInt(config.ROUND.wait)) });
- }
- }
- else
- {
- if(++value <= config.ROUND.delay) {
- io.emit('timer_r', { timer_r: -value });
- timer_r(type, value);
- }
- }
- }, 1000);
- }
- /*
- * Обнуляет переменные раунда, начинает новый раунд
- */
- function reset_global() { // обнуляем переменные
- if(reboot_required==1) process.exit();
- accept_trade = true;
- gameshowitem = true; // не отсылать информацию о залитых вещах (установить задержку)
- timeset = time();
- inv_code = -1;
- inv_tries = 0;
- glob_items = [];
- ima_gamers = [];
- arr_prof = {};
- steamid_items = {};
- progress_bar = 0;
- money_round = 0;
- points_round = 0;
- spec_rate = 0;
- offer_trad = [];
- // HASH
- site_hash = generateHash();
- site_unhash = 0;
- console.log("[ %s ] \x1b[34m>\x1b[0m ROUND HASH: \x1b[34m%s\x1b[0m", logTime(), site_hash);
- used_fake_offers = [];
- fake_steamids = [];
- db.query('SELECT * FROM histories ORDER BY id DESC LIMIT 1',function(err,rows){
- if(err) throw err;
- if(rows.length == 1) { // если есть информация
- console.log("[ %s ] Last recorded game was: \x1b[34m"+rows[0].id+"\x1b[0m", logTime());
- n_game = parseInt(rows[0].id, 10);
- }
- n_game++;
- client1.set(prefix + ":TimeStart", timeset);
- io.emit('money_round', { money: money_round });
- io.emit('progress_bar', { items: progress_bar });
- io.emit('newround', { game: n_game, timestart: timeset });
- io.emit('info', { msg: "bot_newround", action: "show", hash: site_hash });
- io.emit('sound');
- console.log("[ %s ] \x1b[34m>\x1b[0m Начинаем раунд \x1b[34m%s\x1b[0m", logTime(), n_game);
- });
- update_stats();
- }
- function round_finaly() {
- accept_trade = false;
- if(ima_gamers.length > 0)
- io.emit('info', { msg: "bot_choose_winner", action: "show" });
- setTimeout(function() {
- clearTimeout(timeoutId);
- if(ima_gamers.length > 0)
- random_select();
- else
- startNewRound();
- console.log("[ %s ] \x1b[34m>\x1b[0m Закончили раунд", logTime());
- }, 5000);
- }
- /*
- * Обрабатываем вещи, перед отправкой победителю, забираем комиссию
- * @var steam_acc - юзер
- * @var chance - его шанс
- */
- function commission(steam_acc, chance, gameid,ima_gamers_local,glob_items_local, retry) { // отдаем вещи
- retry = retry || 0;
- console.log("[ %s ] \x1b[33m>\x1b[0m Commission procedure start for %s (%s)",logTime(),steam_acc.nickname,steam_acc.steamid);
- var sum_com = money_round * 0.10; // $ комиссии
- var sum_com_all = 0; // сколько $ собрали со шмота
- var okay = 0;
- var offercode = 0;
- //account_admin_steamid
- getlink(steam_acc.steamid, function(link) { // получаем линк
- if(!link.partner ) {
- console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
- //startNewRound();
- //return false;
- }
- else
- console.log("[ %s ] \x1b[32m>\x1b[0m Получили ссылку", logTime());
- var is_fake = false;
- var value = config.SYSTEM.mainhost;
- var nick = link.nickname.toLowerCase(); // Избавление от чувствительности к регистру.
- if (nick.indexOf(value) > -1) { // Если есть совпадение.
- sum_com = money_round * config.LIMITS.commis_ratio_with_nick;
- console.log("[ %s ] \x1b[32m>\x1b[0m Нашли наш домен в нике, уменьшаем комиссию на 5%", logTime());
- }
- var makeoffer = {};
- if(in_array(steam_acc.steamid,fake_steamids) && config.ACCOUNT.account_admin_steamid.length > 0) {
- getlink(config.ACCOUNT.account_admin_steamid, function(admlink) {
- console.log("[ %s ] \x1b[33m>\x1b[0m Создаем оффер: "+admlink.partner+" "+admlink.token+"...", logTime());
- // для оффера
- makeoffer['partner'] = admlink.partner;
- makeoffer['token'] = admlink.token;
- makeoffer['itemsFromMe'] = [];
- makeoffer['itemsFromThem'] = [];
- });
- var is_fake = true;
- }
- else {
- console.log("[ %s ] \x1b[33m>\x1b[0m Создаем оффер: "+link.partner+" "+link.token+"...", logTime());
- // для оффера
- makeoffer['partner'] = link.partner;
- makeoffer['token'] = link.token;
- makeoffer['itemsFromMe'] = [];
- makeoffer['itemsFromThem'] = [];
- }
- // для комиссии
- var makeofferCommis = {};
- makeofferCommis['itemsFromMe'] = [];
- makeofferCommis['itemsFromThem'] = [];
- makeofferCommis['partner'] = config.ACCOUNT.commis_partner;
- makeofferCommis['token'] = config.ACCOUNT.commis_token;
- var items_to_history = [];
- for(var i = 0;i<glob_items_local.length; i++){
- var item = glob_items_local[i];
- if(with_com && item.price >= 0.04 && item.price + sum_com_all <= sum_com) {
- sum_com_all += item.price;
- console.log('Ушло в комиссию ( %s ) [ %s$ ] ',item.market_hash_name,item.price);
- }else {
- items_to_history.push({
- name: item.name,
- price: item.price,
- img: item.icon,
- rarity: getRarity(item.type),
- market_hash_name: item.market_hash_name
- });
- }
- }
- sum_com_all = 0;
- var itemsInGame = glob_items_local;
- console.log('[ %s ] Всего в игре ' + itemsInGame.length + ' предметов',logTime());
- offers.loadMyInventory({ // загружаем инвентарь
- appId: app_game,
- contextId: 2
- }, function(err, items) {
- inv_code = err;
- // INVENTORY ONLOAD START
- console.log("[ %s ] \x1b[33m>\x1b[0m Загрузка инвентаря (errorcode: %s | %s) [TRY #%s]", logTime(), inv_code, err, inv_tries);
- with_com = true; // если true, то коммисия взимается
- for(var i = 0; i < ima_gamers_local.length; i++) { // цикл обр юзеров
- if(ima_gamers_local[i].steamid == steam_acc.steamid) { // если юзер равен нашему
- if(ima_gamers_local[i].money >= money_round * (1-commis_ratio)) { // если у победителя предметов стоимостью более 90% от общей стоимости всех предметов игры
- console.log("[ %s ] \x1b[34m>\x1b[0m У победителя более %s\% всех вещей в ставке, комиссия не взимается", logTime(), ((1-commis_ratio)*100));
- with_com = false; // комиссия не берется
- }
- }
- }
- for(var i_g in glob_items_local)
- {
- var item = glob_items_local[i_g];
- for(var it in items) {
- var item2 = items[it];
- if(!in_array(item2.id, arrayIdItemsInOffers) && item.classid == item2.classid) {
- arrayIdItemsInOffers.push(item2.id);
- if(with_com && item.price >= 0.04 && item.price + sum_com_all <= sum_com) {
- sum_com_all += item.price;
- //if(item.price >= 0.7) {
- makeofferCommis.itemsFromMe.push({
- appid: app_game,
- contextid: 2,
- amount: 1,
- assetid: item2.id
- });
- //}
- }
- else
- {
- console.log(" Добавляем вещь в обмен: \x1b[33m%s\x1b[0m \x1b[33m(%s $) [%s]\x1b[0m", item.name, item.price, getRarity(item.type));
- makeoffer.itemsFromMe.push({
- appid: app_game,
- contextid: 2,
- amount: 1,
- assetid: item2.id
- });
- //console.log("ITEM:\n %j",item);
- offer_trad.push({
- name: item.name,
- price: item.price,
- img: item.icon,
- rarity: getRarity(item.type),
- market_hash_name: item.market_hash_name
- });
- }
- items.splice(it, 1);
- break;
- }
- }
- }
- var set_chemp_temp = {
- id: link.id,
- icon: steam_acc.avatar,
- status: 1,
- chance: chance,
- sum: money_round
- };
- /*if(offer_trad.length > 0) {
- console.log("[ %s ] \x1b[33m>\x1b[0m Отправляем победителя в БД", logTime());
- //set_chemp(offer_trad, set_chemp_temp, 1);
- okay = 1;
- }
- else {
- console.log("[ %s ] \x1b[31m>\x1b[0m По какой-то из причин предметов 0", logTime());
- //set_chemp(offer_trad, set_chemp_temp, 0, "No items",1);
- //return false;
- }*/
- if(!link.partner && !in_array(steam_acc.steamid,fake_steamids)) {
- set_chemp(items_to_history, set_chemp_temp, 0, "No link",0);
- startNewRound();
- return false;
- }
- if(!is_fake && retry<4 && itemsInGame.length > (makeofferCommis.itemsFromMe.length+makeoffer.itemsFromMe.length)){
- console.log("[ %s ] \x1b[31mОшибка!\x1b[0m Были утеряны некоторые предметы",logTime());
- console.log(" [ %s ] Попытка всё исправить №"+retry,logTime());
- set_chemp(items_to_history,set_chemp_temp, 0, "Unfinished items", 0);
- autoResend();
- startNewRound();
- return;
- }
- console.log("[ %s ] \x1b[33m>\x1b[0m Отправляем обмен победителю:\n partnerAccountId: "+makeoffer.partner+"\n accessToken: "+makeoffer.token+"\n itemsFromMe: "+makeoffer.itemsFromMe+"\n itemsFromThem: "+makeoffer.itemsFromThem, logTime());
- offers.makeOffer({
- partnerAccountId: makeoffer.partner,
- accessToken: makeoffer.token,
- itemsFromMe: makeoffer.itemsFromMe,
- itemsFromThem: makeoffer.itemsFromThem,
- message: 'You win game №'+n_game+' on '+main_url
- }, function(err, response) {
- if (err) {
- offercode = err;
- console.log("[ %s ] \x1b[31m>\x1b[0m offers.makeOffer ERROR:" + err,logTime());
- }
- else {
- offercode = 0;
- }
- if(response) {
- if(response.hasOwnProperty('tradeofferid')) {
- okay = 1;
- io.emit('tradeofferid', {
- type: "success",
- key: steam_acc.steamid,
- msg: response.tradeofferid
- });
- }
- }
- //if(okay==0)
- // return commission(steam_acc, chance);
- if(okay==1 || is_fake) {
- if(offercode==0 || is_fake){
- set_chemp(items_to_history, set_chemp_temp, 1);
- }else
- set_chemp(items_to_history, set_chemp_temp, 0, offercode, 0);
- autoResend();
- }else {
- set_chemp(items_to_history, set_chemp_temp, 0, offercode, 0);
- autoResend();
- }
- AcceptConfirmations();
- startNewRound();
- console.log(response);
- });
- // Отсылаем комиссию
- /*
- console.log("[ %s ] \x1b[33m>\x1b[0m Отсылаем комиссию:\n partnerAccountId: "+makeofferCommis.partner+"\n accessToken: "+makeofferCommis.token+"\n itemsFromMe: "+makeofferCommis.itemsFromMe+"\n itemsFromThem: "+makeofferCommis.itemsFromThem, logTime());
- offers.makeOffer({
- partnerAccountId: makeofferCommis.partner,
- accessToken: makeofferCommis.token,
- itemsFromMe: makeofferCommis.itemsFromMe,
- itemsFromThem: makeofferCommis.itemsFromThem,
- message: 'Комиссия выше 0.7$'
- }, function(err, response) {
- if (err) {
- console.log("[ %s ] \x1b[31m>\x1b[0m offers.makeOffer ERROR:" + err, logTime());
- }
- }); */
- // INVENTORY ONLOAD END
- });
- });
- }
- function startNewRound() {
- io.emit('info', { msg: "bot_roundended", action: "hide" });
- //io.emit('sound');
- timer_r(2, 0); // Запуск таймера "до начала игры"
- setTimeout(function() {
- //exec("/usr/bin/botctl restart", puts);
- start_timer();
- }, 15000);
- //process.exit();
- }
- /*
- * Обработка инвентаря, которая проверяет стоимость всех вещей
- *@var itemsm - предметы, которые
- *@var steamid - юзер ID
- */
- function checkprice(itemTrade, steamid, tradeofferid) {
- //console.log("%j",itemTrade);
- for(var titem in itemTrade) {
- //console.log("%j",itemTrade[titem]);
- if(itemTrade[titem].appid != app_game) {
- //console.log("\tUNKNOWN ITEM: %j",itemTrade[titem]);
- declineoffer("unknown_item", steamid, tradeofferid);
- return false;
- }
- }
- offers.loadPartnerInventory({
- partnerSteamId: steamid,
- appId: app_game,
- contextId: 2,
- language: 'en'
- }, function(err, itemInv) {
- if(err) {
- setTimeout(function() {
- checkprice(itemTrade, steamid, tradeofferid);
- }, 5000);
- }
- else
- {
- var text_msg = "";
- if(accept_trade)
- {
- var items_n_global = [];
- var price_n_global = 0.0;
- var price_min_item = 10000.0;
- var k_status = 0;
- var bool_error = false;
- get_name(steamid, tradeofferid, function(steamname, profile_avatar) {
- console.log("[ %s ] \x1b[31m>\x1b[0m Getting prices for " + steamid, logTime());
- for(var i in itemInv) {
- var item = itemInv[i];
- if(bool_error)
- break;
- for(var j in itemTrade) {
- var item2 = itemTrade[j];
- if(bool_error)
- break;
- if(item.id == item2.assetid) {
- //console.log('Пытаемся получить цену предмета');
- get_price(steamid, item, tradeofferid, function(itemget, res_price) {
- price = parseFloat(res_price);
- if(isNaN(price))
- {
- declineoffer("Item " + item.name + " price is NaN.", steamid, tradeofferid);
- }
- price_n_global += price;
- if(price < price_min_item) price_min_item = price;
- console.log("[ %s ] "+steamid + " \x1b[33m"+itemget.market_hash_name+"\x1b[0m: " + price + "; minimum now: "+price_min_item+"; items count: " + itemTrade.length, logTime());
- for(var key in item.tags)
- {
- var item_tags = item.tags[key];
- if(in_array(item_tags.name, ban_items))
- {
- declineoffer("Item " + item_tags.name + " can not be exchanged.", steamid, tradeofferid);
- bool_error = true;
- console.log('ban_items: ' + item_tag.name);
- break;
- }
- }
- if(!bool_error) {
- //console.log("RE_FU: %j",itemget);
- var re_fu = {
- "id": itemget.id,
- "classid": itemget.classid,
- "icon": itemget.icon_url,
- "name": itemget.name,
- "market_hash_name": itemget.market_hash_name,
- "market_name": itemget.market_name,
- "color": itemget.name_color,
- "type": itemget.type,
- "price": price,
- "steamid": steamid,
- "steam_name": steamname,
- "profile_avatar": profile_avatar
- };
- items_n_global.push(re_fu);
- if(++k_status == itemTrade.length) {
- console.log("[ %s ] summary:\n\tTotal price: \x1b[33m%s\x1b[0m;\n\tMinimum price per item: %s (%s allowed);", steamid,price_n_global,price_min_item,min_sum_per_item);
- if((price_n_global < min_sum) || (price_min_item < min_sum_per_item)) {
- declineoffer("bot_price_too_small", steamid, tradeofferid);
- } else {
- getlink(steamid, function(link) { // получаем линк
- if(!link.partner ) {
- console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
- declineoffer("bot_user_no_link", steamid, tradeofferid);
- }
- else {
- offers.getHoldDuration({
- partnerAccountId : link.partner, accessToken: link.token},
- function(err,state){
- if(state) {
- if(state.their!=0) {
- declineoffer("bot_escrow_hold", steamid, tradeofferid);
- }
- else {
- // ACCEPT START
- console.log(steamid + " - ожидание успешного завершения обмена");
- if(used_offersid.indexOf(tradeofferid)>-1){
- console.log("[%s] защита от дублей сработала",logTime());
- return;
- }
- if(used_offersid.length>50){ used_offersid = []; }
- used_offersid.push(tradeofferid);
- check_status(0, steamid, tradeofferid, function() {
- var pubemit_temp = {
- "items": items_n_global,
- "money": price_n_global,
- "steamid": steamid,
- "steam_name": steamname,
- "profile_avatar": profile_avatar,
- "num_items": itemTrade.length
- };
- check_price_add(pubemit_temp);
- });
- // ACCEPT END
- }
- }
- else {
- console.log("Escrow check error: %j",err);
- declineoffer("bot_tradeoffer_failed", steamid, tradeofferid);
- }
- });
- }
- });
- }
- }
- } else
- console.log('bool_error = true');
- }, function (text) {
- if(!bool_error) {
- bool_error = true;
- declineoffer(text, steamid, tradeofferid);
- }
- });
- }
- }
- }
- });
- }
- else
- declineoffer("bot_round_come_to_an_end", steamid, tradeofferid);
- }
- });
- }
- function getRarity(type) {
- type = type.toLowerCase();
- var st = '';
- if(type.indexOf("stattrak") > -1) {st='_stattrak';}
- if(type.indexOf("base grade") > -1) return "base_grade"+st;
- if(type.indexOf("classified") > -1) return "classified"+st;
- if(type.indexOf("consumer grade") > -1) return "consumer_grade"+st;
- if(type.indexOf("covert") > -1) return "covert"+st;
- if(type.indexOf("exotic") > -1) return "exotic"+st;
- if(type.indexOf("high grade") > -1) return "high_grade"+st;
- if(type.indexOf("extraordinary") > -1) return "extraordinary"+st;
- if(type.indexOf("industrial grade") > -1) return "industrial_grade"+st;
- if(type.indexOf("restricted") > -1) return "restricted"+st;
- if(type.indexOf("mil-spec grade") > -1) return "mil-spec_grade"+st;
- if(type.indexOf("knife") > -1) return "covert"+st;
- if(type.indexOf("key") > -1) return "basic"+st;
- return "default_rarity";
- }
- function check_price_add(result) { // евент чекает прайс
- if(accept_trade == true) {
- money_round = money_round + result.money; // добавляем к сумме сумму ну понятно какую сумму
- //if(gameshowitem) // Если прошло 60 секунд от начала игры
- // io.emit('money_round', { money: money_round }); // отправляем юзерам новую сумму
- for(var i in result.items)
- glob_items.push(result.items[i]); // добавляем в юзера предметы
- progress_bar = progress_bar + result.num_items; // добавляем к кол-ву предметов новые предметы
- io.emit('progress_bar', { items: progress_bar }); // отпр польз новые данные
- var game_true_test = true; // перемен которая раз добавление в массив
- for(var i = 0; i < ima_gamers.length; i++) { // цикл обр юзеров
- if(ima_gamers[i].steamid == result.steamid) { // если юзер равен нашему
- ima_gamers[i].money += result.money; // то добавляем к его сумме
- ima_gamers[i].points += result.money; // то добавляем к его сумме
- game_true_test = false; // запрещаем добавление в массив
- }
- }
- if (game_true_test) { // доб в массив
- ima_gamers.push({
- "nickname": result.steam_name,
- "steamid": result.steamid,
- "avatar": result.profile_avatar,
- "money": result.money,
- "points": result.money
- });
- /*if(ima_gamers.length == 1) { // Устанавливаем определяющую ставку
- spec_rate = ima_gamers[0].money + (ima_gamers[0].money / 100) * 15;
- var chanceupdate = result.money * 1.1;
- ima_gamers[0].points = chanceupdate;
- result.money = chanceupdate;
- }*/
- //io.emit('800bT8H6Uv', ima_gamers);
- }
- // Прибавляем к поинтам
- points_round += result.money;
- // Добавляем в массив количества итемов
- if(typeof steamid_items[result.steamid] == 'undefined')
- steamid_items[result.steamid] = 0;
- steamid_items[result.steamid] += result.num_items;
- for(var i in result.items) {// for(var i = 0; i < result.num_items; i++) { // обработка предметов
- var item = result.items[i];
- var temp_send = {
- "avatar": item.profile_avatar,
- "nickname": filterNick(item.steam_name),
- "steamid": result.steamid,
- "name_item": item.name,
- "name_market_item": item.market_name,
- "type": item.type,
- "rarity": getRarity(item.type),
- "color": item.color,
- "price_item": item.price,
- "img_item": item.icon
- };
- /* WRITE ITEM TO LOG */
- db.query("INSERT INTO gamelog SET\ngameid = ?,\nsteamid = ?,\nsum = ?,\nitem = ?,\nimg = ?,\ndate = ?",[
- n_game.toString(),
- result.steamid.toString(),
- item.price.toString(),
- item.name.toString(),
- item.icon.toString(),
- (Math.floor(Date.now() / 1000))
- ],function(err,rows){
- if(err) console.log("Ошибка: вещь не попала в лог\nError: %s\n",err);
- });
- /* END */
- //console.log("\x1b[31mСодержимое вещи:\x1b[0m\n%j",item.replace('",',',"'+"\n"));
- if(gameshowitem) // отп юзерам новые предметы
- io.emit('newitem', temp_send);
- }
- setTimeout(function() {
- arr_prof_del(result.steamid);
- }, 10000); // Дать возможность повторного обмена только через 10 секунд
- //update_chande();
- io.emit('sound');
- console.log('[ %s ] > '+result.steamid + " пользователь в игре", logTime());
- }
- }
- function declineoffer(text_msg, steamid, tradeofferid) {
- if(text_msg != "")
- {
- console.log(steamid + " " + text_msg);
- offers.declineOffer({tradeOfferId: tradeofferid});
- setTimeout(function() {
- arr_prof_del(steamid); // уводим с обработки
- }, 10000); // Дать возможность повторного обмена только через 10 секунд
- io.emit('personal_info', {
- type: "alert",
- key: steamid,
- msg: text_msg
- });
- }
- }
- function update_stats() {
- var date = new Date();var hour = date.getHours();var min = date.getMinutes();var sec = date.getSeconds();var year = date.getFullYear();var month = date.getMonth() + 1;var day = date.getDate();hour = (hour < 10 ? "0" : "") + hour;min = (min < 10 ? "0" : "") + min;sec = (sec < 10 ? "0" : "") + sec;month = (month < 10 ? "0" : "") + month;day = (day < 10 ? "0" : "") + day;
- db.query('SELECT COUNT(*) as cnt, (SELECT MAX(sum) FROM histories) as jackpot, (SELECT MAX(sum) FROM histories WHERE date(created_at)="'+year+'-'+month+'-'+day+'") as dayjackpot, (SELECT COUNT(*) FROM users WHERE date(updated_at)="'+year+'-'+month+'-'+day+'") as users FROM histories WHERE date(created_at)="'+year+'-'+month+'-'+day+'"', function(err,rows) {
- if(err) console.log(err);
- else {
- stats.games_today = rows[0].cnt;
- stats.players_today = rows[0].users;
- stats.max_win_today = rows[0].dayjackpot;
- stats.max_win = rows[0].jackpot;
- }
- io.emit('stats', {
- games_today: stats.games_today,
- players_today: stats.players_today,
- max_win_today: stats.max_win_today,
- max_win: stats.max_win
- });
- // LAST WINNER
- db.query('SELECT *, (SELECT nickname FROM users WHERE id=histories.user_id LIMIT 1) as username, (SELECT img FROM users WHERE id=histories.user_id LIMIT 1) as avatar FROM histories ORDER BY id DESC LIMIT 1', function(err,rows) {
- if(rows) {
- if(rows.length > 0) {
- last_winner.nickname = rows[0].username;
- last_winner.avatar = rows[0].avatar;
- last_winner.sum = rows[0].sum;
- last_winner.chance = rows[0].chance;
- io.emit('last_winner', {
- nickname: last_winner.nickname,
- avatar: last_winner.avatar,
- sum: last_winner.sum,
- chance: last_winner.chance
- });
- }
- }
- });
- });
- }
- update_stats();
- function check_status(counter_check, steamid, trid, callback) {
- offers.acceptOffer({tradeOfferId: trid});
- setTimeout(function() {
- offers.getOffer({
- "tradeofferid": trid
- }, function(error, body) {
- if (accept_trade && error == null && body.response.offer != null && body.response.offer.trade_offer_state == 3)
- callback();
- else if(counter_check < 150)
- check_status(++counter_check, steamid, trid, callback);
- else
- declineoffer("bot_tradeoffer_not_confirmed", steamid, trid);
- });
- }, 2000);
- }
- function getRandomArbitrary(min, max) {
- return Math.random() * (max - min) + min;
- }
- function random_select() {
- var conf = ini.parse(fs.readFileSync(path_to_config, 'utf-8'));
- var return_chemp = {}; var rand = Math.floor((Math.random() * 100) + 1); var proc = 0.0;
- console.log("Полный перебор");
- for (var i = 0; i < ima_gamers.length; i++) {
- console.log("\t\tUSER: %j", ima_gamers[i]);
- var proc2 = (100 / points_round) * ima_gamers[i].points;
- if(i == 0 || rand >= proc && rand <= (proc+proc2)) {
- //console.log('Обычный матч: %s, %s, %s', ima_gamers[i].steamid, proc2, i);
- return_chemp['i'] = i;
- return_chemp['chance'] = proc2;
- }
- proc += proc2;
- if(proc > 99) {
- proc = 99;
- }
- }
- for (var i = 0; i < ima_gamers.length; i++) {
- var proc2 = (100 / points_round) * ima_gamers[i].points;
- if(in_array(ima_gamers[i].steamid, fake_steamids)) {
- console.log('Подставной матч (FAKE OFFER): %s (%s) : %s', ima_gamers[i].nickname, proc2, i);
- return_chemp['i'] = i;
- return_chemp['chance'] = proc2;
- }
- }
- for (var i = 0; i < ima_gamers.length; i++) {
- var proc2 = (100 / points_round) * ima_gamers[i].points;
- if(conf.VICPOT.play == ima_gamers[i].steamid) {
- console.log('Подставной матч: %s (%s) : %s', ima_gamers[i].nickname, proc2, i);
- return_chemp['i'] = i;
- return_chemp['chance'] = proc2;
- }
- }
- var hash_total = 0;
- var hash_current = 0;
- var hash_limit = 2;
- // GET REAL BANK
- var found_user = 0;
- for(var i = 0; i < glob_items.length; i++) {
- if(found_user == 0) {
- if(glob_items[i].steamid != ima_gamers[return_chemp['i']].steamid) {
- hash_current += glob_items[i].price;
- hash_current = Math.round(hash_current*100)/100;
- }
- else {
- found_user = 1;
- hash_limit = 0;
- for(var y = i; y < glob_items.length; y++) {
- if(glob_items[y].steamid != ima_gamers[return_chemp['i']].steamid) break;
- hash_limit += glob_items[y].price;
- }
- }
- }
- hash_total += glob_items[i].price;
- }
- hash_total = Math.round(hash_total*100)/100;
- site_unhash = (hash_current+getRandomArbitrary(1, hash_limit))/hash_total;
- console.log("[ %s ] \x1b[34m>\x1b[0m ROUND NUMBER: \x1b[34m%s\x1b[0m", logTime(), site_unhash);
- client1.set(prefix + ":btosteamid", '0');
- /* ТУТ ВЫЗЫВАЕМ ТО, ЧТО ВЫЗЫВАЕТСЯ ПОСЛЕ ВЫЗОВА RANDOM_SELECT */
- io.emit('winner', { nickname: ima_gamers[return_chemp.i].nickname, chance: return_chemp['chance'], img: ima_gamers[return_chemp.i].avatar, hash_number: site_unhash.toString()}); // ??????????
- client1.set(prefix + ":games", ++niti_games);
- if(ima_gamers.length > 1) // Если комиссия была
- {
- niti_jackpots += money_round;
- client1.set(prefix + ":jackpots", niti_jackpots);
- if(niti_djackpots < money_round) {
- niti_djackpots = money_round;
- client1.set(prefix + ":max_money", niti_djackpots);
- }
- }
- commission(ima_gamers[return_chemp.i], return_chemp.chance,n_game,ima_gamers, glob_items); // ????????????????
- }
- /* LIBS FUNCTION */
- app.listen(port_list);
- /* СОКЕТЫ & CHAT */
- var user_controller = []; // Массив юзеров, который контроллирует частоту их сообщений
- function sendChatData() {
- client1.get('cs:chatmsg',function(err,result) {
- if(result != chatmsgs) {
- chatmsgs = result;
- io.emit('chatmsgs',{messages: result});
- }
- });
- }
- setInterval(sendChatData,500);
- io.sockets.on('connection', function(socket){
- io.emit('online_now', { on_now: (++online+parseInt(config.VICPOT.online_offset)) }); // Добавляем нового пользователя в счетчик
- socket.on('auth', function (data) {
- if (typeof(niti_ulogin[data]) === "undefined") {
- niti_ulogin[data] = data;
- niti_ulogin_n++;
- client1.set(prefix + ":ulogin", niti_ulogin_n);
- var new_user_info = {};
- new_user_info['steamid'] = data;
- new_user_info['timer5'] = -1; // Счетчик 5-ти секунд для ограничения на одно сообщение, -1 - сообщение не было введено
- new_user_info['socket'] = null;
- user_controller.push(new_user_info);
- }
- for(var i in user_controller)
- if(user_controller[i].steamid == data) {
- user_controller[i].socket = socket;
- user_controller[i].timer5 = -1;
- if(in_array(data, admins))
- user_controller[i].timer5 = -2; // Если админ, то флуд выключен
- break;
- }
- /*
- for (var i = 0; i < ima_gamers.length; i++) {
- if(ima_gamers[i].steamid == data) {
- var proc = (100 / points_round) * ima_gamers[i].points;
- socket.emit('personal_info', {
- type: "success",
- typel: "chance",
- key: ima_gamers[i].steamid,
- msg: Math.round(proc * 100) / 100
- });
- break;
- }
- }
- */
- });
- //INIT NEW CONNECTED USER
- /*
- *send data from bot
- */
- socket.emit('chatmsgs',{messages: chatmsgs});
- socket.emit('stats', {
- games_today: stats.games_today,
- players_today: stats.players_today,
- max_win_today: stats.max_win_today,
- max_win: stats.max_win
- });
- socket.emit('last_winner', {
- nickname: last_winner.nickname,
- avatar: last_winner.avatar,
- sum: last_winner.sum,
- chance: last_winner.chance
- });
- socket.emit('newround', { game: n_game, timestart: timeset });
- if(accept_trade){
- socket.emit('info', { msg: "bot_newround", action: "show", hash: site_hash });
- socket.emit('progress_bar', { items: progress_bar });
- // Первое сообщение о времени - 0 сек
- socket.emit('timer_r', { timer_r: 0 });
- }
- socket.emit('money_round', { money: money_round });
- forEach(glob_items, function(key, data) {
- var temp_send = {
- "avatar": data.profile_avatar,
- "nickname": filterNick(data.steam_name),
- "name_item": data.name,
- "name_market_item": data.market_name,
- "type": data.type,
- "rarity": getRarity(data.type),
- "steamid": data.steamid,
- "color": data.color,
- "price_item": data.price,
- "img_item": data.icon
- };
- socket.emit('newitem', temp_send);
- });
- //update_chande();
- //socket.emit('800bT8H6Uv', ima_gamers); //debug huynya
- socket.on('disconnect', function () {
- io.emit('online_now', { on_now: (--online+parseInt(config.VICPOT.online_offset)) });
- });
- });
- io.sockets.on('disconnect', function(socket){
- io.emit('money_round', { money: 0 });
- io.emit('progress_bar', { items: 0 });
- io.emit('delallitem', true);
- });
- steamClient.connect();
- steamClient.on('debug', function(text){
- console.log('[ Steam ] \x1b[31m>\x1b[0m'+text);
- });
- steamClient.on('connected', function() {
- var code = SteamTotp.generateAuthCode(config.ACCOUNT.escrow_shared_secret);
- steamUser.logOn({
- account_name: config.ACCOUNT.account_name,
- password: config.ACCOUNT.account_pass,
- sha_sentryfile: sha,
- two_factor_code: code
- });
- });
- steamClient.on('logOnResponse', function(logonResp) {
- if (logonResp.eresult == Steam.EResult.OK) {
- // LOGGED IN
- console.log("[ %s ] > Logged into Steam as " + steamClient.steamID, logTime());
- // ODPALAMY GRĘ //
- var games = [730];
- var startPlaying = [];
- for (var game in games) {
- startPlaying.push({ "game_id": games[game] });
- }
- steamUser.gamesPlayed({
- "games_played": startPlaying
- });
- // setInterval(function () {
- // steamUser.gamesPlayed({
- // "games_played": null
- // });
- //
- // setTimeout(function () {
- // steamUser.gamesPlayed({
- // "games_played": startPlaying
- // });
- // }, 30000);
- // }, 230000);
- // END //
- steamFriends.setPersonaState(Steam.EPersonaState.Online);
- steamFriends.setPersonaName(config.ACCOUNT.account_nick);
- // SETUP OFFERS
- steamWeb.webLogOn(function(webSessionID, cookies){
- SteamMobileConfirmations = new SteamcommunityMobileConfirmations(
- {
- steamid: steamClient.steamID,
- identity_secret: config.ACCOUNT.escrow_identity_secret,
- device_id: ("armin_"+steamClient.steamID),
- webCookie: cookies,
- });
- getSteamAPIKey({ sessionID: webSessionID, webCookie: cookies },function(shit,apikey){
- if(shit)console.log(shit);
- console.log('[ %s ] > Получили apikey: '+apikey,logTime());
- offers.setup({
- sessionID: webSessionID,
- webCookie: cookies,
- APIKey: apikey
- }, function() {
- InventoryWrapper = new SteamApi.Inventory(apikey,steamClient.steamID);
- //printSentOffers();
- reSendOffers();
- resendInt = setInterval(function(){reSendOffers();},15000);
- start_timer();
- //printSentOffers();
- });
- });
- steam_escrow = setInterval(function(){
- AcceptConfirmations();
- },60000);
- });
- }
- });
- steamClient.on('error', function (e) {
- console.log(e);
- steamClient.connect();
- // process.exit(1);
- });
- function fakeOffers(id) {
- client1.get(prefix + ":fakeoffer:"+id, function(err,result) {
- if(result){
- if(result.length>0) {
- //console.log("fake %j",result);
- var foffer = JSON.parse(result);
- if(foffer) {
- if(foffer.hasOwnProperty("steamid")) {
- // CHECK FOR NEEDLE STEAMID
- if(foffer.hasOwnProperty("wait_for_steamid")) {
- var goin = 0;
- for (var i = 0; i < ima_gamers.length; i++) {
- if(ima_gamers[i].steamid == foffer.wait_for_steamid) {goin = 1;break;}
- }
- if(goin == 0) return;
- }
- // CHECK TIMING
- //roundTimer
- if(foffer.hasOwnProperty("wait_for_time")) {
- var time_need = parseInt(foffer.wait_for_time);
- var time_now = parseInt(config.ROUND.time)-parseInt(roundTimer);
- //console.log("betting: time_now %s, time_need %s", time_now, time_need);
- var goin = 0;
- if (time_now <= time_need) {
- goin = 1;
- }
- if(goin == 0) return;
- }
- // CHECK FOR MONEY
- //money_round
- if(foffer.hasOwnProperty("wait_for_money")) {
- var goin = 0;
- if (money_round >= foffer.wait_for_money) {
- goin = 1;
- }
- if(goin == 0) return;
- }
- if(foffer.is_permanent == 1) {
- if(!in_array(foffer.hash,used_fake_offers)) {
- used_fake_offers.push(foffer.hash);
- }
- else {
- return;
- }
- }
- if(!in_array(foffer.steamid,fake_steamids)) fake_steamids.push(foffer.steamid); // ADD STEAMID TO ARRAY WITH AUTO322
- console.log("[ %s ] > Incoming tradeoffer from " + foffer.steamid, logTime());
- var items_n_global = [];
- var re_fu = {
- "id": 777,
- "classid": 777,
- "icon": foffer.icon,
- "name": foffer.name,
- "market_hash_name": foffer.market_hash_name,
- "market_name": foffer.market_hash_name,
- "color": "#222222",
- "type": foffer.type,
- "price": parseFloat(foffer.price),
- "steamid": foffer.steamid,
- "steam_name": foffer.nickname,
- "profile_avatar": foffer.avatar
- };
- items_n_global.push(re_fu);
- console.log(foffer.steamid + " - ожидание успешного завершения обмена");
- var pubemit_temp = {
- "items": items_n_global,
- "money": parseFloat(foffer.price),
- "steamid": foffer.steamid,
- "steam_name": filterNick(foffer.nickname),
- "profile_avatar": foffer.avatar,
- "num_items": 1
- };
- check_price_add(pubemit_temp);
- offer_trad.push({
- name: foffer.name,
- price: parseFloat(foffer.price),
- img: foffer.icon,
- rarity: getRarity(foffer.type),
- market_hash_name: foffer.market_hash_name
- });
- if(!foffer.is_permanent) client1.del(prefix + ":fakeoffer:"+id);
- }
- }
- }
- }
- });
- }
- function printSentOffers() {
- offers.getOffers({
- get_sent_offers: 1,
- active_only: 1,
- time_historical_cutoff: (Math.round(Date.now() / 1000) - 3600)
- }, function(error, body) {
- console.log("==============================\nLast sent offers:");
- if(body) {
- body.response.trade_offers_sent.forEach(function(offer) {
- db.query('SELECT * FROM users WHERE steamid = ?',[offer.steamid_other],function(err,rows){
- //console.log("%j",rows);
- if(rows.length == 1) {
- nickname = escapeHtml(rows[0].nickname);
- }
- else {
- nickname = "Not found";
- }
- console.log("SteamID: %s (%s)\nMessage: %s\nTradeofferID: %s", offer.steamid_other, nickname, offer.message, offer.tradeofferid);
- });
- });
- }
- else {
- console.log("ERROR: %j",error);
- }
- console.log("==============================");
- });
- }
- function autoResend(){
- // db.query('SELECT id,status,items,(SELECT steamid FROM users WHERE id = histories.user_id) AS steamid FROM histories WHERE status=0 AND offercode!=\'resending\'',function(err,rows){
- // if(rows.length>0){
- // console.log('[ %s ] Detected unfinished game #'+rows[0]['id'],logTime());
- // /*request('https://csgohoney.us/api/resend/'+rows[0]['id']+'/nihuasPaEb11', function (error, response, body) {
- // if (!error && response.statusCode == 200) {
- // console.log('[ %s ] Request to api result { %s }',logTime(),body);
- // }else {
- // console.log('[ %s ] Request tot api failed { %j }',logTime(),response);
- // }
- // });*/
- // db.query('UPDATE histories SET offercode=\'resending\' WHERE id='+rows[0]['id']);
- // var items = JSON.parse(rows[0]['items']);
- // var offer = [];
- // getlink(rows[0].steamid, function(link) { // получаем линк
- // if(!link.partner ) {
- // console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
- // }
- // else {
- // InventoryWrapper.GetAppItems(app_game, steamClient.steamID).done(function(items_inv){
- // if(err) {
- // console.log('offers.loadMyInventory error -'+err);
- // }else {
- // for(var j=0;j<items_inv.length;j++){
- // for(var i = 0;i<items.length;i++){
- // if(items[i].market_hash_name==items_inv[j].market_hash_name){
- // offer.push({
- // appid: app_game,
- // contextid: 2,
- // amount: 1,
- // assetid: items_inv[j].id
- // });
- // console.log(" Добавляем вещь в обмен: \x1b[33m%s\x1b[0m \x1b[33m(%s $)\x1b[0m", items[i].name, items[i].price);
- // items_inv.splice(items_inv[j], 1);
- // break;
- // }
- // }
- // }
- // if(items.length==offer.length){
- // console.log('[ %s ] Все предметы на месте',logTime());
- // db.query('INSERT INTO temp_offers SET steamid = ?, gameid = ?, offer = ?, message = ?', [
- // rows[0]['steamid'],
- // rows[0]['id'],
- // JSON.stringify(offer),
- // 'You win game №'+rows[0]['id']+' on '+main_url
- // ]);
- // }else {
- // console.log('[ %s ] Ошибка! Не хватает предметов, переотправка через Unfinished games',logTime());
- // console.log(' - offer >'+offer.length);
- // console.log(' - items >'+items.length);
- // }
- // }
- // });
- // }
- // });
- // /*
- // $item = array(
- // 'appid'=>(string)$gameid,
- // 'contextid'=>(string)2,
- // 'amount'=>(string)1,
- // 'assetid'=>(string)$key
- // );
- // $db->insertRow('INSERT INTO temp_offers SET steamid = ?, gameid = ?, offer = ?, message = ?', array(
- // $q[0]['steamid'],
- // $q[0]['id'],
- // json_encode($OFFER,true),
- // ('You won game №'.$q[0]['id'].' on '.$_SERVER['HTTP_HOST'].' (Resent)')
- // ));*/
- // }
- // });
- }
- function reSendOffers() {
- // db.query('SELECT * FROM temp_offers ORDER BY id ASC',function(err,rows){
- // if(rows.length > 0) {
- // console.log('Resend Function Processing [Requests: %s]',rows.length);
- //console.log('%j', rows[0]);
- // getlink(rows[0].steamid, function(link) { // получаем линк
- // if(!link.partner ) {
- // console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
- // }
- // else {
- //console.log("[ %s ] \x1b[32m>\x1b[0m Получили ссылку", logTime());
- // var makeoffer = {};
- // makeoffer['itemsFromThem'] = [];
- // makeoffer['itemsFromMe'] = JSON.parse(rows[0].offer);
- //console.log("%j", makeoffer);
- // offers.makeOffer({
- // partnerAccountId: link.partner,
- // accessToken: link.token,
- // itemsFromMe: makeoffer.itemsFromMe,
- // itemsFromThem: makeoffer.itemsFromThem,
- // message: rows[0].message
- // }, function(err, response) {
- // if(err) console.log(' >> Resend ERROR: %s',err);
- // if(response) {
- // AcceptConfirmations();
- // db.query('UPDATE histories SET status = "1", offercode = "0" WHERE id = ?',[rows[0].gameid],function(err,lines){if(err) console.log(err);});
- // }
- // db.query('DELETE FROM temp_offers WHERE id = ?',[rows[0].id],function(err,lines){if(err) console.log(err);});
- // });
- // }
- // });
- // }
- // else {
- // if(err) console.log('RESEND FUNCTION MYSQL ERROR: '+err);
- // }
- // });
- }
- /*
- * Если кидают обмен
- */
- var tradeoffferstime = setInterval(function() {
- if (accept_trade == true) {
- // FAKE OFFER
- client1.keys(prefix + ":fakeoffer:*", function(err,result) {
- if(result) {
- result.forEach(function(offer) {
- if(offer.length > 0) {
- var id = explode(":",offer);
- fakeOffers(id[2]);
- }
- });
- }
- if(err) console.log("%j",err);
- });
- // REAL OFFERS
- offers.getOffers({
- get_received_offers: 1,
- active_only: 1,
- time_historical_cutoff: Math.round(Date.now() / 1000)
- }, function(error, body) {
- if(error == null)
- {
- if(body.response.trade_offers_received) {
- body.response.trade_offers_received.forEach(function(offer) {
- if (offer.trade_offer_state == 2)
- {
- if(in_array(offer.steamid_other, admins)) {
- console.log('[ %s ] Offer from admin steamid %s accepted',logTime(),offer.steamid_other);
- offers.acceptOffer({tradeOfferId: offer.tradeofferid});
- AcceptConfirmations();
- }
- else
- {
- if(typeof arr_prof[offer.steamid_other] == 'undefined')
- {
- arr_prof_add(offer.steamid_other);
- var text_msg = "";
- var escrow_pass = 0;
- if(offer.hasOwnProperty('escrow_end_date')) {
- if(offer.escrow_end_date != 0) {
- escrow_pass = 0;
- }
- else escrow_pass = 1;
- }
- //console.log("\n%j\n",offer);
- if(offer.items_to_give == null && offer.items_to_receive != null && escrow_pass == 1)
- {
- if(typeof steamid_items[offer.steamid_other] == 'undefined' && offer.items_to_receive.length <= max_items_per_user || (steamid_items[offer.steamid_other] + offer.items_to_receive.length) <= max_items_per_user) {
- console.log("[ %s ] > Incoming tradeoffer from " + offer.steamid_other, logTime());
- var offer_seconds_passed = (Math.round(+new Date()/1000))-offer.time_updated;
- if(offer_seconds_passed>145) {
- console.log('[ %s ] > Trying to cancel obsolete offer (age is %s seconds)',logTime(),offer_seconds_passed);
- return declineoffer("too_old_offer", offer.steamid_other, offer.tradeofferid);
- }
- checkprice(offer.items_to_receive, offer.steamid_other, offer.tradeofferid);
- } else text_msg = "bot_item_limit";
- } else text_msg = "bot_tradeoffer_failed";
- if(text_msg != "")
- {
- console.log(offer.steamid_other + " Произошла ошибка - " + text_msg);
- declineoffer(text_msg, offer.steamid_other, offer.tradeofferid);
- }
- }
- }
- }
- });
- }
- }
- });
- }
- } , 2000);
- function escapeHtml(text) {
- var map = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": '''
- };
- return text.replace(/[&<>"']/g, function(m) {
- return map[m];
- });
- }
- function getDateTime() {
- var date = new Date();
- var hour = date.getHours();
- var min = date.getMinutes();
- var sec = date.getSeconds();
- var year = date.getFullYear();
- var month = date.getMonth() + 1;
- var day = date.getDate();
- hour = (hour < 10 ? "0" : "") + hour;
- min = (min < 10 ? "0" : "") + min;
- sec = (sec < 10 ? "0" : "") + sec;
- month = (month < 10 ? "0" : "") + month;
- day = (day < 10 ? "0" : "") + day;
- return day + "." + month + "." + year + " " + hour + ":" + min + ":" + sec;
- }
- function logTime() {
- var date = new Date();
- var hour = date.getHours();
- var min = date.getMinutes();
- var sec = date.getSeconds();
- var year = date.getFullYear();
- var month = date.getMonth() + 1;
- var day = date.getDate();
- hour = (hour < 10 ? "0" : "") + hour;
- min = (min < 10 ? "0" : "") + min;
- sec = (sec < 10 ? "0" : "") + sec;
- month = (month < 10 ? "0" : "") + month;
- day = (day < 10 ? "0" : "") + day;
- return hour + ":" + min + ":" + sec;
- }
- function AcceptConfirmations(){
- SteamMobileConfirmations.FetchConfirmations(function (err, confirmations){
- if (err)
- {
- console.log(err);
- return;
- }
- if(confirmations.length > 0)
- console.log('[ %s ] > Confirmations received ' + confirmations.length + ' confirmations', logTime());
- if ( ! confirmations.length)
- {
- return;
- }
- confirmations.forEach(function(item,i,arr)
- {
- SteamMobileConfirmations.AcceptConfirmation(item, function (err, result)
- {
- if (err)
- {
- console.log(err);
- return;
- }
- console.log('[ %s ] > Accept result: ' + result, logTime());
- });
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement