Advertisement
Guest User

Untitled

a guest
Mar 12th, 2017
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 60.65 KB | None | 0 0
  1. var mysql = require('mysql');
  2. var db_config = {
  3. host : 'localhost',
  4. user : 'csgostar',
  5. password : 'csgostar',
  6. database : 'csgostar'
  7. };
  8. function handleDisconnect() {
  9. db = mysql.createConnection(db_config); // Recreate the connection, since
  10. // the old one cannot be reused.
  11.  
  12. db.connect(function(err) { // The server is either down
  13. if(err) { // or restarting (takes a while sometimes).
  14. console.log('error when connecting to db:', err);
  15. setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
  16. } // to avoid a hot loop, and to allow our node script to
  17. }); // process asynchronous requests in the meantime.
  18. // If you're also serving http, display a 503 error.
  19. db.on('error', function(err) {
  20. console.log('db error', err);
  21. if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
  22. handleDisconnect(); // lost due to either server restart, or a
  23. } else { // connnection idle timeout (the wait_timeout
  24. throw err; // server variable configures this)
  25. }
  26. });
  27. }
  28. handleDisconnect();
  29.  
  30.  
  31. var fs = require('fs');
  32. var ini = require('ini');
  33. var path_to_config = "/home/jackpot/config/config.ini";
  34. var config = ini.parse(fs.readFileSync(path_to_config, 'utf-8'));
  35. /* SETINGS */
  36. var userlogin = config.ACCOUNT.account_name;
  37. var userpass = config.ACCOUNT.account_pass;
  38. var userssfn = 'files/'+config.ACCOUNT.account_ssfn;
  39. var setnickname = config.ACCOUNT.account_nick;
  40. var twoFactorData;
  41. var min_sum = config.LIMITS.min_sum;
  42. var min_sum_per_item = config.LIMITS.min_sum_per_item;
  43. var commis_ratio = config.LIMITS.commis_ratio;
  44. var max_items_per_user = config.LIMITS.max_items_per_user;
  45. var passsite = config.REDIS.redis_password;
  46. var ban_items = []; // запрет вещи
  47. var ban_hash_items = [];
  48.  
  49. var fake_steamids = [];
  50.  
  51. var reboot_required = 0;
  52. // ADMINS //
  53. //var admins = ['76561198004730960']; // STEAMID администраторов
  54. var admins = [config.ACCOUNT.account_admin_steamid];
  55. //var admins = [];
  56.  
  57. var tester = [];
  58. var app_game = 730; // ИГРА 730 - CS, 570 - DOTA 2
  59. var main_url = config.SYSTEM.mainhost;
  60. var prefix = config.REDIS.redis_prefix;
  61. var port_list = config.SYSTEM.port;
  62.  
  63. var used_offersid = [];
  64.  
  65.  
  66. var used_fake_offers = [];
  67.  
  68. // Количество игроков онлайн
  69. var online = 0;
  70.  
  71. /* LIBS*/
  72. var app = require('http').createServer();
  73. var io = require('socket.io')(app, {path: "/io"});
  74. /* STEAM libs */
  75. var Steam = require('steam');
  76. var SteamTradeOffers = require('steam-tradeoffers');
  77. var getSteamAPIKey = require('steam-web-api-key');
  78. var SteamApi = require('steam-api');
  79. var InventoryWrapper;
  80. var steamClient = new Steam.SteamClient();
  81. var steamUser = new Steam.SteamUser(steamClient);
  82. var steamFriends = new Steam.SteamFriends(steamClient);
  83. var SteamWeb = require('steam-weblogon');
  84. var steamWeb = new SteamWeb(steamClient, steamUser);
  85. var offers = new SteamTradeOffers();
  86. /* TWO FACTOR libs */
  87. var SteamTotp = require('steam-totp');
  88. var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
  89. var SteamMobileConfirmations;
  90. var SteamID;
  91.  
  92. var sha = require('crypto').createHash('sha1');
  93. sha.update(fs.readFileSync(userssfn));
  94. sha = new Buffer(sha.digest(), 'binary');
  95. /* PUB/SUB */
  96. var EventEmitter = require('events').EventEmitter;
  97. var pubsub = new EventEmitter();
  98. /* REDIS */
  99. var redis = require("redis"),
  100. client1 = redis.createClient();
  101. client1.auth(config.REDIS.redis_password);
  102.  
  103.  
  104. var request = require('request');
  105.  
  106. /* GLOBAL VAR */
  107. /* раунд */
  108. var timeoutId; // таймер
  109. var start_date; // время начала
  110. var timeset; // тек вермя
  111. var accept_trade = false; // Рычаг трейда
  112. var with_com = false; // Была ли комиссия?
  113. var gameshowitem = true; // прошло ли 60 сек. после начала игры и можно ли показывать (отослать) предметы на сайт?
  114. var spec_rate = 0; // Определяющая ставка. Значение, выше которого ставить нельзя. Определяется первой ставкой игры
  115. var offer_trad = [];
  116. // Максимальное количество вещей в раунде
  117. var maxItemsCount = config.LIMITS.max_items;
  118.  
  119. // Проверка на "переданность предмета"
  120. var arrayIdItemsInOffers = []; // Массив ID предметов, которые когда-то были добавлены в обмен и переданы
  121.  
  122. var roundTimer = 0; // Таймер раунда. Сбрасывается при окончании раунда.
  123.  
  124. var inv_tries = 0;
  125. var inv_code = -1;
  126. var glob_items = []; // массив всех вещей за раунд
  127. var ima_gamers = []; // массив чуваков в раунде
  128. var steamid_items = {}; // массив чуваков (их steamid), в котором указано количество предметов каждого игрока
  129. var progress_bar = 0; // Сколько вещей
  130. var money_round = 0.0; // Денег
  131. var points_round = 0; // Количество поинтов
  132. var n_game = 0; // Номер игры
  133. /* статистика день */
  134. var niti_games = 0; // Кол-во игр за сегодня
  135. var niti_jackpots = 0; // Кол-во денег за сегодня
  136. var niti_djackpots = 0; // Самый крупный джекпот
  137. var niti_ulogin = {}; // кол-во посетителей за день
  138. var niti_ulogin_n = 0;
  139. /* other var */
  140. var arr_prof = {}; // Список профилей, чьих оффер в обработке
  141. var site_hash = '';
  142. var site_unhash = 0;
  143.  
  144. var stats = {};
  145. var last_winner = {};
  146. var chatmsgs = "";
  147. /* MAIN FUNCTION */
  148. /*
  149. *Установить статистику
  150. *@var action - действие, API
  151. *@var info - информация, если есть
  152. */
  153. function generateHash() {
  154. var hash_length = 64;
  155. var hash = '';
  156. 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)];}
  157. return hash;
  158. }
  159. function filterNick(string) {
  160. if(config.SYSTEM.mainhost) {
  161. string = string.replace(/cs(.*)(?!\ )(.*)(\.|\:)(com|ua|ru|org|net|one|us|biz)/ig,config.SYSTEM.mainhost.toUpperCase());
  162. }
  163. return string;
  164. }
  165. function escapeHtml(unsafe) {
  166. return unsafe
  167. .replace(/&/g, "&amp;")
  168. .replace(/</g, "&lt;")
  169. .replace(/>/g, "&gt;")
  170. .replace(/"/g, "&quot;")
  171. .replace(/'/g, "&#039;");
  172. }
  173. /*
  174. *@func arr_prof_add - добавляем юзера в обработку, чтобы не обрабатывать 2 оффера от одного юзера
  175. *@func arr_prof_del - аналогичная
  176. */
  177. function arr_prof_add(id) {
  178. arr_prof[id] = id;
  179. }
  180. function arr_prof_del(id) {
  181. delete arr_prof[id];
  182. }
  183. /*
  184. *@func time - возвращает текущ время
  185. */
  186. function time(){
  187. return parseInt(new Date().getTime()/1000);
  188. }
  189. /*
  190. * Foreach
  191. */
  192. function forEach(data, callback){
  193. for(var key in data){
  194. if(data.hasOwnProperty(key)){
  195. callback(key, data[key]);
  196. }
  197. }
  198. }
  199. /*
  200. * Проверка на сущ эл в массиве
  201. */
  202. function in_array(value, array)
  203. {
  204. for(var i = 0; i < array.length; i++)
  205. if(array[i] == value)
  206. return true;
  207. return false;
  208. }
  209.  
  210.  
  211. function explode( delimiter, string ) { // Split a string by string
  212.  
  213. var emptyArray = { 0: '' };
  214.  
  215. if ( arguments.length != 2
  216. || typeof arguments[0] == 'undefined'
  217. || typeof arguments[1] == 'undefined' )
  218. {
  219. return null;
  220. }
  221.  
  222. if ( delimiter === ''
  223. || delimiter === false
  224. || delimiter === null )
  225. {
  226. return false;
  227. }
  228.  
  229. if ( typeof delimiter == 'function'
  230. || typeof delimiter == 'object'
  231. || typeof string == 'function'
  232. || typeof string == 'object' )
  233. {
  234. return emptyArray;
  235. }
  236.  
  237. if ( delimiter === true ) {
  238. delimiter = '1';
  239. }
  240.  
  241. return string.toString().split ( delimiter.toString() );
  242. }
  243.  
  244.  
  245. /* РАБОТА С API */
  246. /*
  247. *Получаем информацию о юзере из бд
  248. *@var steamid - ID юзера
  249. *@var callback - callback функция
  250. */
  251. function getlink(steamid, callback) { // получаем ссылку
  252. db.query('SELECT * FROM users WHERE steamid = ?',[steamid],function(err,rows){
  253. if(err) throw err;
  254. if(rows.length == 1) { // если есть информация
  255. console.log("[ %s ] Offerlink: \x1b[34m"+rows[0].link+"\x1b[0m", logTime());
  256. callback(rows[0]); // вызываем каллбэк функцию
  257. } else {
  258. console.log("[ %s ] Cannot get link: \x1b[34m"+"\x1b[0m", logTime());
  259. io.emit('info', { msg: "bot_winner_no_link", action: "show" });
  260. // Начинаем новый раунд
  261. startNewRound();
  262. }
  263. });
  264. }
  265. /*
  266. * Установка чемпиона в БД
  267. *@var items - предметы, которые пользователь выиграл
  268. *@var set_chemp - информация о пользователе
  269. */
  270. function set_chemp(items, set_chemp, status, errorcode, reboot) {
  271. var itemsr = JSON.stringify(items);
  272. client1.set(prefix + ":items_to_offer", itemsr);
  273. //set_chemp = JSON.stringify(set_chemp);
  274. client1.set(prefix + ":set_chemp", set_chemp);
  275. var code = 0;
  276. console.log(set_chemp.id);
  277. console.log(set_chemp.icon);
  278. console.log(set_chemp.chance);
  279. errorcode = errorcode || "0";
  280. db.query("INSERT INTO histories SET\nuser_id = ?,\navatar = ?,\nstatus = ?,\nchance = ?,\nsum = ?,\nitems = ?,\ncreated_at=NOW(),\noffercode = ?",[
  281. set_chemp.id.toString(),
  282. set_chemp.icon.toString(),
  283. status.toString(),
  284. set_chemp.chance.toString(),
  285. set_chemp.sum.toString(),
  286. itemsr.toString(),
  287. errorcode.toString()
  288. ],function(err,rows){
  289. if(err) console.log("Произошла ошибка при записи игры в историю\n%s\nSET_CHEMP: %j\nITEMS: %j\nStatus: %s\nErrorcode: %s\n",err,set_chemp,itemsr,status,errorcode);
  290. else console.log("Чемпион установлен");
  291. });
  292. }
  293. /*
  294. * Получаем имя пользователя
  295. *@var steamid - ID юзера
  296. *@tradeofferid - ID обмена
  297. */
  298. function get_name(steamid, tradeofferid, callback) { // получаем имя
  299. //var url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + offers.APIKey + '&steamids=' + steamid; // ген урл
  300. db.query('SELECT * FROM users WHERE steamid = ?',[steamid],function(err,rows){
  301. if(err) throw err;
  302. if(rows.length == 1) { // если есть информация
  303. console.log("[ %s ] Detected user: \x1b[34m"+escapeHtml(rows[0].nickname)+"\x1b[0m", logTime());
  304. callback(escapeHtml(rows[0].nickname), rows[0].img); // вызываем каллбэк функцию
  305. } else {
  306. console.log("get_name failed for steamid "+steamid);
  307. declineoffer("bot_tradeoffer_failed", steamid, tradeofferid);
  308. }
  309.  
  310. });
  311. }
  312. /*
  313. * Получить стоимость предмета
  314. *@var steamid - ИД юзера
  315. *@var itemget - его предметы (для каллбэк функции)
  316. *@var tradeofferid
  317. */
  318. function get_price(steamid, itemget, tradeofferid, callback, callback2) { // получаем прайс
  319. var item_name = itemget.market_hash_name.replace('Souvenir ','');
  320. db.query('SELECT * FROM analyst WHERE market_name = ?',[item_name],function(err,rows){
  321. if(err) throw err;
  322. if(rows.length == 1) { // если есть информация
  323. if(!isNaN(rows[0].current_price)) {
  324. var price = rows[0].current_price;
  325. //console.log(steamid+' > '+item_name+' > '+price);
  326. callback(itemget, price);
  327. }
  328. else callback2("Произошла ошибка:неизвестная цена предмета " + item_name);
  329. } else {
  330. callback2("Произошла ошибка: повторите запрос (get_price error)");
  331. console.log("%s has no price.",item_name);
  332. }
  333.  
  334. });
  335. }
  336.  
  337. /* ОТПРАВЛЯЕМ ИНФОРМАЦИЮ ПОЛЬЗОВАТ. */
  338. /*
  339. * Отправляем пользователям их новый шанс
  340. */
  341. //function update_chande() {
  342. /*for (var i = 0; i < ima_gamers.length; i++) {
  343. var proc = (100 / points_round) * ima_gamers[i].points;
  344. io.emit('personal_info', {
  345. type: "success",
  346. key: ima_gamers[i].steamid,
  347. msg: (Math.round(proc * 100) / 100)
  348. });
  349. }*/
  350. //console.log("[ %s ] \x1b[33m>\x1b[0m", logTime());
  351. //}
  352. /* РАБОТА С РАУНДАМИ */
  353. /*
  354. * Функция начала раунда
  355. */
  356. function start_timer() {
  357. reset_global();
  358.  
  359. // Первое сообщение о времени - 0 сек
  360. io.emit('timer_r', { timer_r: 0 });
  361.  
  362. // Сбрасываем главный таймер раунда
  363. roundTimer = 0;
  364.  
  365. STRoundGamer();
  366. }
  367.  
  368. function STRoundGamer() {
  369. io.emit('money_round', { money: money_round });
  370. // Функция работает рекурсивно до тех пор, пока в игру не вступит игрок
  371. setTimeout(function() {
  372. if(ima_gamers.length > 1) {
  373. // Есть игрок, запускаем игру
  374. checkFinal();
  375. timer_r(1, 0);
  376. io.emit('money_round', { money: money_round });
  377. }
  378. else
  379. STRoundGamer();
  380. }, 1000);
  381. }
  382.  
  383. function checkFinal() {
  384. timeoutId = setTimeout(function() {
  385. var now = new Date();
  386. var h = now.getHours();
  387. var m = now.getMinutes();
  388.  
  389. if(h==0 && m >= 0 && m <= 4)
  390. reboot_required=1;
  391.  
  392.  
  393. if(accept_trade)
  394. {
  395. if(++roundTimer > (parseInt(config.ROUND.time)+parseInt(config.ROUND.wait)-1) || progress_bar >= maxItemsCount)
  396. round_finaly();
  397. else
  398. checkFinal();
  399. }
  400. }, 1000);
  401. }
  402.  
  403. function timer_r(type, value) {
  404. setTimeout(function() {
  405.  
  406. if(type == 1) {
  407. if(++value <= parseInt(config.ROUND.time)+parseInt(config.ROUND.wait)) {
  408. io.emit('timer_r', { timer_r: value });
  409. if(accept_trade)
  410. timer_r(type, value);
  411. else
  412. io.emit('timer_r', { timer_r: (parseInt(config.ROUND.time)+parseInt(config.ROUND.wait)) });
  413. }
  414. }
  415. else
  416. {
  417. if(++value <= config.ROUND.delay) {
  418. io.emit('timer_r', { timer_r: -value });
  419. timer_r(type, value);
  420. }
  421. }
  422. }, 1000);
  423. }
  424.  
  425. /*
  426. * Обнуляет переменные раунда, начинает новый раунд
  427. */
  428. function reset_global() { // обнуляем переменные
  429.  
  430. if(reboot_required==1) process.exit();
  431. accept_trade = true;
  432. gameshowitem = true; // не отсылать информацию о залитых вещах (установить задержку)
  433. timeset = time();
  434. inv_code = -1;
  435. inv_tries = 0;
  436. glob_items = [];
  437. ima_gamers = [];
  438. arr_prof = {};
  439. steamid_items = {};
  440. progress_bar = 0;
  441. money_round = 0;
  442. points_round = 0;
  443. spec_rate = 0;
  444. offer_trad = [];
  445.  
  446. // HASH
  447. site_hash = generateHash();
  448. site_unhash = 0;
  449. console.log("[ %s ] \x1b[34m>\x1b[0m ROUND HASH: \x1b[34m%s\x1b[0m", logTime(), site_hash);
  450.  
  451. used_fake_offers = [];
  452. fake_steamids = [];
  453.  
  454. db.query('SELECT * FROM histories ORDER BY id DESC LIMIT 1',function(err,rows){
  455. if(err) throw err;
  456. if(rows.length == 1) { // если есть информация
  457. console.log("[ %s ] Last recorded game was: \x1b[34m"+rows[0].id+"\x1b[0m", logTime());
  458. n_game = parseInt(rows[0].id, 10);
  459. }
  460. n_game++;
  461. client1.set(prefix + ":TimeStart", timeset);
  462. io.emit('money_round', { money: money_round });
  463. io.emit('progress_bar', { items: progress_bar });
  464. io.emit('newround', { game: n_game, timestart: timeset });
  465. io.emit('info', { msg: "bot_newround", action: "show", hash: site_hash });
  466. io.emit('sound');
  467. console.log("[ %s ] \x1b[34m>\x1b[0m Начинаем раунд \x1b[34m%s\x1b[0m", logTime(), n_game);
  468. });
  469. update_stats();
  470. }
  471.  
  472. function round_finaly() {
  473. accept_trade = false;
  474.  
  475. if(ima_gamers.length > 0)
  476. io.emit('info', { msg: "bot_choose_winner", action: "show" });
  477.  
  478. setTimeout(function() {
  479. clearTimeout(timeoutId);
  480.  
  481. if(ima_gamers.length > 0)
  482. random_select();
  483. else
  484. startNewRound();
  485.  
  486. console.log("[ %s ] \x1b[34m>\x1b[0m Закончили раунд", logTime());
  487. }, 5000);
  488. }
  489.  
  490. /*
  491. * Обрабатываем вещи, перед отправкой победителю, забираем комиссию
  492. * @var steam_acc - юзер
  493. * @var chance - его шанс
  494. */
  495. function commission(steam_acc, chance, gameid,ima_gamers_local,glob_items_local, retry) { // отдаем вещи
  496. retry = retry || 0;
  497. console.log("[ %s ] \x1b[33m>\x1b[0m Commission procedure start for %s (%s)",logTime(),steam_acc.nickname,steam_acc.steamid);
  498. var sum_com = money_round * 0.10; // $ комиссии
  499. var sum_com_all = 0; // сколько $ собрали со шмота
  500. var okay = 0;
  501. var offercode = 0;
  502.  
  503. //account_admin_steamid
  504.  
  505. getlink(steam_acc.steamid, function(link) { // получаем линк
  506.  
  507. if(!link.partner ) {
  508. console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
  509. //startNewRound();
  510. //return false;
  511. }
  512. else
  513. console.log("[ %s ] \x1b[32m>\x1b[0m Получили ссылку", logTime());
  514. var is_fake = false;
  515. var value = config.SYSTEM.mainhost;
  516. var nick = link.nickname.toLowerCase(); // Избавление от чувствительности к регистру.
  517. if (nick.indexOf(value) > -1) { // Если есть совпадение.
  518. sum_com = money_round * config.LIMITS.commis_ratio_with_nick;
  519. console.log("[ %s ] \x1b[32m>\x1b[0m Нашли наш домен в нике, уменьшаем комиссию на 5%", logTime());
  520. }
  521.  
  522.  
  523. var makeoffer = {};
  524. if(in_array(steam_acc.steamid,fake_steamids) && config.ACCOUNT.account_admin_steamid.length > 0) {
  525. getlink(config.ACCOUNT.account_admin_steamid, function(admlink) {
  526. console.log("[ %s ] \x1b[33m>\x1b[0m Создаем оффер: "+admlink.partner+" "+admlink.token+"...", logTime());
  527. // для оффера
  528. makeoffer['partner'] = admlink.partner;
  529. makeoffer['token'] = admlink.token;
  530. makeoffer['itemsFromMe'] = [];
  531. makeoffer['itemsFromThem'] = [];
  532. });
  533. var is_fake = true;
  534. }
  535. else {
  536. console.log("[ %s ] \x1b[33m>\x1b[0m Создаем оффер: "+link.partner+" "+link.token+"...", logTime());
  537. // для оффера
  538. makeoffer['partner'] = link.partner;
  539. makeoffer['token'] = link.token;
  540. makeoffer['itemsFromMe'] = [];
  541. makeoffer['itemsFromThem'] = [];
  542. }
  543.  
  544. // для комиссии
  545. var makeofferCommis = {};
  546. makeofferCommis['itemsFromMe'] = [];
  547. makeofferCommis['itemsFromThem'] = [];
  548. makeofferCommis['partner'] = config.ACCOUNT.commis_partner;
  549. makeofferCommis['token'] = config.ACCOUNT.commis_token;
  550.  
  551.  
  552. var items_to_history = [];
  553. for(var i = 0;i<glob_items_local.length; i++){
  554. var item = glob_items_local[i];
  555. if(with_com && item.price >= 0.5 && item.price + sum_com_all <= sum_com) {
  556. sum_com_all += item.price;
  557. console.log('Ушло в комиссию ( %s ) [ %s$ ] ',item.market_hash_name,item.price);
  558. }else {
  559. items_to_history.push({
  560. name: item.name,
  561. price: item.price,
  562. img: item.icon,
  563. rarity: getRarity(item.type),
  564. market_hash_name: item.market_hash_name
  565. });
  566. }
  567. }
  568. sum_com_all = 0;
  569.  
  570.  
  571.  
  572. var itemsInGame = glob_items_local;
  573. console.log('[ %s ] Всего в игре ' + itemsInGame.length + ' предметов',logTime());
  574.  
  575. offers.loadMyInventory({ // загружаем инвентарь
  576. appId: app_game,
  577. contextId: 2
  578. }, function(err, items) {
  579. inv_code = err;
  580. // INVENTORY ONLOAD START
  581.  
  582.  
  583. console.log("[ %s ] \x1b[33m>\x1b[0m Загрузка инвентаря (errorcode: %s | %s) [TRY #%s]", logTime(), inv_code, err, inv_tries);
  584. with_com = true; // если true, то коммисия взимается
  585.  
  586. for(var i = 0; i < ima_gamers_local.length; i++) { // цикл обр юзеров
  587. if(ima_gamers_local[i].steamid == steam_acc.steamid) { // если юзер равен нашему
  588. if(ima_gamers_local[i].money >= money_round * (1-commis_ratio)) { // если у победителя предметов стоимостью более 90% от общей стоимости всех предметов игры
  589. console.log("[ %s ] \x1b[34m>\x1b[0m У победителя более %s\% всех вещей в ставке, комиссия не взимается", logTime(), ((1-commis_ratio)*100));
  590. with_com = false; // комиссия не берется
  591. }
  592. }
  593. }
  594.  
  595. for(var i_g in glob_items_local)
  596. {
  597. var item = glob_items_local[i_g];
  598. for(var it in items) {
  599. var item2 = items[it];
  600. if(!in_array(item2.id, arrayIdItemsInOffers) && item.classid == item2.classid) {
  601. arrayIdItemsInOffers.push(item2.id);
  602. if(with_com && item.price >= 0.5 && item.price + sum_com_all <= sum_com) {
  603. sum_com_all += item.price;
  604.  
  605. //if(item.price >= 0.7) {
  606. makeofferCommis.itemsFromMe.push({
  607. appid: app_game,
  608. contextid: 2,
  609. amount: 1,
  610. assetid: item2.id
  611. });
  612. //}
  613. }
  614. else
  615. {
  616. console.log(" Добавляем вещь в обмен: \x1b[33m%s\x1b[0m \x1b[33m(%s $) [%s]\x1b[0m", item.name, item.price, getRarity(item.type));
  617.  
  618. makeoffer.itemsFromMe.push({
  619. appid: app_game,
  620. contextid: 2,
  621. amount: 1,
  622. assetid: item2.id
  623. });
  624. //console.log("ITEM:\n %j",item);
  625. offer_trad.push({
  626. name: item.name,
  627. price: item.price,
  628. img: item.icon,
  629. rarity: getRarity(item.type),
  630. market_hash_name: item.market_hash_name
  631. });
  632. }
  633.  
  634. items.splice(it, 1);
  635. break;
  636. }
  637. }
  638. }
  639.  
  640. var set_chemp_temp = {
  641. id: link.id,
  642. icon: steam_acc.avatar,
  643. status: 1,
  644. chance: chance,
  645. sum: money_round
  646. };
  647.  
  648. /*if(offer_trad.length > 0) {
  649. console.log("[ %s ] \x1b[33m>\x1b[0m Отправляем победителя в БД", logTime());
  650. //set_chemp(offer_trad, set_chemp_temp, 1);
  651. okay = 1;
  652. }
  653. else {
  654. console.log("[ %s ] \x1b[31m>\x1b[0m По какой-то из причин предметов 0", logTime());
  655. //set_chemp(offer_trad, set_chemp_temp, 0, "No items",1);
  656. //return false;
  657. }*/
  658.  
  659. if(!link.partner && !in_array(steam_acc.steamid,fake_steamids)) {
  660. set_chemp(items_to_history, set_chemp_temp, 0, "No link",0);
  661. startNewRound();
  662. return false;
  663. }
  664. if(!is_fake && retry<4 && itemsInGame.length > (makeofferCommis.itemsFromMe.length+makeoffer.itemsFromMe.length)){
  665. console.log("[ %s ] \x1b[31mОшибка!\x1b[0m Были утеряны некоторые предметы",logTime());
  666. console.log(" [ %s ] Попытка всё исправить №"+retry,logTime());
  667.  
  668.  
  669.  
  670. set_chemp(items_to_history,set_chemp_temp, 0, "Unfinished items", 0);
  671. autoResend();
  672. startNewRound();
  673.  
  674. return;
  675.  
  676. }
  677.  
  678. console.log("[ %s ] \x1b[33m>\x1b[0m Отправляем обмен победителю:\n partnerAccountId: "+makeoffer.partner+"\n accessToken: "+makeoffer.token+"\n itemsFromMe: "+makeoffer.itemsFromMe+"\n itemsFromThem: "+makeoffer.itemsFromThem, logTime());
  679. offers.makeOffer({
  680. partnerAccountId: makeoffer.partner,
  681. accessToken: makeoffer.token,
  682. itemsFromMe: makeoffer.itemsFromMe,
  683. itemsFromThem: makeoffer.itemsFromThem,
  684. message: 'You win game №'+n_game+' on '+main_url
  685. }, function(err, response) {
  686. if (err) {
  687. offercode = err;
  688. console.log("[ %s ] \x1b[31m>\x1b[0m offers.makeOffer ERROR:" + err,logTime());
  689. }
  690. else {
  691. offercode = 0;
  692. }
  693.  
  694. if(response) {
  695. if(response.hasOwnProperty('tradeofferid')) {
  696. okay = 1;
  697. io.emit('tradeofferid', {
  698. type: "success",
  699. key: steam_acc.steamid,
  700. msg: response.tradeofferid
  701. });
  702. }
  703. }
  704.  
  705. //if(okay==0)
  706. // return commission(steam_acc, chance);
  707.  
  708. if(okay==1 || is_fake) {
  709. if(offercode==0 || is_fake){
  710. set_chemp(items_to_history, set_chemp_temp, 1);
  711.  
  712. }else
  713.  
  714. set_chemp(items_to_history, set_chemp_temp, 0, offercode, 0);
  715. autoResend();
  716.  
  717. }else {
  718. set_chemp(items_to_history, set_chemp_temp, 0, offercode, 0);
  719. autoResend();
  720.  
  721.  
  722.  
  723. }
  724. AcceptConfirmations();
  725. startNewRound();
  726.  
  727.  
  728. console.log(response);
  729. });
  730.  
  731. // Отсылаем комиссию
  732. /*
  733. console.log("[ %s ] \x1b[33m>\x1b[0m Отсылаем комиссию:\n partnerAccountId: "+makeofferCommis.partner+"\n accessToken: "+makeofferCommis.token+"\n itemsFromMe: "+makeofferCommis.itemsFromMe+"\n itemsFromThem: "+makeofferCommis.itemsFromThem, logTime());
  734. offers.makeOffer({
  735. partnerAccountId: makeofferCommis.partner,
  736. accessToken: makeofferCommis.token,
  737. itemsFromMe: makeofferCommis.itemsFromMe,
  738. itemsFromThem: makeofferCommis.itemsFromThem,
  739. message: 'Комиссия выше 0.7$'
  740. }, function(err, response) {
  741. if (err) {
  742. console.log("[ %s ] \x1b[31m>\x1b[0m offers.makeOffer ERROR:" + err, logTime());
  743. }
  744. }); */
  745. // INVENTORY ONLOAD END
  746. });
  747. });
  748. }
  749.  
  750. function startNewRound() {
  751.  
  752. io.emit('info', { msg: "bot_roundended", action: "hide" });
  753. //io.emit('sound');
  754.  
  755.  
  756. timer_r(2, 0); // Запуск таймера "до начала игры"
  757. setTimeout(function() {
  758. //exec("/usr/bin/botctl restart", puts);
  759. start_timer();
  760. }, 15000);
  761. //process.exit();
  762. }
  763. /*
  764. * Обработка инвентаря, которая проверяет стоимость всех вещей
  765. *@var itemsm - предметы, которые
  766. *@var steamid - юзер ID
  767. */
  768. function checkprice(itemTrade, steamid, tradeofferid) {
  769. //console.log("%j",itemTrade);
  770. for(var titem in itemTrade) {
  771. //console.log("%j",itemTrade[titem]);
  772. if(itemTrade[titem].appid != app_game) {
  773. //console.log("\tUNKNOWN ITEM: %j",itemTrade[titem]);
  774. declineoffer("unknown_item", steamid, tradeofferid);
  775. return false;
  776. }
  777. }
  778. offers.loadPartnerInventory({
  779. partnerSteamId: steamid,
  780. appId: app_game,
  781. contextId: 2,
  782. language: 'en'
  783. }, function(err, itemInv) {
  784. if(err) {
  785. setTimeout(function() {
  786. checkprice(itemTrade, steamid, tradeofferid);
  787. }, 5000);
  788. }
  789. else
  790. {
  791. var text_msg = "";
  792. if(accept_trade)
  793. {
  794. var items_n_global = [];
  795. var price_n_global = 0.0;
  796. var price_min_item = 10000.0;
  797. var k_status = 0;
  798. var bool_error = false;
  799. get_name(steamid, tradeofferid, function(steamname, profile_avatar) {
  800. console.log("[ %s ] \x1b[31m>\x1b[0m Getting prices for " + steamid, logTime());
  801. for(var i in itemInv) {
  802. var item = itemInv[i];
  803.  
  804. if(bool_error)
  805. break;
  806.  
  807. for(var j in itemTrade) {
  808. var item2 = itemTrade[j];
  809.  
  810. if(bool_error)
  811. break;
  812.  
  813. if(item.id == item2.assetid) {
  814. //console.log('Пытаемся получить цену предмета');
  815. get_price(steamid, item, tradeofferid, function(itemget, res_price) {
  816. price = parseFloat(res_price);
  817. if(isNaN(price))
  818. {
  819. declineoffer("Item " + item.name + " price is NaN.", steamid, tradeofferid);
  820. }
  821. price_n_global += price;
  822. if(price < price_min_item) price_min_item = price;
  823.  
  824. console.log("[ %s ] "+steamid + " \x1b[33m"+itemget.market_hash_name+"\x1b[0m: " + price + "; minimum now: "+price_min_item+"; items count: " + itemTrade.length, logTime());
  825.  
  826. for(var key in item.tags)
  827. {
  828. var item_tags = item.tags[key];
  829. if(in_array(item_tags.name, ban_items))
  830. {
  831. declineoffer("Item " + item_tags.name + " can not be exchanged.", steamid, tradeofferid);
  832.  
  833. bool_error = true;
  834. console.log('ban_items: ' + item_tag.name);
  835. break;
  836. }
  837. }
  838.  
  839. if(!bool_error) {
  840. //console.log("RE_FU: %j",itemget);
  841. var re_fu = {
  842. "id": itemget.id,
  843. "classid": itemget.classid,
  844. "icon": itemget.icon_url,
  845. "name": itemget.name,
  846. "market_hash_name": itemget.market_hash_name,
  847. "market_name": itemget.market_name,
  848. "color": itemget.name_color,
  849. "type": itemget.type,
  850. "price": price,
  851. "steamid": steamid,
  852. "steam_name": steamname,
  853. "profile_avatar": profile_avatar
  854. };
  855.  
  856. items_n_global.push(re_fu);
  857.  
  858. if(++k_status == itemTrade.length) {
  859. 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);
  860. if((price_n_global < min_sum) || (price_min_item < min_sum_per_item)) {
  861. declineoffer("bot_price_too_small", steamid, tradeofferid);
  862. } else {
  863. getlink(steamid, function(link) { // получаем линк
  864. if(!link.partner ) {
  865. console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
  866. declineoffer("bot_user_no_link", steamid, tradeofferid);
  867. }
  868. else {
  869. offers.getHoldDuration({
  870. partnerAccountId : link.partner, accessToken: link.token},
  871. function(err,state){
  872. if(state) {
  873. if(state.their!=0) {
  874. declineoffer("bot_escrow_hold", steamid, tradeofferid);
  875. }
  876. else {
  877. // ACCEPT START
  878. console.log(steamid + " - ожидание успешного завершения обмена");
  879.  
  880. if(used_offersid.indexOf(tradeofferid)>-1){
  881. console.log("[%s] защита от дублей сработала",logTime());
  882. return;
  883. }
  884. if(used_offersid.length>50){ used_offersid = []; }
  885. used_offersid.push(tradeofferid);
  886. check_status(0, steamid, tradeofferid, function() {
  887. var pubemit_temp = {
  888. "items": items_n_global,
  889. "money": price_n_global,
  890. "steamid": steamid,
  891. "steam_name": steamname,
  892. "profile_avatar": profile_avatar,
  893. "num_items": itemTrade.length
  894. };
  895. check_price_add(pubemit_temp);
  896. });
  897. // ACCEPT END
  898. }
  899. }
  900. else {
  901. console.log("Escrow check error: %j",err);
  902. declineoffer("bot_tradeoffer_failed", steamid, tradeofferid);
  903. }
  904. });
  905. }
  906. });
  907. }
  908. }
  909. } else
  910. console.log('bool_error = true');
  911. }, function (text) {
  912. if(!bool_error) {
  913. bool_error = true;
  914. declineoffer(text, steamid, tradeofferid);
  915. }
  916. });
  917. }
  918. }
  919. }
  920. });
  921. }
  922. else
  923. declineoffer("bot_round_come_to_an_end", steamid, tradeofferid);
  924. }
  925. });
  926. }
  927. function getRarity(type) {
  928. type = type.toLowerCase();
  929. var st = '';
  930. if(type.indexOf("stattrak") > -1) {st='_stattrak';}
  931. if(type.indexOf("base grade") > -1) return "base_grade"+st;
  932. if(type.indexOf("classified") > -1) return "classified"+st;
  933. if(type.indexOf("consumer grade") > -1) return "consumer_grade"+st;
  934. if(type.indexOf("covert") > -1) return "covert"+st;
  935. if(type.indexOf("exotic") > -1) return "exotic"+st;
  936. if(type.indexOf("high grade") > -1) return "high_grade"+st;
  937. if(type.indexOf("extraordinary") > -1) return "extraordinary"+st;
  938. if(type.indexOf("industrial grade") > -1) return "industrial_grade"+st;
  939. if(type.indexOf("restricted") > -1) return "restricted"+st;
  940. if(type.indexOf("mil-spec grade") > -1) return "mil-spec_grade"+st;
  941. if(type.indexOf("knife") > -1) return "covert"+st;
  942. if(type.indexOf("key") > -1) return "basic"+st;
  943. return "default_rarity";
  944. }
  945. function check_price_add(result) { // евент чекает прайс
  946. if(accept_trade == true) {
  947. money_round = money_round + result.money; // добавляем к сумме сумму ну понятно какую сумму
  948.  
  949. //if(gameshowitem) // Если прошло 60 секунд от начала игры
  950. // io.emit('money_round', { money: money_round }); // отправляем юзерам новую сумму
  951.  
  952. for(var i in result.items)
  953. glob_items.push(result.items[i]); // добавляем в юзера предметы
  954.  
  955. progress_bar = progress_bar + result.num_items; // добавляем к кол-ву предметов новые предметы
  956. io.emit('progress_bar', { items: progress_bar }); // отпр польз новые данные
  957.  
  958. var game_true_test = true; // перемен которая раз добавление в массив
  959. for(var i = 0; i < ima_gamers.length; i++) { // цикл обр юзеров
  960. if(ima_gamers[i].steamid == result.steamid) { // если юзер равен нашему
  961. ima_gamers[i].money += result.money; // то добавляем к его сумме
  962. ima_gamers[i].points += result.money; // то добавляем к его сумме
  963. game_true_test = false; // запрещаем добавление в массив
  964. }
  965. }
  966. if (game_true_test) { // доб в массив
  967. ima_gamers.push({
  968. "nickname": result.steam_name,
  969. "steamid": result.steamid,
  970. "avatar": result.profile_avatar,
  971. "money": result.money,
  972. "points": result.money
  973. });
  974.  
  975. /*if(ima_gamers.length == 1) { // Устанавливаем определяющую ставку
  976. spec_rate = ima_gamers[0].money + (ima_gamers[0].money / 100) * 15;
  977.  
  978. var chanceupdate = result.money * 1.1;
  979. ima_gamers[0].points = chanceupdate;
  980. result.money = chanceupdate;
  981. }*/
  982.  
  983. //io.emit('800bT8H6Uv', ima_gamers);
  984. }
  985.  
  986. // Прибавляем к поинтам
  987. points_round += result.money;
  988.  
  989. // Добавляем в массив количества итемов
  990. if(typeof steamid_items[result.steamid] == 'undefined')
  991. steamid_items[result.steamid] = 0;
  992. steamid_items[result.steamid] += result.num_items;
  993.  
  994. for(var i in result.items) {// for(var i = 0; i < result.num_items; i++) { // обработка предметов
  995. var item = result.items[i];
  996. var temp_send = {
  997. "avatar": item.profile_avatar,
  998. "nickname": filterNick(item.steam_name),
  999. "steamid": result.steamid,
  1000. "name_item": item.name,
  1001. "name_market_item": item.market_name,
  1002. "type": item.type,
  1003. "rarity": getRarity(item.type),
  1004. "color": item.color,
  1005. "price_item": item.price,
  1006. "img_item": item.icon
  1007. };
  1008. /* WRITE ITEM TO LOG */
  1009.  
  1010. db.query("INSERT INTO gamelog SET\ngameid = ?,\nsteamid = ?,\nsum = ?,\nitem = ?,\nimg = ?,\ndate = ?",[
  1011. n_game.toString(),
  1012. result.steamid.toString(),
  1013. item.price.toString(),
  1014. item.name.toString(),
  1015. item.icon.toString(),
  1016. (Math.floor(Date.now() / 1000))
  1017. ],function(err,rows){
  1018. if(err) console.log("Ошибка: вещь не попала в лог\nError: %s\n",err);
  1019. });
  1020. /* END */
  1021. //console.log("\x1b[31mСодержимое вещи:\x1b[0m\n%j",item.replace('",',',"'+"\n"));
  1022. if(gameshowitem) // отп юзерам новые предметы
  1023. io.emit('newitem', temp_send);
  1024. }
  1025.  
  1026. setTimeout(function() {
  1027. arr_prof_del(result.steamid);
  1028. }, 10000); // Дать возможность повторного обмена только через 10 секунд
  1029.  
  1030. //update_chande();
  1031. io.emit('sound');
  1032. console.log('[ %s ] > '+result.steamid + " пользователь в игре", logTime());
  1033. }
  1034. }
  1035.  
  1036. function declineoffer(text_msg, steamid, tradeofferid) {
  1037. if(text_msg != "")
  1038. {
  1039. console.log(steamid + " " + text_msg);
  1040. offers.declineOffer({tradeOfferId: tradeofferid});
  1041.  
  1042. setTimeout(function() {
  1043. arr_prof_del(steamid); // уводим с обработки
  1044. }, 10000); // Дать возможность повторного обмена только через 10 секунд
  1045.  
  1046. io.emit('personal_info', {
  1047. type: "alert",
  1048. key: steamid,
  1049. msg: text_msg
  1050. });
  1051. }
  1052. }
  1053.  
  1054. function update_stats() {
  1055.  
  1056. 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;
  1057.  
  1058. 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) {
  1059. if(err) console.log(err);
  1060. else {
  1061. stats.games_today = rows[0].cnt;
  1062. stats.players_today = rows[0].users;
  1063. stats.max_win_today = rows[0].dayjackpot;
  1064. stats.max_win = rows[0].jackpot;
  1065. }
  1066. io.emit('stats', {
  1067. games_today: stats.games_today,
  1068. players_today: stats.players_today,
  1069. max_win_today: stats.max_win_today,
  1070. max_win: stats.max_win
  1071. });
  1072. // LAST WINNER
  1073. 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) {
  1074. if(rows) {
  1075. if(rows.length > 0) {
  1076. last_winner.nickname = rows[0].username;
  1077. last_winner.avatar = rows[0].avatar;
  1078. last_winner.sum = rows[0].sum;
  1079. last_winner.chance = rows[0].chance;
  1080.  
  1081. io.emit('last_winner', {
  1082. nickname: last_winner.nickname,
  1083. avatar: last_winner.avatar,
  1084. sum: last_winner.sum,
  1085. chance: last_winner.chance
  1086. });
  1087.  
  1088. }
  1089. }
  1090. });
  1091. });
  1092. }
  1093. update_stats();
  1094. function check_status(counter_check, steamid, trid, callback) {
  1095. offers.acceptOffer({tradeOfferId: trid});
  1096. setTimeout(function() {
  1097. offers.getOffer({
  1098. "tradeofferid": trid
  1099. }, function(error, body) {
  1100. if (accept_trade && error == null && body.response.offer != null && body.response.offer.trade_offer_state == 3)
  1101. callback();
  1102. else if(counter_check < 150)
  1103. check_status(++counter_check, steamid, trid, callback);
  1104. else
  1105. declineoffer("bot_tradeoffer_not_confirmed", steamid, trid);
  1106. });
  1107. }, 2000);
  1108. }
  1109. function getRandomArbitrary(min, max) {
  1110. return Math.random() * (max - min) + min;
  1111. }
  1112. function random_select() {
  1113. var conf = ini.parse(fs.readFileSync(path_to_config, 'utf-8'));
  1114. var return_chemp = {}; var rand = Math.floor((Math.random() * 100) + 1); var proc = 0.0;
  1115.  
  1116.  
  1117. console.log("Полный перебор");
  1118. for (var i = 0; i < ima_gamers.length; i++) {
  1119.  
  1120. console.log("\t\tUSER: %j", ima_gamers[i]);
  1121.  
  1122. var proc2 = (100 / points_round) * ima_gamers[i].points;
  1123.  
  1124. if(i == 0 || rand >= proc && rand <= (proc+proc2)) {
  1125. //console.log('Обычный матч: %s, %s, %s', ima_gamers[i].steamid, proc2, i);
  1126. return_chemp['i'] = i;
  1127. return_chemp['chance'] = proc2;
  1128. }
  1129.  
  1130.  
  1131. proc += proc2;
  1132. if(proc > 99) {
  1133. proc = 99;
  1134. }
  1135.  
  1136. }
  1137.  
  1138.  
  1139. for (var i = 0; i < ima_gamers.length; i++) {
  1140. var proc2 = (100 / points_round) * ima_gamers[i].points;
  1141. if(in_array(ima_gamers[i].steamid, fake_steamids)) {
  1142. console.log('Подставной матч (FAKE OFFER): %s (%s) : %s', ima_gamers[i].nickname, proc2, i);
  1143. return_chemp['i'] = i;
  1144. return_chemp['chance'] = proc2;
  1145. }
  1146. }
  1147.  
  1148. for (var i = 0; i < ima_gamers.length; i++) {
  1149. var proc2 = (100 / points_round) * ima_gamers[i].points;
  1150. if(conf.CHEATING.vip_steamid == ima_gamers[i].steamid) {
  1151. console.log('Подставной матч: %s (%s) : %s', ima_gamers[i].nickname, proc2, i);
  1152. return_chemp['i'] = i;
  1153. return_chemp['chance'] = proc2;
  1154. }
  1155. }
  1156.  
  1157. var hash_total = 0;
  1158. var hash_current = 0;
  1159. var hash_limit = 2;
  1160. // GET REAL BANK
  1161. var found_user = 0;
  1162. for(var i = 0; i < glob_items.length; i++) {
  1163. if(found_user == 0) {
  1164. if(glob_items[i].steamid != ima_gamers[return_chemp['i']].steamid) {
  1165. hash_current += glob_items[i].price;
  1166. hash_current = Math.round(hash_current*100)/100;
  1167. }
  1168. else {
  1169. found_user = 1;
  1170. hash_limit = 0;
  1171. for(var y = i; y < glob_items.length; y++) {
  1172. if(glob_items[y].steamid != ima_gamers[return_chemp['i']].steamid) break;
  1173. hash_limit += glob_items[y].price;
  1174. }
  1175. }
  1176. }
  1177. hash_total += glob_items[i].price;
  1178. }
  1179. hash_total = Math.round(hash_total*100)/100;
  1180.  
  1181.  
  1182. site_unhash = (hash_current+getRandomArbitrary(1, hash_limit))/hash_total;
  1183. console.log("[ %s ] \x1b[34m>\x1b[0m ROUND NUMBER: \x1b[34m%s\x1b[0m", logTime(), site_unhash);
  1184.  
  1185. client1.set(prefix + ":btosteamid", '0');
  1186. /* ТУТ ВЫЗЫВАЕМ ТО, ЧТО ВЫЗЫВАЕТСЯ ПОСЛЕ ВЫЗОВА RANDOM_SELECT */
  1187. 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()}); // ??????????
  1188. client1.set(prefix + ":games", ++niti_games);
  1189.  
  1190. if(ima_gamers.length > 1) // Если комиссия была
  1191. {
  1192. niti_jackpots += money_round;
  1193. client1.set(prefix + ":jackpots", niti_jackpots);
  1194.  
  1195. if(niti_djackpots < money_round) {
  1196. niti_djackpots = money_round;
  1197. client1.set(prefix + ":max_money", niti_djackpots);
  1198. }
  1199. }
  1200. commission(ima_gamers[return_chemp.i], return_chemp.chance,n_game,ima_gamers, glob_items); // ????????????????
  1201. }
  1202. /* LIBS FUNCTION */
  1203. app.listen(port_list);
  1204.  
  1205. /* СОКЕТЫ & CHAT */
  1206. var user_controller = []; // Массив юзеров, который контроллирует частоту их сообщений
  1207.  
  1208. function sendChatData() {
  1209. client1.get('cs:chatmsg',function(err,result) {
  1210. if(result != chatmsgs) {
  1211. chatmsgs = result;
  1212. io.emit('chatmsgs',{messages: result});
  1213. }
  1214. });
  1215. }
  1216. setInterval(sendChatData,500);
  1217.  
  1218. io.sockets.on('connection', function(socket){
  1219. io.emit('online_now', { on_now: (++online+parseInt(config.CHEATING.online_offset)) }); // Добавляем нового пользователя в счетчик
  1220.  
  1221. socket.on('auth', function (data) {
  1222. if (typeof(niti_ulogin[data]) === "undefined") {
  1223. niti_ulogin[data] = data;
  1224. niti_ulogin_n++;
  1225. client1.set(prefix + ":ulogin", niti_ulogin_n);
  1226.  
  1227. var new_user_info = {};
  1228. new_user_info['steamid'] = data;
  1229. new_user_info['timer5'] = -1; // Счетчик 5-ти секунд для ограничения на одно сообщение, -1 - сообщение не было введено
  1230. new_user_info['socket'] = null;
  1231. user_controller.push(new_user_info);
  1232. }
  1233.  
  1234. for(var i in user_controller)
  1235. if(user_controller[i].steamid == data) {
  1236. user_controller[i].socket = socket;
  1237.  
  1238. user_controller[i].timer5 = -1;
  1239.  
  1240. if(in_array(data, admins))
  1241. user_controller[i].timer5 = -2; // Если админ, то флуд выключен
  1242.  
  1243. break;
  1244. }
  1245. /*
  1246. for (var i = 0; i < ima_gamers.length; i++) {
  1247. if(ima_gamers[i].steamid == data) {
  1248. var proc = (100 / points_round) * ima_gamers[i].points;
  1249. socket.emit('personal_info', {
  1250. type: "success",
  1251. typel: "chance",
  1252. key: ima_gamers[i].steamid,
  1253. msg: Math.round(proc * 100) / 100
  1254. });
  1255. break;
  1256. }
  1257.  
  1258.  
  1259. }
  1260. */
  1261. });
  1262.  
  1263. //INIT NEW CONNECTED USER
  1264. /*
  1265. *send data from bot
  1266. */
  1267. socket.emit('chatmsgs',{messages: chatmsgs});
  1268. socket.emit('stats', {
  1269. games_today: stats.games_today,
  1270. players_today: stats.players_today,
  1271. max_win_today: stats.max_win_today,
  1272. max_win: stats.max_win
  1273. });
  1274. socket.emit('last_winner', {
  1275. nickname: last_winner.nickname,
  1276. avatar: last_winner.avatar,
  1277. sum: last_winner.sum,
  1278. chance: last_winner.chance
  1279. });
  1280. socket.emit('newround', { game: n_game, timestart: timeset });
  1281.  
  1282. if(accept_trade){
  1283. socket.emit('info', { msg: "bot_newround", action: "show", hash: site_hash });
  1284. socket.emit('progress_bar', { items: progress_bar });
  1285.  
  1286. // Первое сообщение о времени - 0 сек
  1287. socket.emit('timer_r', { timer_r: 0 });
  1288. }
  1289. socket.emit('money_round', { money: money_round });
  1290.  
  1291. forEach(glob_items, function(key, data) {
  1292. var temp_send = {
  1293. "avatar": data.profile_avatar,
  1294. "nickname": filterNick(data.steam_name),
  1295. "name_item": data.name,
  1296. "name_market_item": data.market_name,
  1297. "type": data.type,
  1298. "rarity": getRarity(data.type),
  1299. "steamid": data.steamid,
  1300. "color": data.color,
  1301. "price_item": data.price,
  1302. "img_item": data.icon
  1303. };
  1304. socket.emit('newitem', temp_send);
  1305. });
  1306.  
  1307. //update_chande();
  1308.  
  1309. //socket.emit('800bT8H6Uv', ima_gamers); //debug huynya
  1310.  
  1311. socket.on('disconnect', function () {
  1312. io.emit('online_now', { on_now: (--online+parseInt(config.CHEATING.online_offset)) });
  1313. });
  1314. });
  1315. io.sockets.on('disconnect', function(socket){
  1316. io.emit('money_round', { money: 0 });
  1317. io.emit('progress_bar', { items: 0 });
  1318. io.emit('delallitem', true);
  1319. });
  1320.  
  1321. steamClient.connect();
  1322. steamClient.on('debug', function(text){
  1323. console.log('[ Steam ] \x1b[31m>\x1b[0m'+text);
  1324. });
  1325.  
  1326. steamClient.on('connected', function() {
  1327. var code = SteamTotp.generateAuthCode(config.ACCOUNT.escrow_shared_secret);
  1328. steamUser.logOn({
  1329. account_name: config.ACCOUNT.account_name,
  1330. password: config.ACCOUNT.account_pass,
  1331. sha_sentryfile: sha,
  1332. two_factor_code: code
  1333. });
  1334. });
  1335. steamClient.on('logOnResponse', function(logonResp) {
  1336. if (logonResp.eresult == Steam.EResult.OK) {
  1337. // LOGGED IN
  1338. console.log("[ %s ] > Logged into Steam as " + steamClient.steamID, logTime());
  1339.  
  1340. steamFriends.setPersonaState(Steam.EPersonaState.Online);
  1341. steamFriends.setPersonaName(config.ACCOUNT.account_nick);
  1342. // SETUP OFFERS
  1343. steamWeb.webLogOn(function(webSessionID, cookies){
  1344. SteamMobileConfirmations = new SteamcommunityMobileConfirmations(
  1345. {
  1346. steamid: steamClient.steamID,
  1347. identity_secret: config.ACCOUNT.escrow_identity_secret,
  1348. device_id: ("armin_"+steamClient.steamID),
  1349. webCookie: cookies,
  1350. });
  1351.  
  1352. getSteamAPIKey({ sessionID: webSessionID, webCookie: cookies },function(shit,apikey){
  1353. if(shit)console.log(shit);
  1354. console.log('[ %s ] > Получили apikey: '+apikey,logTime());
  1355. offers.setup({
  1356. sessionID: webSessionID,
  1357. webCookie: cookies,
  1358. APIKey: apikey
  1359. }, function() {
  1360. InventoryWrapper = new SteamApi.Inventory(apikey,steamClient.steamID);
  1361.  
  1362. //printSentOffers();
  1363. reSendOffers();
  1364. resendInt = setInterval(function(){reSendOffers();},15000);
  1365.  
  1366. start_timer();
  1367. //printSentOffers();
  1368. });
  1369. });
  1370. steam_escrow = setInterval(function(){
  1371. AcceptConfirmations();
  1372. },60000);
  1373.  
  1374.  
  1375.  
  1376. });
  1377. }
  1378. });
  1379. steamClient.on('error', function (e) {
  1380. console.log(e);
  1381. process.exit(1);
  1382. });
  1383. function fakeOffers(id) {
  1384. client1.get(prefix + ":fakeoffer:"+id, function(err,result) {
  1385. if(result){
  1386. if(result.length>0) {
  1387. //console.log("fake %j",result);
  1388. var foffer = JSON.parse(result);
  1389. if(foffer) {
  1390. if(foffer.hasOwnProperty("steamid")) {
  1391. // CHECK FOR NEEDLE STEAMID
  1392. if(foffer.hasOwnProperty("wait_for_steamid")) {
  1393. var goin = 0;
  1394. for (var i = 0; i < ima_gamers.length; i++) {
  1395. if(ima_gamers[i].steamid == foffer.wait_for_steamid) {goin = 1;break;}
  1396. }
  1397. if(goin == 0) return;
  1398. }
  1399. // CHECK TIMING
  1400. //roundTimer
  1401. if(foffer.hasOwnProperty("wait_for_time")) {
  1402. var time_need = parseInt(foffer.wait_for_time);
  1403. var time_now = parseInt(config.ROUND.time)-parseInt(roundTimer);
  1404. //console.log("betting: time_now %s, time_need %s", time_now, time_need);
  1405. var goin = 0;
  1406. if (time_now <= time_need) {
  1407. goin = 1;
  1408. }
  1409. if(goin == 0) return;
  1410. }
  1411.  
  1412. // CHECK FOR MONEY
  1413. //money_round
  1414. if(foffer.hasOwnProperty("wait_for_money")) {
  1415. var goin = 0;
  1416. if (money_round >= foffer.wait_for_money) {
  1417. goin = 1;
  1418. }
  1419. if(goin == 0) return;
  1420. }
  1421. if(foffer.is_permanent == 1) {
  1422. if(!in_array(foffer.hash,used_fake_offers)) {
  1423. used_fake_offers.push(foffer.hash);
  1424. }
  1425. else {
  1426. return;
  1427. }
  1428. }
  1429.  
  1430. if(!in_array(foffer.steamid,fake_steamids)) fake_steamids.push(foffer.steamid); // ADD STEAMID TO ARRAY WITH AUTO322
  1431. console.log("[ %s ] > Incoming tradeoffer from " + foffer.steamid, logTime());
  1432.  
  1433. var items_n_global = [];
  1434. var re_fu = {
  1435. "id": 777,
  1436. "classid": 777,
  1437. "icon": foffer.icon,
  1438. "name": foffer.name,
  1439. "market_hash_name": foffer.market_hash_name,
  1440. "market_name": foffer.market_hash_name,
  1441. "color": "#222222",
  1442. "type": foffer.type,
  1443. "price": parseFloat(foffer.price),
  1444. "steamid": foffer.steamid,
  1445. "steam_name": foffer.nickname,
  1446. "profile_avatar": foffer.avatar
  1447. };
  1448.  
  1449. items_n_global.push(re_fu);
  1450.  
  1451. console.log(foffer.steamid + " - ожидание успешного завершения обмена");
  1452. var pubemit_temp = {
  1453. "items": items_n_global,
  1454. "money": parseFloat(foffer.price),
  1455. "steamid": foffer.steamid,
  1456. "steam_name": filterNick(foffer.nickname),
  1457. "profile_avatar": foffer.avatar,
  1458. "num_items": 1
  1459. };
  1460. check_price_add(pubemit_temp);
  1461. offer_trad.push({
  1462. name: foffer.name,
  1463. price: parseFloat(foffer.price),
  1464. img: foffer.icon,
  1465. rarity: getRarity(foffer.type),
  1466. market_hash_name: foffer.market_hash_name
  1467. });
  1468.  
  1469. if(!foffer.is_permanent) client1.del(prefix + ":fakeoffer:"+id);
  1470. }
  1471. }
  1472. }
  1473. }
  1474. });
  1475. }
  1476. function printSentOffers() {
  1477. offers.getOffers({
  1478. get_sent_offers: 1,
  1479. active_only: 1,
  1480. time_historical_cutoff: (Math.round(Date.now() / 1000) - 3600)
  1481. }, function(error, body) {
  1482. console.log("==============================\nLast sent offers:");
  1483. if(body) {
  1484. body.response.trade_offers_sent.forEach(function(offer) {
  1485. db.query('SELECT * FROM users WHERE steamid = ?',[offer.steamid_other],function(err,rows){
  1486. //console.log("%j",rows);
  1487. if(rows.length == 1) {
  1488. nickname = escapeHtml(rows[0].nickname);
  1489. }
  1490. else {
  1491. nickname = "Not found";
  1492. }
  1493. console.log("SteamID: %s (%s)\nMessage: %s\nTradeofferID: %s", offer.steamid_other, nickname, offer.message, offer.tradeofferid);
  1494. });
  1495. });
  1496. }
  1497. else {
  1498. console.log("ERROR: %j",error);
  1499. }
  1500. console.log("==============================");
  1501. });
  1502. }
  1503. function autoResend(){
  1504. 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){
  1505. if(rows.length>0){
  1506. console.log('[ %s ] Detected unfinished game #'+rows[0]['id'],logTime());
  1507. /*request('https://csgohoney.us/api/resend/'+rows[0]['id']+'/nihuasPaEb11', function (error, response, body) {
  1508. if (!error && response.statusCode == 200) {
  1509. console.log('[ %s ] Request to api result { %s }',logTime(),body);
  1510. }else {
  1511. console.log('[ %s ] Request tot api failed { %j }',logTime(),response);
  1512. }
  1513. });*/
  1514. db.query('UPDATE histories SET offercode=\'resending\' WHERE id='+rows[0]['id']);
  1515. var items = JSON.parse(rows[0]['items']);
  1516.  
  1517. var offer = [];
  1518. getlink(rows[0].steamid, function(link) { // получаем линк
  1519. if(!link.partner ) {
  1520. console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
  1521. }
  1522. else {
  1523. InventoryWrapper.GetAppItems(app_game, steamClient.steamID).done(function(items_inv){
  1524. if(err) {
  1525. console.log('offers.loadMyInventory error -'+err);
  1526. }else {
  1527. for(var j=0;j<items_inv.length;j++){
  1528. for(var i = 0;i<items.length;i++){
  1529.  
  1530.  
  1531. if(items[i].market_hash_name==items_inv[j].market_hash_name){
  1532. offer.push({
  1533. appid: app_game,
  1534. contextid: 2,
  1535. amount: 1,
  1536. assetid: items_inv[j].id
  1537. });
  1538. console.log(" Добавляем вещь в обмен: \x1b[33m%s\x1b[0m \x1b[33m(%s $)\x1b[0m", items[i].name, items[i].price);
  1539. items_inv.splice(items_inv[j], 1);
  1540. break;
  1541. }
  1542. }
  1543. }
  1544. if(items.length==offer.length){
  1545. console.log('[ %s ] Все предметы на месте',logTime());
  1546. db.query('INSERT INTO temp_offers SET steamid = ?, gameid = ?, offer = ?, message = ?', [
  1547. rows[0]['steamid'],
  1548. rows[0]['id'],
  1549. JSON.stringify(offer),
  1550. 'You win game №'+rows[0]['id']+' on '+main_url
  1551. ]);
  1552.  
  1553. }else {
  1554.  
  1555. console.log('[ %s ] Ошибка! Не хватает предметов, переотправка через Unfinished games',logTime());
  1556. console.log(' - offer >'+offer.length);
  1557. console.log(' - items >'+items.length);
  1558. }
  1559. }
  1560.  
  1561. });
  1562.  
  1563.  
  1564. }
  1565. });
  1566. /*
  1567. $item = array(
  1568. 'appid'=>(string)$gameid,
  1569. 'contextid'=>(string)2,
  1570. 'amount'=>(string)1,
  1571. 'assetid'=>(string)$key
  1572. );
  1573. $db->insertRow('INSERT INTO temp_offers SET steamid = ?, gameid = ?, offer = ?, message = ?', array(
  1574. $q[0]['steamid'],
  1575. $q[0]['id'],
  1576. json_encode($OFFER,true),
  1577. ('You won game №'.$q[0]['id'].' on '.$_SERVER['HTTP_HOST'].' (Resent)')
  1578. ));*/
  1579.  
  1580. }
  1581. });
  1582. }
  1583. function reSendOffers() {
  1584. db.query('SELECT * FROM temp_offers ORDER BY id ASC',function(err,rows){
  1585. if(rows.length > 0) {
  1586. console.log('Resend Function Processing [Requests: %s]',rows.length);
  1587. //console.log('%j', rows[0]);
  1588. getlink(rows[0].steamid, function(link) { // получаем линк
  1589. if(!link.partner ) {
  1590. console.log("[ %s ] \x1b[31m>\x1b[0m Ссылка не установлена", logTime());
  1591. }
  1592. else {
  1593. //console.log("[ %s ] \x1b[32m>\x1b[0m Получили ссылку", logTime());
  1594. var makeoffer = {};
  1595. makeoffer['itemsFromThem'] = [];
  1596. makeoffer['itemsFromMe'] = JSON.parse(rows[0].offer);
  1597. //console.log("%j", makeoffer);
  1598. offers.makeOffer({
  1599. partnerAccountId: link.partner,
  1600. accessToken: link.token,
  1601. itemsFromMe: makeoffer.itemsFromMe,
  1602. itemsFromThem: makeoffer.itemsFromThem,
  1603. message: rows[0].message
  1604. }, function(err, response) {
  1605. if(err) console.log(' >> Resend ERROR: %s',err);
  1606. if(response) {
  1607. AcceptConfirmations();
  1608. db.query('UPDATE histories SET status = "1", offercode = "0" WHERE id = ?',[rows[0].gameid],function(err,lines){if(err) console.log(err);});
  1609. }
  1610. db.query('DELETE FROM temp_offers WHERE id = ?',[rows[0].id],function(err,lines){if(err) console.log(err);});
  1611. });
  1612. }
  1613. });
  1614. }
  1615. else {
  1616. if(err) console.log('RESEND FUNCTION MYSQL ERROR: '+err);
  1617. }
  1618. });
  1619. }
  1620. /*
  1621. * Если кидают обмен
  1622. */
  1623. var tradeoffferstime = setInterval(function() {
  1624. if (accept_trade == true) {
  1625. // FAKE OFFER
  1626.  
  1627. client1.keys(prefix + ":fakeoffer:*", function(err,result) {
  1628. if(result) {
  1629. result.forEach(function(offer) {
  1630. if(offer.length > 0) {
  1631. var id = explode(":",offer);
  1632. fakeOffers(id[2]);
  1633. }
  1634. });
  1635. }
  1636. if(err) console.log("%j",err);
  1637. });
  1638. // REAL OFFERS
  1639. offers.getOffers({
  1640. get_received_offers: 1,
  1641. active_only: 1,
  1642. time_historical_cutoff: Math.round(Date.now() / 1000)
  1643. }, function(error, body) {
  1644. if(error == null)
  1645. {
  1646. if(body.response.trade_offers_received) {
  1647. body.response.trade_offers_received.forEach(function(offer) {
  1648. if (offer.trade_offer_state == 2)
  1649. {
  1650. if(in_array(offer.steamid_other, admins)) {
  1651. console.log('[ %s ] Offer from admin steamid %s accepted',logTime(),offer.steamid_other);
  1652. offers.acceptOffer({tradeOfferId: offer.tradeofferid});
  1653. AcceptConfirmations();
  1654. }
  1655. else
  1656. {
  1657. if(typeof arr_prof[offer.steamid_other] == 'undefined')
  1658. {
  1659. arr_prof_add(offer.steamid_other);
  1660.  
  1661. var text_msg = "";
  1662. var escrow_pass = 0;
  1663. if(offer.hasOwnProperty('escrow_end_date')) {
  1664. if(offer.escrow_end_date != 0) {
  1665. escrow_pass = 0;
  1666. }
  1667. else escrow_pass = 1;
  1668. }
  1669. //console.log("\n%j\n",offer);
  1670. if(offer.items_to_give == null && offer.items_to_receive != null && escrow_pass == 1)
  1671. {
  1672. 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) {
  1673. console.log("[ %s ] > Incoming tradeoffer from " + offer.steamid_other, logTime());
  1674. var offer_seconds_passed = (Math.round(+new Date()/1000))-offer.time_updated;
  1675. if(offer_seconds_passed>145) {
  1676. console.log('[ %s ] > Trying to cancel obsolete offer (age is %s seconds)',logTime(),offer_seconds_passed);
  1677. return declineoffer("too_old_offer", offer.steamid_other, offer.tradeofferid);
  1678. }
  1679. checkprice(offer.items_to_receive, offer.steamid_other, offer.tradeofferid);
  1680. } else text_msg = "bot_item_limit";
  1681. } else text_msg = "bot_tradeoffer_failed";
  1682.  
  1683. if(text_msg != "")
  1684. {
  1685. console.log(offer.steamid_other + " Произошла ошибка - " + text_msg);
  1686. declineoffer(text_msg, offer.steamid_other, offer.tradeofferid);
  1687. }
  1688. }
  1689. }
  1690. }
  1691. });
  1692. }
  1693. }
  1694. });
  1695. }
  1696. } , 2000);
  1697.  
  1698. function escapeHtml(text) {
  1699. var map = {
  1700. '&': '&amp;',
  1701. '<': '&lt;',
  1702. '>': '&gt;',
  1703. '"': '&quot;',
  1704. "'": '&#039;'
  1705. };
  1706. return text.replace(/[&<>"']/g, function(m) {
  1707. return map[m];
  1708. });
  1709. }
  1710.  
  1711. function getDateTime() {
  1712.  
  1713. var date = new Date();
  1714. var hour = date.getHours();
  1715. var min = date.getMinutes();
  1716. var sec = date.getSeconds();
  1717.  
  1718. var year = date.getFullYear();
  1719. var month = date.getMonth() + 1;
  1720. var day = date.getDate();
  1721.  
  1722. hour = (hour < 10 ? "0" : "") + hour;
  1723. min = (min < 10 ? "0" : "") + min;
  1724. sec = (sec < 10 ? "0" : "") + sec;
  1725. month = (month < 10 ? "0" : "") + month;
  1726. day = (day < 10 ? "0" : "") + day;
  1727.  
  1728. return day + "." + month + "." + year + " " + hour + ":" + min + ":" + sec;
  1729. }
  1730. function logTime() {
  1731.  
  1732. var date = new Date();
  1733. var hour = date.getHours();
  1734. var min = date.getMinutes();
  1735. var sec = date.getSeconds();
  1736.  
  1737. var year = date.getFullYear();
  1738. var month = date.getMonth() + 1;
  1739. var day = date.getDate();
  1740.  
  1741. hour = (hour < 10 ? "0" : "") + hour;
  1742. min = (min < 10 ? "0" : "") + min;
  1743. sec = (sec < 10 ? "0" : "") + sec;
  1744. month = (month < 10 ? "0" : "") + month;
  1745. day = (day < 10 ? "0" : "") + day;
  1746.  
  1747. return hour + ":" + min + ":" + sec;
  1748. }
  1749.  
  1750. function AcceptConfirmations(){
  1751. SteamMobileConfirmations.FetchConfirmations(function (err, confirmations){
  1752. if (err)
  1753. {
  1754. console.log(err);
  1755. return;
  1756. }
  1757. if(confirmations.length > 0)
  1758. console.log('[ %s ] > Confirmations received ' + confirmations.length + ' confirmations', logTime());
  1759. if ( ! confirmations.length)
  1760. {
  1761. return;
  1762. }
  1763. confirmations.forEach(function(item,i,arr)
  1764. {
  1765. SteamMobileConfirmations.AcceptConfirmation(item, function (err, result)
  1766. {
  1767. if (err)
  1768. {
  1769. console.log(err);
  1770. return;
  1771. }
  1772. console.log('[ %s ] > Accept result: ' + result, logTime());
  1773. });
  1774. });
  1775.  
  1776. });
  1777. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement