Advertisement
Guest User

Untitled

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