Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Script created by Echo
- var fs = require('fs');
- var request = require('request');
- var config = require('./config.json');
- var crypto = require('crypto');
- var log4js = require('log4js');
- //SSL INIT
- var express = require('express');
- var options = {
- key: fs.readFileSync('certs/name.key'),
- cert: fs.readFileSync('certs/name.crt'),
- requestCert: true
- };
- var app = express();
- var server = require('https').createServer(options, app);
- var io = require('socket.io').listen(server);
- server.listen(2087, "0.0.0.0");
- //SSL END
- log4js.configure({
- appenders: {
- console: {
- type: 'console'
- },
- default: {
- type: 'file',
- filename: 'logs/cf_'+time()+'.log'
- }
- },
- categories: {
- default: {
- appenders: ['default', 'console'],
- level: 'trace'
- }
- }
- });
- var logger = log4js.getLogger();
- //BOT PACKAGES
- var bots = {
- 'communities': {},
- 'clients': {},
- 'managers': {}
- };
- var SteamUser = require('steam-user');
- var TradeOfferManager = require('steam-tradeoffer-manager');
- var SteamTotp = require('steam-totp');
- var SteamCommunity = require('steamcommunity');
- //BOT PACKAGES
- //PICK BOTS//
- var get_bots = config.bots;
- for(var z in get_bots)
- {
- if(get_bots[z]['botname'])
- {
- logger.trace('Bot ' + z + ' detected in config.');
- bots['communities'][z] = new SteamCommunity();
- bots['clients'][z] = new SteamUser();
- bots['managers'][z] = new TradeOfferManager({
- steam: bots['clients'][z],
- domain: 'localhost',
- language: 'en'
- });
- }
- }
- //PICK BOTS//
- var mysql = require('mysql');
- var db_config = {
- //debug: true,
- host: config.options.sql['host'],
- user: config.options.sql['username'],
- password: config.options.sql['password'],
- database: config.options.sql['database']
- };
- var pool;
- handleDisconnect();
- setInterval(function() { verifyGame(); }, 10000);
- process.on('uncaughtException', function (err) {
- logger.error('Strange error');
- logger.error(err);
- });
- //GAME INFO
- var AppID = 730;
- var ContextID = 2;
- var minDep = config.options.minDeposit;
- var percentRake = 8;
- var maximumBots = 2;
- var jackpotPRake = 8;
- var coolDown = {};
- var sendTradeCoolDown = {};
- var proxies = config.proxies;
- var deletingTrades = [];
- var inventoryTimer = {};
- var socketBySteam = {};
- var tradingRequests = {};
- var loadGames = [];
- var timerGame = {};
- var timer11Game = {};
- //PIN SYSTEM
- var pinSystem = false;
- var pinnedMessages = [];
- //PIN SYSTEM
- var gamesPending = {};
- var antiFlood = {};
- var timesFlooding = {};
- var inventoryUser = {};
- var gameJoinedExpire = {};
- //CHAT FUNCTIONS
- var chatMessages = [];
- var usersOnline = {};
- var antiSpamChat = {};
- //CHAT FUNCTIONS
- //JACKPOT'
- var jackpotHash = "";
- var jackpotSecret = "";
- var jackpotRound = -1;
- var jackpotBot = 0;
- var jackpotState = 'NONE';
- var jackpotTickets = 0;
- var jackpotTotalTickets = [];
- var totalJackpotItems = 0;
- var totalJackpotValue = 0;
- var totalSecondsJackpot = 0;
- var usersPrices = {};
- var checkJackpotEnd;
- var JackpotUsers = [];
- var JinventoryUser = {};
- var JinventoryTimer = {};
- var jackpotQueueBets = [];
- var jackpotInt;
- var jackpotNextRoundTime;
- var CoinfliprecentGames = [];
- nextJackpotRound();
- function nextJackpotRound()
- {
- var secret = makeSecret();
- var hash = makeHash();
- var botAles = Math.floor(Math.random() * (maximumBots - 1 + 1)) + 1;
- var botul = 'bot' + botAles;
- pool.query('INSERT INTO jgames SET hash = ' + pool.escape(hash) + ', secret = ' + pool.escape(secret) + ', pot = 0.00, items = 0, tickets = 0, bot = ' + pool.escape(botul), function(er, ro) {
- if(er) throw er;
- jackpotRound = ro.insertId;
- jackpotState = 'WAITING';
- jackpotHash = hash;
- jackpotSecret = secret;
- JackpotUsers = [];
- jackpotTotalTickets = [];
- jackpotTickets = 0;
- totalJackpotItems = 0;
- totalJackpotValue = 0;
- totalSecondsJackpot = 0;
- usersPrices = {};
- jackpotBot = botul;
- io.sockets.emit('message', {
- type: 'newJackpotRound',
- hash: hash
- });
- if(jackpotQueueBets.length > 0)
- {
- for(var i in jackpotQueueBets)
- {
- if(jackpotQueueBets[i]['removed'] != 1)
- {
- if(jackpotState == 'WAITING') jackpotState = 'BETTING';
- var minTicket = parseInt(jackpotTickets+1);
- var maxTicket = parseInt(minTicket+(jackpotQueueBets[i]['totalPrice']*100)-1);
- for(var a = minTicket; a < maxTicket; a++)
- {
- jackpotTotalTickets.push({
- 'user': jackpotQueueBets[i]['user'],
- 'ticket': parseInt(a)
- });
- }
- jackpotTickets += parseInt(jackpotQueueBets[i]['totalPrice']*100);
- var assetidsSS = jackpotQueueBets[i]['receivedItems'].join('/');
- pool.query('INSERT INTO jbets SET user = ' + pool.escape(jackpotQueueBets[i]['user']) + ', assetids = ' + pool.escape(assetidsSS) + ', value = ' + pool.escape(jackpotQueueBets[i]['totalPrice']) + ', minTicket = ' + pool.escape(minTicket) + ', maxTicket = ' + pool.escape(maxTicket) + ', total = ' + pool.escape(jackpotQueueBets[i]['totalSkins']) + ', jid = ' + pool.escape(jackpotRound) + ', token = ' + pool.escape(jackpotQueueBets[i]['offerID']));
- setTimeout(function() {
- addJackpotBet(jackpotQueueBets[i]['user'], jackpotQueueBets[i]['skinImages'], jackpotQueueBets[i]['skinImages'], jackpotQueueBets[i]['skinPrices'], jackpotQueueBets[i]['totalSkins'], jackpotQueueBets[i]['totalPrice'], jackpotQueueBets[i]['itemsData']);
- jackpotQueueBets[i]['removed'] = 1;
- }, 8000);
- }
- }
- }
- });
- }
- lastGames();
- function lastGames()
- {
- pool.query('SELECT * FROM games WHERE ended = 1 AND tcreated > ' + pool.escape(time()-86400) + ' ORDER BY id DESC LIMIT 20', function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- var recentGames = [];
- for(var i in row)
- {
- CoinfliprecentGames.push(row[i]);
- }
- });
- }
- setTradingRequests();
- function setTradingRequests()
- {
- pool.query('SELECT * FROM trades WHERE status = ' + pool.escape('PendingAccept'), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- for(var i in row)
- {
- logger.debug('Trade #' + row[i].tid + ' added --> ' + row[i].action + ' + ' + row[i].user);
- var timpExpire = time()+20;
- tradingRequests[row[i].tid] = {
- action: row[i].action,
- user: row[i].user,
- created: parseInt(row[i].created),
- expired: timpExpire
- };
- pool.query('UPDATE trades SET expired = ' + pool.escape(timpExpire) + ' WHERE id = ' + pool.escape(row[i].id));
- }
- });
- }
- loadAllGames();
- function loadAllGames()
- {
- pool.query('SELECT * FROM games WHERE `ended` = 0', function(err, res) {
- if(err) throw err;
- loadGames = [];
- for(var i in res)
- {
- loadGames.push({
- 'id': res[i].id,
- 'csteamid': res[i].csteamid,
- 'cname': res[i].cname,
- 'cavatar': res[i].cavatar,
- 'cskinsurl': res[i].cskinsurl,
- 'cskinsnames': res[i].cskinsnames,
- 'cskinsprices': res[i].cskinsprices,
- 'cskins': res[i].cskins,
- 'ctp': res[i].ctp,
- 'psteamid': res[i].psteamid,
- 'pname': res[i].pname,
- 'pavatar': res[i].pavatar,
- 'pskinsurl': res[i].pskinsurl,
- 'pskinsnames': res[i].pskinsnames,
- 'pskinsprices': res[i].pskinsprices,
- 'pskins': res[i].pskins,
- 'ptp': res[i].ptp,
- 'hash': res[i].hash,
- 'secret': res[i].secret,
- 'cpick': res[i].cpick,
- 'ppick': res[i].ppick,
- 'winner': res[i].winner,
- 'winnerPercentage': res[i].winnerPercentage,
- 'timer11': res[i].timer11
- });
- }
- });
- }
- function sendTrades(socket, steamid)
- {
- pool.query('SELECT * FROM trades WHERE user = ' + pool.escape(steamid) + ' ORDER BY id DESC', function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- var ids = [];
- var tids = [];
- var codes = [];
- var actions = [];
- var statuses = [];
- for(var i in row)
- {
- ids.push(row[i]['id']);
- tids.push(row[i]['tid']);
- codes.push(row[i]['code']);
- actions.push(row[i]['action']);
- statuses.push(row[i]['status']);
- }
- ids = ids.join('/');
- tids = tids.join('/');
- codes = codes.join('/');
- actions = actions.join('/');
- statuses = statuses.join('/');
- socket.emit('message', {
- type: 'getTrades',
- trades: {
- id: ids,
- tid: tids,
- code: codes,
- action: actions,
- status: statuses
- }
- });
- });
- }
- function sendProfileStatistics(socket, steamid)
- {
- pool.query('SELECT csteamid, psteamid, cpick, ppick, ctp, ptp, winner FROM games WHERE csteamid = ' + pool.escape(steamid) + ' OR psteamid = ' + pool.escape(steamid), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- var totalplayed = 0;
- var totalwon = 0;
- var totallost = 0;
- for(var i in row)
- {
- if(row[i]['csteamid'] == steamid)
- {
- if(row[i]['winner'] == 'ct')
- {
- if(row[i]['cpick'] == 'ct')
- {
- totalwon += row[i]['ctp']+row[i]['ptp'];
- totalplayed += row[i]['ctp']+row[i]['ptp'];
- }
- else if(row[i]['cpick'] == 't')
- {
- totallost += row[i]['ctp'];
- totalplayed += row[i]['ctp'];
- }
- }
- else if(row[i]['winner'] == 't')
- {
- if(row[i]['cpick'] == 't')
- {
- totalwon += row[i]['ctp']+row[i]['ptp'];
- totalplayed += row[i]['ctp']+row[i]['ptp'];
- }
- else if(row[i]['cpick'] == 'ct')
- {
- totallost += row[i]['ctp'];
- totalplayed += row[i]['ctp'];
- }
- }
- }
- else if(row[i]['psteamid'] == steamid)
- {
- if(row[i]['winner'] == 'ct')
- {
- if(row[i]['ppick'] == 'ct')
- {
- totalwon += row[i]['ctp']+row[i]['ptp'];
- totalplayed += row[i]['ctp']+row[i]['ptp'];
- }
- else if(row[i]['ppick'] == 't')
- {
- totallost += row[i]['ptp'];
- totalplayed += row[i]['ptp'];
- }
- }
- else if(row[i]['winner'] == 't')
- {
- if(row[i]['ppick'] == 't')
- {
- totalwon += row[i]['ctp']+row[i]['ptp'];
- totalplayed += row[i]['ctp']+row[i]['ptp'];
- }
- else if(row[i]['ppick'] == 'ct')
- {
- totallost += row[i]['ptp'];
- totalplayed += row[i]['ptp'];
- }
- }
- }
- }
- socket.emit('message', {
- type: 'profileStatistics',
- totalplayed: totalplayed,
- totalwon: totalwon,
- totallost: totallost
- });
- });
- }
- io.on('connection', function(socket) {
- socket.on('hash', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- addHistory(socket);
- socket.emit('pinsSystem', pinSystem, pinnedMessages);
- if(!usersOnline[address])
- {
- usersOnline[address] = 1;
- }
- pool.query('SELECT steamid FROM users WHERE csrf_token = ' + pool.escape(m.csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0)
- {
- socket.emit('message', {
- type: 'newJackpotRound',
- hash: jackpotHash
- });
- if(jackpotState == 'BETTING')
- {
- for(var i in JackpotUsers)
- {
- socket.emit('message', {
- type: 'addJackpotBet',
- userInfo: {
- avatar: JackpotUsers[i]['userInfo'].avatar,
- name: JackpotUsers[i]['userInfo'].name,
- steamid: JackpotUsers[i]['userInfo'].steamid,
- level: JackpotUsers[i]['userInfo'].level
- },
- itemsInfo: JackpotUsers[i]['itemsInfo']
- });
- }
- socket.emit('message', {
- type: 'jackpotSet',
- totalUsers: JackpotUsers.length,
- potItemsValue: totalJackpotValue,
- potValue: totalJackpotItems,
- timpul: totalSecondsJackpot-time()
- });
- }
- }
- if(row.length > 0)
- {
- getInv(row[0].steamid, socket);
- if(socketBySteam.hasOwnProperty(row[0].steamid))
- {
- delete socketBySteam[row[0].steamid];
- socketBySteam[row[0].steamid] = {
- 'info': socket.id
- };
- }
- else
- {
- socketBySteam[row[0].steamid] = {
- 'info': socket.id
- };
- }
- socket.emit('message', {
- type: 'newJackpotRound',
- hash: jackpotHash
- });
- if(jackpotState == 'BETTING')
- {
- JackpotUsers.forEach(function (i) {
- if(i['userInfo'].steamid == row[0].steamid)
- {
- var yourValue = 0;
- for(var z in i['itemsInfo'])
- {
- yourValue += parseFloat(i['itemsInfo'][z].price);
- }
- var chance = 100 - ((totalJackpotValue-yourValue)/totalJackpotValue)*100;
- socket.emit('message', {
- type: 'standingQueue',
- totalItems: i['itemsInfo'].length,
- yourChance: chance
- });
- }
- });
- for(var i in JackpotUsers)
- {
- socket.emit('message', {
- type: 'addJackpotBet',
- userInfo: {
- avatar: JackpotUsers[i]['userInfo'].avatar,
- name: JackpotUsers[i]['userInfo'].name,
- steamid: JackpotUsers[i]['userInfo'].steamid,
- level: JackpotUsers[i]['userInfo'].level
- },
- itemsInfo: JackpotUsers[i]['itemsInfo']
- });
- }
- socket.emit('message', {
- type: 'jackpotSet',
- totalUsers: JackpotUsers.length,
- potItemsValue: totalJackpotValue,
- potValue: totalJackpotItems,
- timpul: totalSecondsJackpot-time()
- });
- }
- }
- });
- loadStatistics(socket);
- io.sockets.emit('message', {
- type: 'connections',
- total: Object.keys(usersOnline).length
- });
- loadGames.forEach(function(itm) {
- socket.emit('message', {
- type: 'addGame',
- games: {
- 'id': itm.id,
- 'csteamid': itm.csteamid,
- 'cname': itm.cname,
- 'cavatar': itm.cavatar,
- 'cskinsurl': itm.cskinsurl,
- 'cskinsnames': itm.cskinsnames,
- 'cskinsprices': itm.cskinsprices,
- 'cskins': itm.cskins,
- 'ctp': itm.ctp,
- 'psteamid': itm.psteamid,
- 'pname': itm.pname,
- 'pavatar': itm.pavatar,
- 'pskinsurl': itm.pskinsurl,
- 'pskinsnames': itm.pskinsnames,
- 'pskinsprices': itm.pskinsprices,
- 'pskins': itm.pskins,
- 'ptp': itm.ptp,
- 'hash': itm.hash,
- 'secret': itm.secret,
- 'winnerPercentage': itm.winnerPercentage,
- 'winner': itm.winner,
- 'cpick': itm.cpick,
- 'ppick': itm.ppick,
- 'timer': timerGame[itm.id]-time(),
- 'timer11': itm.timer11,
- 'ttimer11': timer11Game[itm.id]-time()
- }
- });
- });
- });
- socket.on('jackpot_win', function(steamid, token, prize_won) {
- if(steamid && token && prize_won) {
- prize_won_load(steamid, token, prize_won, function(error, msg) {
- if(error == 1) socket.emit('message', {type: 'msg', tip: 'error', msg: msg});
- else socket.emit('message', {type: 'msg', tip: 'alert', msg: msg});
- });
- }
- });
- socket.on('getProfile_stats', function(csrf) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(csrf)
- {
- pool.query('SELECT steamid FROM users WHERE csrf_token = ' + pool.escape(csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- sendProfileStatistics(socket, row[0].steamid);
- });
- }
- });
- socket.on('getTrades_web', function(csrf) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(csrf)
- {
- pool.query('SELECT steamid FROM users WHERE csrf_token = ' + pool.escape(csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- sendTrades(socket, row[0].steamid);
- });
- }
- });
- socket.on('sendTrade', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- var tradeID = m.tradeID;
- if(!tradeID)
- {
- if(socketBySteam.hasOwnProperty(row[0].user))
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You need to enter a tradeid.'
- });
- }
- }
- return;
- }
- pool.query('SELECT status,action,user,items,code,bot FROM trades WHERE tid = ' + pool.escape(tradeID), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row[0].status == 'PendingAccept' && row[0].action == 'winning')
- {
- pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(row[0].user), function(er, ro) {
- if(er) throw er;
- if(ro.length == 0)
- {
- if(socketBySteam.hasOwnProperty(row[0].user))
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'User does not exists in db.'
- });
- }
- }
- return;
- }
- if(sendTradeCoolDown[address]-time() >= 1) {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You need to wait ' + (sendTradeCoolDown[address]-time()) + ' more seconds to click it again.'
- });
- return;
- } else {
- sendTradeCoolDown[address] = time()+60;
- }
- if(!ro[0].tradelink.includes('://'))
- {
- if(socketBySteam.hasOwnProperty(row[0].user))
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You need to add your tradelink before requesting a tradeoffer.'
- });
- sendTradeCoolDown[address] = time();
- }
- }
- return;
- }
- pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].user) + ' AND status = ' + pool.escape('PendingAccept') + ' AND NOT action = ' + pool.escape('winning'), function(ca, ma) {
- if(ca) throw ca;
- if(ma.length == 0) return;
- if(ma[0].tTrades != 0)
- {
- if(socketBySteam.hasOwnProperty(row[0].user))
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You isset an active tradeoffer.'
- });
- sendTradeCoolDown[address] = time();
- }
- }
- return;
- }
- var Items = row[0].items.split('/');
- var create = bots['managers'][row[0].bot].createOffer(row[0].user, ro[0].tradelink.split('token=')[1]);
- bots['managers'][row[0].bot].loadInventory(AppID, ContextID, true, function(err, inv, curr) {
- if(err) throw err;
- if(inv.length == 0)
- {
- logger.info('An error ocurred while loading bot inventory. Status of trade #' + tradeID + ' has been changed to <Accepted>.');
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(tradeID));
- sendTradeCoolDown[address] = time();
- return;
- }
- for(var i in Items)
- {
- for(var z in inv)
- {
- if(Items[i] == inv[z].assetid && Items[i] != 1)
- {
- Items[i] = 1;
- create.addMyItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": inv[z].assetid
- });
- }
- }
- }
- create.setMessage('Your winnings are here. Security code: ' + row[0].code);
- create.send(function(err2, status) {
- if(err2)
- {
- if(err2.toString() == 'Error: Cannot send an empty trade offer')
- {
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(tradeID));
- logger.info('Trade #' + tradeID + ' has been already accepted, so the trade will not be send.');
- if(socketBySteam.hasOwnProperty(row[0].user))
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'This trade was accepted in the past. Status changed to "Accepted".'
- });
- sendTradeCoolDown[address] = time();
- }
- }
- }
- else
- {
- throw err2;
- }
- return;
- }
- var timpExpire = time()+90;
- tradingRequests[create.id] = {
- action: 'winning',
- user: row[0].user,
- created: time(),
- expire: timpExpire
- };
- pool.query('UPDATE trades SET tid = ' + pool.escape(create.id) + ', expired = ' + pool.escape(timpExpire) + ' WHERE tid = ' + pool.escape(tradeID));
- if(socketBySteam.hasOwnProperty(row[0].user))
- {
- if(io.sockets.connected[socketBySteam[row[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[row[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerSend',
- code: row[0].code,
- tid: create.id
- });
- }
- }
- logger.debug('Winnings from tradeid #' + tradeID + ' were sent again to winner ' + row[0].user + ' new tradeoffer #' + create.id);
- sendTradeCoolDown[address] = time();
- });
- });
- });
- });
- }
- });
- });
- //JACKPOT PLAYER GETINV
- socket.on('jwantInv', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(m.csrf)
- {
- pool.query('SELECT steamid FROM users WHERE csrf_token = ' + pool.escape(m.csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row.length > 0 && !JinventoryTimer.hasOwnProperty(row[0].steamid))
- {
- jgetInv(row[0].steamid, socket);
- JinventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- }
- else if(row.length > 0 && JinventoryTimer.hasOwnProperty(row[0].steamid))
- {
- if(JinventoryUser.hasOwnProperty(row[0].steamid) && JinventoryTimer[row[0].steamid]['timer']-time() > 0)
- {
- var id = JinventoryUser[row[0].steamid]['id'];
- var name = JinventoryUser[row[0].steamid]['name'];
- var price = JinventoryUser[row[0].steamid]['price'];
- var img = JinventoryUser[row[0].steamid]['img'];
- socket.emit('message', {
- type: 'jgetInventory',
- id: id,
- name: name,
- price: price,
- img: img
- });
- socket.emit('message', {
- type: 'msg',
- tip: 'jInv',
- seconds: JinventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- else if(JinventoryTimer[row[0].steamid]['timer']-time() <= 0)
- {
- JinventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- jgetInv(row[0].steamid, socket);
- socket.emit('message', {
- type: 'msg',
- tip: 'jInv',
- seconds: JinventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- }
- });
- }
- });
- //JACKPOT DEPOSIT BUTTON
- socket.on('jDeposit', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(antiFlood[socket]+2 >= time()) {
- timesFlooding[socket] += 1;
- if(timesFlooding[socket] == 3)
- {
- delete timesFlooding[socket];
- socket.disconnect();
- return;
- }
- return;
- } else {
- antiFlood[socket] = time();
- }
- if(m.csrf)
- {
- pool.query('SELECT steamid,tradelink,rank FROM users WHERE csrf_token = ' + pool.escape(m.csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0)
- {
- logger.debug('Error [1]');
- return;
- }
- pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].steamid) + ' AND status = ' + pool.escape('PendingAccept'), function(er, ro) {
- if(er) throw er;
- if(ro.length == 0) return;
- if(ro[0].tTrades != 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: You isset an active tradeoffer.'
- });
- return;
- }
- if(!row[0].tradelink.includes('://') || !row[0].tradelink.includes('steamcommunity.com') || !row[0].tradelink.includes('partner') || !row[0].tradelink.includes('token'))
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: Tradelink wrong.'
- });
- return;
- }
- var joinedJackpot = 0;
- JackpotUsers.forEach(function (i) {
- if(i['userInfo'].steamid == row[0].steamid && row[0].rank != 69)
- {
- joinedJackpot = 1;
- }
- });
- if(joinedJackpot == 1)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: You are already in this pot!'
- });
- return;
- }
- if(jackpotRound == -1)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: The game is not open.'
- });
- return;
- }
- if(jackpotState == 'NONE')
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: The game did not start. (state: ' + jackpotState + ')'
- });
- return;
- }
- var Items = m.assets.split('/');
- var ItemsToReceived = 0;
- var ItemsPriceValue = 0;
- var pretul = require('./prices.json');
- var itemsToReceive = [];
- var create = bots['managers'][jackpotBot].createOffer(row[0].steamid, row[0].tradelink.split('token=')[1]);
- bots['managers'][jackpotBot].getUserInventoryContents(row[0].steamid, AppID, ContextID, true, function(e, inv, curr) {
- if(e) throw e;
- if(inv.length == 0)
- {
- logger.debug('Error [4]');
- return;
- }
- for(var i in Items)
- {
- for(var z in inv)
- {
- if(Items[i] == inv[z].assetid && Items[i].ss != 1)
- {
- Items[i].ss = 1;
- ItemsToReceived++;
- ItemsPriceValue += parseFloat(pretul[inv[z].market_hash_name]);
- itemsToReceive.push(inv[z].assetid);
- }
- }
- }
- if(ItemsToReceived + totalJackpotItems > 50)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: You exceeded the maximum items in this pot!'
- });
- return;
- }
- if(ItemsToReceived > 25)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: Maximum items per user is 25!'
- });
- return;
- }
- if(itemsToReceive.length == 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Error: You need to select items.'
- });
- return;
- }
- for(var i in itemsToReceive)
- {
- create.addTheirItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsToReceive[i]
- });
- }
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerProcessing'
- });
- var cod = makeCode();
- create.setMessage('Security code: ' + cod);
- create.send(function(ab, status) {
- if(ab)
- {
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerError',
- msg: ab.toString()
- });
- logger.trace('Line: 1078' + ab.toString());
- return;
- }
- var timpCreat = time();
- var timpExpired = time()+90;
- logger.debug('Tradeoffer #' + create.id + ' (' + status + ' - joinJackpot) with code : ' + cod + ' has been created by steamid: ' + row[0].steamid);
- tradingRequests[create.id] = {
- action: 'joinJackpot',
- user: row[0].steamid,
- created: timpCreat,
- expired: timpExpired
- }
- pool.query('INSERT INTO trades SET user = ' + pool.escape(row[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('joinJackpot') + ', code = ' + pool.escape(cod) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpired) + ', bot = ' + pool.escape(jackpotBot));
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerSend',
- tid: create.id,
- code: cod
- });
- });
- });
- });
- });
- }
- });
- //INVENTORY TIMER
- socket.on('wantInv', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(m.csrf)
- {
- pool.query('SELECT steamid FROM users WHERE csrf_token = ' + pool.escape(m.csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- getInv(row[0].steamid, socket);
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- }
- else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
- {
- var id = inventoryUser[row[0].steamid]['id'];
- var name = inventoryUser[row[0].steamid]['name'];
- var price = inventoryUser[row[0].steamid]['price'];
- var img = inventoryUser[row[0].steamid]['img'];
- socket.emit('message', {
- type: 'getInventory',
- id: id,
- name: name,
- price: price,
- img: img
- });
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
- {
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- getInv(row[0].steamid, socket);
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- }
- });
- }
- });
- socket.on('wantInv2', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(m.csrf)
- {
- pool.query('SELECT steamid FROM users WHERE csrf_token = ' + pool.escape(m.csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- if(row.length > 0 && !inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- getInv2(row[0].steamid, socket);
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- }
- else if(row.length > 0 && inventoryTimer.hasOwnProperty(row[0].steamid))
- {
- if(inventoryUser.hasOwnProperty(row[0].steamid) && inventoryTimer[row[0].steamid]['timer']-time() > 0)
- {
- var id = inventoryUser[row[0].steamid]['id'];
- var name = inventoryUser[row[0].steamid]['name'];
- var price = inventoryUser[row[0].steamid]['price'];
- var img = inventoryUser[row[0].steamid]['img'];
- socket.emit('message', {
- type: 'getInventory2',
- id: id,
- name: name,
- price: price,
- img: img
- });
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv2',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- else if(inventoryTimer[row[0].steamid]['timer']-time() <= 0)
- {
- inventoryTimer[row[0].steamid] = {
- 'timer': time()+45
- };
- getInv2(row[0].steamid, socket);
- socket.emit('message', {
- type: 'msg',
- tip: 'Inv2',
- seconds: inventoryTimer[row[0].steamid]['timer']-time()
- });
- }
- }
- });
- }
- });
- socket.on('newGame', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(antiFlood[socket]+2 >= time()) {
- timesFlooding[socket] += 1;
- if(timesFlooding[socket] == 3)
- {
- delete timesFlooding[socket];
- socket.disconnect();
- return;
- }
- return;
- } else {
- antiFlood[socket] = time();
- }
- if(m.csrf)
- {
- pool.query('SELECT steamid,tradelink FROM users WHERE csrf_token = ' + pool.escape(m.csrf), function(err, row) {
- if(err) throw err;
- if(row.length == 0)
- {
- logger.debug('Error [1]');
- return;
- }
- pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(row[0].steamid) + ' AND status = ' + pool.escape('PendingAccept') + ' AND NOT action = ' + pool.escape('winning'), function(er, ro) {
- if(er) throw er;
- if(ro.length == 0) return;
- if(ro[0].tTrades != 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: You isset an active tradeoffer.'
- });
- return;
- }
- if(!row[0].tradelink.includes('://') || !row[0].tradelink.includes('steamcommunity.com') || !row[0].tradelink.includes('partner') || !row[0].tradelink.includes('token'))
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Update your tradelink in the "my profile" page.'
- });
- return;
- }
- var botAles = Math.floor(Math.random() * (maximumBots - 1 + 1)) + 1;
- var Items = m.assets.split('/');
- var itemsToReceive = [];
- var create = bots['managers'][botAles].createOffer(row[0].steamid, row[0].tradelink.split('token=')[1]);
- bots['managers'][botAles].getUserInventoryContents(row[0].steamid, AppID, ContextID, true, function(e, inv, curr) {
- if(e) throw e;
- if(inv.length == 0)
- {
- logger.debug('Error [4]');
- return;
- }
- for(var i in Items)
- {
- for(var z in inv)
- {
- if(Items[i] == inv[z].assetid && inv[z].ss != 1)
- {
- inv[z].ss = 1;
- itemsToReceive.push(inv[z].assetid);
- }
- }
- }
- if(itemsToReceive.length == 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: You need to select items.'
- });
- return;
- }
- for(var i in itemsToReceive)
- {
- create.addTheirItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsToReceive[i]
- });
- }
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerProcessing'
- });
- var cod = makeCode();
- create.setMessage('Security code: ' + cod);
- create.send(function(ab, status) {
- if(ab)
- {
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerError',
- msg: ab.toString()
- });
- logger.trace('Line: 1359 ' + ab.toString());
- return;
- }
- var timpCreat = time();
- var timpExpire = time()+90;
- var expireIn = 0;
- if(m.expire == 1)
- {
- expireIn = 10;
- }
- else if(m.expire == 2)
- {
- expireIn = 30;
- }
- else
- {
- expireIn = 30;
- }
- logger.debug('Tradeoffer #' + create.id + ' (' + status + '; expire in: ' + expireIn + 'm) with code : ' + cod + ' has been created by steamid: ' + row[0].steamid);
- tradingRequests[create.id] = {
- action: 'newGame',
- user: row[0].steamid,
- created: timpCreat,
- expire: timpExpire,
- side: m.side,
- gameExpire: expireIn,
- botulAles: botull
- }
- pool.query('INSERT INTO trades SET user = ' + pool.escape(row[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('newGame') + ', code = ' + pool.escape(cod) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(botAles));
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerSend',
- tid: create.id,
- code: cod
- });
- });
- });
- });
- });
- }
- });
- socket.on('recentGames', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(m.csrf)
- {
- socket.emit('message', {
- type: 'updateRecentGames',
- games: CoinfliprecentGames
- });
- }
- });
- //PIN FUNCTION
- socket.on('addPin', function(m) {
- var mesaj = m.message;
- var utilizator = m.user;
- pool.query('SELECT `name`,`avatar`,`steamid`,`rank`,`mute`,`level`,`tradelink` FROM `users` WHERE `csrf_token` = ' + pool.escape(utilizator), function(err, res) {
- if(err) throw err;
- if(res.length == 0) return;
- var row = res;
- if(row[0].rank == 69)
- {
- pinnedMessages.push({
- name: row[0].name,
- avatar: row[0].avatar,
- steamid: row[0].steamid,
- rank: row[0].rank,
- level: row[0].level,
- message: mesaj
- });
- socket.emit('pinsSystem', pinSystem, pinnedMessages);
- }
- });
- });
- //CHAT FUNCTIONS
- socket.on('nMsg', function(m) {
- var mesaj = escapeHtml(m.message);
- var utilizator = m.user;
- var hide = m.hide;
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- pool.query('SELECT `name`,`avatar`,`steamid`,`rank`,`mute`,`level`,`tradelink` FROM `users` WHERE `csrf_token` = ' + pool.escape(utilizator), function(err, res) {
- if (err) throw err;
- var row = res;
- if(row.length == 0) return;
- if (mesaj.length >= 128 || mesaj.length < 2 && res[0].rank != 69) {
- if(mesaj.length >= 128)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You have exceeded the maximum characters in chat.'
- });
- }
- else if(mesaj.length < 2)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Your message is very short to send in chat.'
- });
- }
- return;
- } else {
- if (antiSpamChat[res[0].steamid] + 2 >= time() && res[0].rank != 69) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: You need to wait before sending another message.'
- });
- return;
- } else {
- antiSpamChat[res[0].steamid] = time();
- }
- var caca = null;
- if (caca = /^\/clear/.exec(mesaj)) {
- if (row[0].rank == 69 || row[0].rank == 92) {
- io.sockets.emit('message', {
- type: 'addMessage',
- tip: 'clear',
- name: 'Alert',
- rank: '0',
- avatar: 'favicon.ico',
- hide: true,
- msg: 'Chat was cleared by Admin ' + row[0].name + '.'
- });
- chatMessages = [];
- logger.trace('Chat: Cleared by Admin ' + row[0].name + '.');
- }
- } else if (caca = /^\/spooky ([0-9]*)/.exec(mesaj)) {
- if (row[0].rank == 69) {
- if(caca[1])
- {
- if(socketBySteam.hasOwnProperty(caca[1]))
- {
- if(io.sockets.connected[socketBySteam[caca[1]]['info']])
- {
- io.sockets.connected[socketBySteam[caca[1]]['info']].emit('spooky');
- }
- }
- }
- }
- } else if (caca = /^\/mute ([0-9]*) ([0-9]*)/.exec(mesaj)) {
- if (row[0].rank == 69 || row[0].rank == 92) {
- var t = time();
- pool.query('UPDATE `users` SET `mute` = ' + pool.escape(parseInt(t) + parseInt(caca[2])) + ' WHERE `steamid` = ' + pool.escape(caca[1]), function(err2, row2) {
- if (err2) throw err2;
- if (row2.affectedRows == 0) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Steamid not found in database.'
- });
- logger.trace('Mute: Steamid not found in database (' + caca[1] + ').');
- return;
- }
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'You have muted user for ' + caca[2] + ' seconds.'
- });
- logger.trace('Mute: Steamid ' + caca[1] + ' has been muted for ' + caca[2] + ' seconds by ' + row[0].name + ' (' + row[0].steamid + ').');
- });
- }
- } else if (caca = /^\/hidegame ([0-9]*)/.exec(mesaj)) {
- if (row[0].rank == 69) {
- hideGame(caca[1]);
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Successfully hided game #' + caca[1] + '!'
- });
- logger.trace('Hide: Admin ' + row[0].name + ' hided game #' + caca[1]);
- }
- } else if (caca = /^\/spin ([0-9]*)/.exec(mesaj)) {
- if (row[0].rank == 69) {
- if(caca[1] == 1)
- {
- pinSystem = true;
- socket.emit('pinsSystem', pinSystem, pinnedMessages);
- }
- else if(caca[1] == 0)
- {
- pinSystem = false;
- socket.emit('pinsSystem', pinSystem, pinnedMessages);
- }
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Successfully changed the pin system to ' + caca[1]
- });
- logger.trace('Chat: Admin ' + row[0].name + ' changed the pin system to ' + caca[1]);
- }
- } else if (caca = /^\/dpin/.exec(mesaj)) {
- if (row[0].rank == 69) {
- pinSystem = false;
- pinnedMessages = [];
- socket.emit('pinsSystem', pinSystem, pinnedMessages);
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Successfully deleted the pins'
- });
- logger.trace('Chat: Admin ' + row[0].name + ' deleted the pins.');
- }
- } else {
- if (row[0].mute > time() && row[0].mute != 0) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You are muted (seconds remaining: ' + parseInt(row[0].mute - time()) + ').'
- });
- logger.trace('Mute: ' + row[0].name + ' (' + row[0].steamid + ') tried to speak (' + mesaj + ') while muted (seconds remaining: ' + parseInt(row[0].mute - time()) + ').');
- return;
- }
- if (chatMessages.length > 20) {
- chatMessages.shift();
- }
- chatMessages.push({
- name: res[0].name,
- avatar: res[0].avatar,
- steamid: res[0].steamid,
- rank: res[0].rank,
- hide: hide,
- level: res[0].level,
- message: mesaj
- });
- io.sockets.emit('message', {
- type: 'addMessage',
- msg: mesaj,
- avatar: res[0].avatar,
- steamid: res[0].steamid,
- rank: res[0].rank,
- hide: hide,
- level: res[0].level,
- name: res[0].name
- });
- logger.trace('Chat: Message from ' + row[0].name + ' (SID: ' + row[0].steamid + ', IP: ' + address + ', hide: ' + hide + ') --> ' + mesaj);
- }
- }
- });
- });
- socket.on('disconnect', function() {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(usersOnline[address])
- {
- delete usersOnline[address];
- }
- io.sockets.emit('message', {
- type: 'connections',
- total: Object.keys(usersOnline).length
- });
- });
- socket.on('setTlink', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(m.csrf)
- {
- if(m.tradelink.includes('://') && m.tradelink.includes('token=') && m.tradelink.includes('partner='))
- {
- pool.query('UPDATE users SET tradelink = ' + pool.escape(m.tradelink) + ' WHERE csrf_token = ' + pool.escape(m.csrf));
- socket.emit('message', {
- type: 'msg',
- tip: 'alert',
- msg: 'Your tradelink has been updated!'
- });
- }
- else
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You need to type a correct tradelink!'
- });
- }
- }
- });
- //CHAT FUNCTIONS
- socket.on('watchGame', function(m) {
- pool.query('SELECT * FROM games WHERE id = ' + pool.escape(m.gameid), function(error, results) {
- if(error) throw error;
- socket.emit('message', {
- type: 'watchCF',
- id: results[0].id,
- cname: results[0].cname,
- cavatar: results[0].cavatar,
- cskinsurl: results[0].cskinsurl,
- cskinsnames: results[0].cskinsnames,
- cskinsprices: results[0].cskinsprices,
- cskins: results[0].cskins,
- ctp: results[0].ctp,
- pname: results[0].pname,
- pavatar: results[0].pavatar,
- pskinsurl: results[0].pskinsurl,
- pskinsnames: results[0].pskinsnames,
- pskinsprices: results[0].pskinsprices,
- pskins: results[0].pskins,
- ptp: results[0].ptp,
- hash: results[0].hash,
- secret: results[0].secret,
- winner: results[0].winner,
- cpick: results[0].cpick,
- ppick: results[0].ppick,
- timer: timerGame[results[0].id]-time(),
- timer11: results[0].timer11,
- ttimer11: timer11Game[results[0].id]-time(),
- winnerPercentage: results[0].winnerPercentage,
- gameNumber: m.gameid,
- expire: results[0].expire-time()
- });
- });
- });
- socket.on('joingame', function(m) {
- var address = socket.client.request.headers['x-forwarded-for'] || socket.request.connection.remoteAddress;
- if(coolDown[address]+2 >= time()) {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Please, stop flooding!'
- });
- return;
- } else {
- coolDown[address] = time();
- }
- if(antiFlood[socket]+2 >= time()) {
- timesFlooding[socket] += 1;
- if(timesFlooding[socket] == 3)
- {
- delete timesFlooding[socket];
- socket.disconnect();
- return;
- }
- return;
- } else {
- antiFlood[socket] = time();
- }
- if(!m.game)
- {
- return;
- }
- var assetids = m.assetids.split('/');
- var gameID = m.game;
- var user_hash = m.csrf;
- pool.query('SELECT id,trade_token,csteamid,cpick,expire,bot FROM games WHERE id = ' + pool.escape(gameID), function(error, results) {
- if(error) throw errorl
- if(results[0].trade_token)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Someone already joined in this game!'
- });
- return;
- }
- /*if(results[0].expire-time() <= 20)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'This game will expire in ~20 seconds. You cannot join!'
- });
- return;
- }*/
- if(results[0].id)
- {
- pool.query('SELECT name,steamid,avatar,tradelink,rank FROM users WHERE csrf_token = ' + pool.escape(user_hash), function(error1, results1) {
- if(error1) throw error1;
- pool.query('SELECT COUNT(`id`) AS tTrades FROM trades WHERE user = ' + pool.escape(results1[0].steamid) + ' AND status = ' + pool.escape('PendingAccept') + ' AND NOT action = ' + pool.escape('winning'), function(ca, ma) {
- if(ca) throw ca;
- if(ma.length == 0) return;
- if(ma[0].tTrades != 0)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'You isset an active tradeoffer.'
- });
- return;
- }
- if(!results[0] || !results1[0])
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Unexpected error, contact an administrator!'
- });
- return;
- }
- if(results[0].csteamid == results1[0].steamid && results1[0].rank != 69)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: You cannot join your own game!'
- });
- return;
- }
- if(results1[0].name || results1[0].steamid || results1[0].avatar)
- {
- var totalAmount = 0;
- var totalItems = 0;
- //ITEMS INFO
- var skinImages = [];
- var skinNames = [];
- var skinPrices = [];
- //ITEMS INFO
- var minPriceDet = 0;
- if(!results1[0].tradelink.includes('://') || !results1[0].tradelink.includes('steamcommunity.com') || !results1[0].tradelink.includes('partner') || !results1[0].tradelink.includes('token'))
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Update your tradelink in the "my profile" page.'
- });
- return;
- }
- var toContinue = 0;
- var create = bots['managers'][results[0].bot].createOffer(results1[0].steamid, results1[0].tradelink.split('token=')[1]);
- var itemsLength = [];
- bots['managers'][results[0].bot].getUserInventoryContents(results1[0].steamid, AppID, ContextID, true, function(err, inv, currencies) {
- for(i = 0; i < inv.length; i++) {
- for(a=0; a < assetids.length; a++)
- {
- if(minPriceDet == 0)
- {
- if(inv[i].assetid == assetids[a] && inv[i].ss != 1)
- {
- inv[i].ss = 1;
- skinImages.push(inv[i].icon_url);
- skinNames.push(inv[i].market_hash_name);
- skinPrices.push(getPriceItem(inv[i].market_hash_name));
- if(getPriceItem(inv[i].market_hash_name) < minDep)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Do not force system [min price $' + minDep + '].'
- });
- minPriceDet = 1;
- toContinue = 1;
- return;
- }
- else
- {
- totalItems++;
- totalAmount += getPriceItem(inv[i].market_hash_name);
- itemsLength.push(inv[i].assetid);
- }
- }
- }
- }
- }
- if(totalItems == 0 || totalItems > 25)
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Min. items per trade: 1 and max. items per trade: 25!'
- });
- return;
- }
- pool.query('SELECT `ctp` FROM games WHERE id = ' + pool.escape(gameID), function(eroare, resultate) {
- if(eroare) throw eroare;
- if(resultate[0].ctp)
- {
- var calculare = 10/100*resultate[0].ctp;
- var Gap01 = parseFloat(resultate[0].ctp - calculare).toFixed(2);
- var Gap02 = parseFloat(resultate[0].ctp + calculare).toFixed(2);
- if(totalAmount < Gap01 || totalAmount > Gap02)
- {
- toContinue = 1;
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Minimum amount required: $' + Gap01 + ' or total amount required: $' + Gap02 + '. Your amount: $' + totalAmount
- });
- return;
- }
- }
- else
- {
- toContinue = 1;
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: Invalid game!'
- });
- return;
- }
- if(toContinue == 0)
- {
- for(var b = 0; b < itemsLength.length; b++)
- {
- create.addTheirItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsLength[b]
- });
- }
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerProcessing'
- });
- var cod = makeCode();
- create.setMessage("Security code: " + cod);
- pool.query('UPDATE games SET scode = ' + pool.escape(cod) + ' WHERE id = ' + pool.escape(gameID));
- create.send(function(err, status) {
- if(err)
- {
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerError',
- msg: err.toString()
- });
- return;
- }
- else
- {
- //INFO ITEMS
- var Skinimages = skinImages.join('/');
- var Skinnames = skinNames.join('/');
- var Skinprices = skinPrices.join('/');
- var timpCreat = time();
- var timpExpire = time()+90;
- gamesPending[create.id] = results1[0].steamid;
- tradingRequests[create.id] = {
- action: 'joingame',
- user: results1[0].steamid,
- created: timpCreat,
- expire: timpExpire,
- gameExpire: results[0].expire,
- gameID: results[0].id
- }
- socket.emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerSend',
- tid: create.id,
- code: cod
- });
- pool.query('INSERT INTO trades SET user = ' + pool.escape(results1[0].steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('joingame') + ', code = ' + pool.escape(cod) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(results[0].bot));
- var ppick = '';
- if(results[0].cpick == 'ct')
- {
- ppick = 't';
- }
- else if(results[0].cpick == 't')
- {
- ppick = 'ct';
- }
- gameJoinedExpire[gameID] = {
- 'id': gameID,
- 'remove': time()+90,
- 'offer': create
- };
- pool.query('SELECT hash FROM games WHERE id = ' + pool.escape(gameID), function(err1, res1) {
- if(err1) throw err1;
- logger.info('Joined game #' + gameID + ', player steamid: ' + results1[0].steamid + ' (' + results1[0].name + ')');
- pool.query('UPDATE `games` SET `psteamid` = ' + pool.escape(results1[0].steamid) + ', `pname` = ' + pool.escape(results1[0].name) + ', `pavatar` = ' + pool.escape(results1[0].avatar) + ', `pskinsurl` = ' + pool.escape(Skinimages) + ', `pskinsnames` = ' + pool.escape(Skinnames) + ', `pskinsprices` = ' + pool.escape(Skinprices) + ', `pskins` = ' + pool.escape(totalItems) + ', `ppick` = ' + pool.escape(ppick) + ', `ptp` = ' + pool.escape(totalAmount) + ', `trade_token` = ' + pool.escape(create.id) + ' WHERE `id` = ' + pool.escape(gameID));
- loadAllGames();
- sendGames(gameID);
- });
- }
- });
- }
- });
- });
- }
- else
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: User_id not found! Hacked.'
- });
- }
- });
- });
- }
- else
- {
- socket.emit('message', {
- type: 'msg',
- tip: 'error',
- msg: 'Error: This game does not exists!'
- });
- }
- });
- });
- });
- function hideGame(gameID)
- {
- pool.query('UPDATE games SET `ended` = 1 WHERE `id` = ' + pool.escape(gameID), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- pool.query('SELECT * FROM games WHERE id = ' + pool.escape(gameID), function(aaa, bbb) {
- if(aaa) throw aaa;
- if(bbb.length == 0) return;
- CoinfliprecentGames.unshift(bbb[0]);
- CoinfliprecentGames.pop();
- });
- });
- loadAllGames();
- setTimeout(function() {
- io.sockets.emit('message', {
- type: 'removeGame',
- id: gameID
- });
- }, 1000);
- }
- function getPriceItem(name)
- {
- var priceItem = 0;
- if (name) {
- var prices = require('./prices.json');
- priceItem = prices[name];
- }
- return priceItem;
- }
- /*
- Getting prices
- */
- var priceUrl = 'https://api.csgofast.com/price/all';
- function getPriceList() {
- request(priceUrl, function(dataAndEvents, r, actual) {
- ok = JSON.parse(actual);
- if (200 != r.statusCode) {
- if (fs.existsSync("./prices.json")) {
- ok = JSON.parse(fs.readFileSync("./prices.json"));
- logger.trace("[SERVER] Loading Prices - Server sided prices loaded!");
- }
- } else {
- fs.writeFileSync("./prices.json", actual);
- logger.trace("[SERVER] Loading Prices - API prices loaded!");
- }
- });
- }
- function PriceOfItem(offer)
- {
- var priceItem = 0;
- if (offer) {
- var prices = require('./prices.json');
- priceItem = prices[offer.market_hash_name];
- }
- return priceItem;
- }
- getPriceList();
- setInterval(getPriceList, config.options.priceRefreshInterval * 1000);
- /*
- Offer handling
- */
- function isInArray(value, array) {
- return array.indexOf(value) > -1;
- }
- function acceptOffer(offer) {
- offer.accept((err) => {
- if (err) logger.error('Unable to accept offer: ' + err);
- logger.info('Trade offer #' + offer.id + ' accepted.');
- });
- }
- function declineOffer(offer) {
- offer.decline((err) => {
- if (err) return logger.error('Unable to decline offer: ' + err);
- logger.info('Trade offer #' + offer.id + ' declined.');
- });
- }
- function verifyGame()
- {
- for(var k in gameJoinedExpire)
- {
- if(gameJoinedExpire[k]['remove'] <= time())
- {
- var oferta = gameJoinedExpire[k]['offer'];
- oferta.decline((err) => {
- if(err) return;
- pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(oferta.id), function(err2, res2) {
- if(err2) throw err2;
- loadAllGames();
- sendGames(res[0].id);
- logger.info('Game joining cancelled because the second player did not accept in time trade offer #' + oferta.id);
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(oferta.id));
- });
- });
- }
- }
- }
- function pickJackpotWinner()
- {
- setTimeout(function() {
- var wooble = Math.floor(Math.random() * (9510 - 9420 + 1)) + 9420;
- var winnerPercentage = Math.random() * (99.9999999999 - 0.0000000001) + 0.0000000001;
- var winnerTicket = Math.floor((jackpotTickets - 0.0000000001) * (winnerPercentage / 100));
- var secondsRotate = Math.floor(Math.random() * (13000 - 8900 + 1)) + 8900;
- var winSteamid;
- var avatarWin;
- var nameWin;
- var isAdded = [];
- var winnerInfo = [];
- jackpotNextRoundTime = time()+(secondsRotate/1000)+12;
- jackpotInt = setInterval(function() {
- if(jackpotNextRoundTime-time() <= 0)
- {
- nextJackpotRound();
- //logger.trace('JACKPOT -> new round started!');
- clearInterval(jackpotInt);
- }
- });
- //logger.trace('JACKPOT -> winner percentage: ' + winnerPercentage + '; winner ticket: ' + winnerTicket);
- jackpotTotalTickets.forEach(function (i) {
- //logger.trace('JACKPOT -> ticket number: ' + i['ticket'] + ' and user ' + i['user']);
- if(i['ticket'] == winnerTicket)
- {
- //logger.info('JACKPOT -> ticket number won: ' + i['ticket'] + ' and user ' + i['user']);
- winSteamid = i['user'];
- pool.query('SELECT name, avatar FROM users WHERE steamid = ' + pool.escape(winSteamid), function(e, r) {
- if(e) {logger.error(e); return;}
- //if(r.length == 0) {logger.error('SELECT ticketname.'); return;}
- avatarWin = r[0].avatar;
- nameWin = r[0].name;
- winnerInfo.push({
- "avatar": avatarWin,
- "name": nameWin,
- "steamid": winSteamid,
- "chance": parseFloat(100 - ((totalJackpotValue-usersPrices[winSteamid])/totalJackpotValue)*100).toFixed(2),
- "pot": totalJackpotValue,
- "secret": jackpotSecret,
- "winnerPercentage": winnerPercentage
- });
- var users_avatars_pot = [];
- var users_names_pot = [];
- for(var i = 0; i < 103; i++)
- {
- var randomUser = Math.floor(Math.random() * (jackpotTotalTickets.length-1 - 1 + 1)) + 1;
- for(var z in JackpotUsers)
- {
- if(jackpotTotalTickets[randomUser]['user'] == JackpotUsers[z]['userInfo']['steamid'] && isAdded[i] != 1)
- {
- isAdded[i] = 1;
- if(i == 92)
- {
- users_avatars_pot.push(avatarWin);
- users_names_pot.push(nameWin);
- continue;
- }
- users_avatars_pot.push(JackpotUsers[z]['userInfo']['avatar']);
- users_names_pot.push(JackpotUsers[z]['userInfo']['name']);
- }
- }
- }
- pool.query('UPDATE jgames SET pot = ' + pool.escape(parseFloat(totalJackpotValue).toFixed(2)) + ', items = ' + pool.escape(totalJackpotItems) + ', tickets = ' + pool.escape(jackpotTickets) + ', winnerTicket = ' + pool.escape(winnerTicket) + ', ended = 1 WHERE id = ' + pool.escape(jackpotRound));
- setTimeout(function() {
- io.sockets.emit('message', {
- type: 'spinJackpot',
- seconds: secondsRotate,
- wooble: wooble,
- users_avatars: users_avatars_pot.join('|'),
- users_names: users_names_pot.join('|'),
- winner: winnerInfo
- });
- setTimeout(function() {
- pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(winSteamid), function(a, b) {
- if(a) {logger.error(a); return;}
- if(b.length == 0) {logger.error('Error inv [tradelinkSteamid]'); return;}
- var itemsToSend = [];
- for(var i in JackpotUsers)
- {
- for(var z in JackpotUsers[i]['itemsInfo'])
- {
- itemsToSend.push(JackpotUsers[i]['itemsInfo'][z]['id']);
- }
- }
- sendJackpotItems(winSteamid, b[0].tradelink, itemsToSend, nameWin);
- //logger.trace('JACKPOT -> Winner got trade');
- });
- }, secondsRotate+1000);
- }, 2000);
- });
- }
- });
- }, 2500);
- }
- function sendJackpotItems(steamid, tradelink, items, name)
- {
- var create = defBot.createOffer(steamid, tradelink.split('token=')[1]);
- var cod = makeCode();
- create.setMessage('Your winnings from jackpot round #' + jackpotRound + '. Security code: ' + cod);
- var totalPrice = 0;
- var itemss = items;
- var Items = [];
- bots['managers'][jackpotBot].loadInventory(AppID, ContextID, true, function(err, inv, curr) {
- if(err) {logger.error(err); return;}
- if(inv.length == 0) {logger.error('Error inv [jackpot]'); return;}
- var pretul = require('./prices.json');
- var itemsDB = [];
- for(var i in inv)
- {
- for(var z in itemss)
- {
- if(inv[i].assetid == itemss[z] && itemss[z].ss != 1)
- {
- itemss[z].ss = 1;
- totalPrice += parseFloat(pretul[inv[i].market_hash_name]);
- Items.push({
- 'name': inv[i].market_hash_name,
- 'price': pretul[inv[i].market_hash_name],
- 'assetid': inv[i].assetid
- });
- }
- }
- }
- var maxComission = jackpotPRake/100*(totalPrice.toFixed(2));
- var currComission = 0.00;
- if(/(CSGOCombine.com|csgocombine.com|CSGOCOMBINE.COM)/.exec(name))
- {
- maxComission = (jackpotPRake - 2)/100*(totalPrice.toFixed(2));
- }
- for(var i in Items)
- {
- if(Items[i].price <= maxComission && ((currComission+Items[i].price) <= maxComission))
- {
- currComission += parseFloat(Items[i].price);
- Items[i].remove = 1;
- //logger.trace('[Script check nr. 1] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') removed from Items array.');
- }
- else
- {
- Items[i].added = 1;
- //logger.trace('[Script check nr. 1] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') added to Items array.');
- }
- }
- for(var i in Items)
- {
- if(Items[i].added == 1)
- {
- itemsDB.push(Items[i].assetid);
- //logger.trace('[Script check nr. 2] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') added to itemsDB array.');
- }
- else if(Items[i].remove == 1)
- {
- //logger.trace('[Script check nr. 2] - ' + Items[i].price + ' (' + Items[i].assetid + ' - ' + Items[i].name + ') removed from itemsDB array.');
- }
- }
- for(var i in itemsDB)
- {
- create.addMyItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsDB[i]
- });
- }
- create.send(function(cc, sts) {
- if(cc)
- {
- logger.error(cc);
- return;
- }
- else
- {
- logger.trace('[Winner-jackpot: ' + steamid + ' (' + name + ') ] Offer #' + create.id + " " + sts);
- var timpCreat = time();
- var timpExpired = time()+90;
- tradingRequests[create.id] = {
- action: 'winning',
- user: steamid,
- created: timpCreat,
- expired: timpExpired
- };
- pool.query('INSERT INTO trades SET user = ' + pool.escape(steamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('winning') + ', code = ' + pool.escape(cod) + ', items = ' + pool.escape(itemsDB.join('/')) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpired) + ', bot = ' + pool.escape(jackpotBot));
- }
- });
- });
- }
- function sendItemsTrade(offer, items, winner, numeleItm, idsItm, priceItm)
- {
- pool.query('SELECT id,cskinsnames,winner,csteamid,psteamid,cname,pname,cskinsprices,ctp,ptp,cassetids,cpick,ppick,bot FROM games WHERE trade_token = ' + pool.escape(offer), function(err, res) {
- if(err) throw err;
- setTimeout(function() {
- hideGame(res[0].id);
- }, 60000);
- var ItemsRake = [];
- var Skins1Names = res[0].cskinsnames.split('/');
- var Skins2Names = numeleItm;
- var TotalSkinsNames = Skins1Names.concat(Skins2Names);
- var Skins1 = res[0].cassetids.split('/');
- var Skins2 = idsItm;
- var allSkins = Skins1.concat(Skins2);
- var Prices1 = res[0].cskinsprices.split('/');
- var Prices2 = priceItm;
- var allPrices = Prices1.concat(Prices2);
- var itemsDB = [];
- var maxComission = percentRake/100*(res[0].ctp+res[0].ptp);
- var currComission = 0.00;
- var partner;
- var numele;
- if(winner == 'ct' && res[0].cpick == 'ct')
- {
- partner = res[0].csteamid;
- numele = res[0].cname;
- }
- else if(winner == 't' && res[0].ppick == 't')
- {
- partner = res[0].psteamid;
- numele = res[0].pname;
- }
- else if(winner == 'ct' && res[0].ppick == 'ct')
- {
- partner = res[0].psteamid;
- numele = res[0].pname;
- }
- else if(winner == 't' && res[0].cpick == 't')
- {
- partner = res[0].csteamid;
- numele = res[0].cname;
- }
- if(/(CSGOCombine.com|csgocombine.com|CSGOCOMBINE.COM)/.exec(numele))
- {
- maxComission = (percentRake - 2)/100*(res[0].ctp+res[0].ptp);
- }
- for(var i in allSkins)
- {
- ItemsRake.push({
- assetid: allSkins[i],
- price: allPrices[i],
- name: TotalSkinsNames[i]
- });
- }
- for(var i in ItemsRake)
- {
- if(ItemsRake[i].price <= maxComission && ((currComission+ItemsRake[i].price) <= maxComission))
- {
- currComission += parseFloat(ItemsRake[i].price);
- ItemsRake[i].remove = 1;
- //logger.trace('[Script check nr. 1] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') removed from ItemsRake array.');
- }
- else
- {
- ItemsRake[i].added = 1;
- //logger.trace('[Script check nr. 1] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') added to ItemsRake array.');
- }
- }
- for(var i in ItemsRake)
- {
- if(ItemsRake[i].added == 1)
- {
- itemsDB.push(ItemsRake[i].assetid);
- //logger.trace('[Script check nr. 2] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') added to itemsDB array.');
- }
- else if(ItemsRake[i].remove == 1)
- {
- //logger.trace('[Script check nr. 2] - ' + ItemsRake[i].price + ' (' + ItemsRake[i].assetid + ' - ' + ItemsRake[i].name + ') removed from itemsDB array.');
- }
- }
- pool.query('SELECT tradelink FROM users WHERE steamid = ' + pool.escape(partner), function(eroare, success) {
- if(eroare) throw eroare;
- if(success.length == 0) return;
- var create = bots['managers'][res[0].bot].createOffer(partner, success[0].tradelink.split('token=')[1]);
- for(var i in itemsDB)
- {
- create.addMyItem({
- "appid": AppID,
- "contextid": ContextID,
- "assetid": itemsDB[i]
- });
- }
- var cod = makeCode();
- create.setMessage('Security code: ' + cod);
- create.send(function(err, status) {
- if(err)
- {
- logger.error(err);
- var WSteamid;
- var WName;
- pool.query('UPDATE games SET sentItems = 1, wcode = ' + pool.escape(cod) + ' WHERE trade_token = ' + pool.escape(offer.id));
- if(winner == 'ct' && res[0].cpick == 'ct')
- {
- WSteamid = res[0].csteamid;
- WName = res[0].cname;
- }
- else if(winner == 't' && res[0].ppick == 't')
- {
- WSteamid = res[0].psteamid;
- WName = res[0].pname;
- }
- else if(winner == 'ct' && res[0].ppick == 'ct')
- {
- WSteamid = res[0].psteamid;
- WName = res[0].pname;
- }
- else if(winner == 't' && res[0].cpick == 't')
- {
- WSteamid = res[0].csteamid;
- WName = res[0].cname;
- }
- var timpCreat = time();
- var timpExpire = time()+90;
- logger.trace('[Winner: ' + WSteamid + ' (' + WName + ') ] Offer #' + create.id + " " + status);
- pool.query('INSERT INTO trades SET user = ' + pool.escape(WSteamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('winning') + ', code = ' + pool.escape(cod) + ', items = ' + pool.escape(itemsDB.join('/')) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(res[0].bot), function(abc, cba) {
- if(abc) throw abc;
- if(cba.length == 0) return;
- logger.info('Trade #' + create.id + ' has been added to database!');
- });
- return;
- }
- else
- {
- var WSteamid;
- var WName;
- pool.query('UPDATE games SET sentItems = 1, wcode = ' + pool.escape(cod) + ' WHERE trade_token = ' + pool.escape(offer.id));
- if(winner == 'ct' && res[0].cpick == 'ct')
- {
- WSteamid = res[0].csteamid;
- WName = res[0].cname;
- }
- else if(winner == 't' && res[0].ppick == 't')
- {
- WSteamid = res[0].psteamid;
- WName = res[0].pname;
- }
- else if(winner == 'ct' && res[0].ppick == 'ct')
- {
- WSteamid = res[0].psteamid;
- WName = res[0].pname;
- }
- else if(winner == 't' && res[0].cpick == 't')
- {
- WSteamid = res[0].csteamid;
- WName = res[0].cname;
- }
- logger.trace('[Winner: ' + WSteamid + ' (' + WName + ') ] Offer #' + create.id + " " + status);
- var timpCreat = time();
- var timpExpire = time()+90;
- tradingRequests[create.id] = {
- action: 'winning',
- user: WSteamid,
- created: timpCreat,
- expire: timpExpire
- };
- pool.query('INSERT INTO trades SET user = ' + pool.escape(WSteamid) + ', tid = ' + pool.escape(create.id) + ', status = ' + pool.escape('PendingAccept') + ', action = ' + pool.escape('winning') + ', code = ' + pool.escape(cod) + ', items = ' + pool.escape(itemsDB.join('/')) + ', created = ' + pool.escape(timpCreat) + ', expired = ' + pool.escape(timpExpire) + ', bot = ' + pool.escape(defBot2), function(abc, cba) {
- if(abc) throw abc;
- if(cba.length == 0) return;
- logger.info('Trade #' + create.id + ' has been added to database!');
- });
- if(gamesPending.hasOwnProperty(offer.id))
- {
- delete gamesPending[offer.id];
- }
- }
- });
- loadAllGames();
- sendGames(res[0].id);
- setTimeout(function() {
- loadStatistics();
- }, 5000);
- });
- });
- }
- function time()
- {
- return parseInt(new Date().getTime()/1000);
- }
- function addHistory(socket)
- {
- chatMessages.forEach(function(itm) {
- socket.emit('message', {
- type: 'addMessage',
- msg: itm.message,
- avatar: itm.avatar,
- steamid: itm.steamid,
- rank: itm.rank,
- hide: itm.hide,
- level: itm.level,
- name: itm.name
- });
- })
- }
- function makeCode() {
- var text = "";
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- for(var i=0; i < 6; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- return text;
- }
- function makeHash()
- {
- var text = "";
- var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
- for(var i=0; i < 32; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- return text;
- }
- function makeSecret()
- {
- var data = 'CSGO-' + time() + '-' + Math.floor(Math.random() * 500);
- var hashess = crypto.createHash('md5').update(data).digest("hex");
- return hashess;
- }
- function getProxy()
- {
- return "http://" + proxies[random(0,proxies.length-1)];
- }
- function random(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- }
- function getInv(user, socket)
- {
- var pret = require('./prices.json');
- var reqOpts = {
- url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
- };
- request(reqOpts, function(err, response, body) {
- if(err) throw err;
- if(response && response.statusCode == 200)
- {
- var bodiul = JSON.parse(body);
- var assets = bodiul['assets'];
- var descriptions = bodiul['descriptions'];
- var counter = 0;
- var idss = [];
- var namess = [];
- var pricess = [];
- var imgss = [];
- var Ids = '';
- var Names = '';
- var Prices = '';
- var Imgs = '';
- if(!assets) return;
- assets.forEach(function(valuey, y) {
- descriptions.forEach(function(valuez, z) {
- if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
- {
- var isTradable = valuez['tradable'];
- if(isTradable == 1)
- {
- var id = valuey['assetid'];
- var name = valuez['market_hash_name'];
- var price = pret[valuez['market_hash_name']];
- var img = valuez['icon_url'];
- if(price >= minDep)
- {
- idss.push(id);
- namess.push(name);
- pricess.push(price);
- imgss.push(img);
- }
- }
- }
- });
- });
- Ids = idss.join('/');
- Names = namess.join('/');
- Prices = pricess.join('/');
- Imgs = imgss.join('/');
- socket.emit('message', {
- type: 'getInventory',
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- });
- inventoryUser[user] = {
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- }
- }
- else
- {
- }
- });
- }
- function getInv2(user, socket)
- {
- var pret = require('./prices.json');
- var reqOpts = {
- url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
- };
- request(reqOpts, function(err, response, body) {
- if(err) throw err;
- if(response && response.statusCode == 200)
- {
- var bodiul = JSON.parse(body);
- var assets = bodiul['assets'];
- var descriptions = bodiul['descriptions'];
- var counter = 0;
- var idss = [];
- var namess = [];
- var pricess = [];
- var imgss = [];
- var Ids = '';
- var Names = '';
- var Prices = '';
- var Imgs = '';
- var Gamess = [];
- if(!assets) return;
- assets.forEach(function(valuey, y) {
- descriptions.forEach(function(valuez, z) {
- if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
- {
- var isTradable = valuez['tradable'];
- if(isTradable == 1)
- {
- var id = valuey['assetid'];
- var name = valuez['market_hash_name'];
- var price = pret[valuez['market_hash_name']];
- var img = valuez['icon_url'];
- if(price >= minDep)
- {
- idss.push(id);
- namess.push(name);
- pricess.push(price);
- imgss.push(img);
- }
- }
- }
- });
- });
- Ids = idss.join('/');
- Names = namess.join('/');
- Prices = pricess.join('/');
- Imgs = imgss.join('/');
- socket.emit('message', {
- type: 'getInventory2',
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- });
- inventoryUser[user] = {
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- }
- }
- else
- {
- }
- });
- }
- function jgetInv(user, socket)
- {
- var pret = require('./prices.json');
- if(config['proxyON'] == true)
- {
- var reqOpts = {
- url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000',
- proxy: getProxy()
- };
- }
- else
- {
- var reqOpts = {
- url: 'http://steamcommunity.com/inventory/' + encodeURIComponent(user) + '/' + AppID + '/' + ContextID + '?l=eng&count=5000'
- };
- }
- request(reqOpts, function(err, response, body) {
- if(err) throw err;
- if(response && response.statusCode == 200)
- {
- var bodiul = JSON.parse(body);
- var assets = bodiul['assets'];
- var descriptions = bodiul['descriptions'];
- var counter = 0;
- var idss = [];
- var namess = [];
- var pricess = [];
- var imgss = [];
- var Ids = '';
- var Names = '';
- var Prices = '';
- var Imgs = '';
- if(!assets) return;
- assets.forEach(function(valuey, y) {
- descriptions.forEach(function(valuez, z) {
- if(valuey['classid'] == valuez['classid'] && valuey['instanceid'] == valuez['instanceid'])
- {
- var isTradable = valuez['tradable'];
- if(isTradable == 1)
- {
- var id = valuey['assetid'];
- var name = valuez['market_hash_name'];
- var price = pret[valuez['market_hash_name']];
- var img = valuez['icon_url'];
- if(price >= minDep)
- {
- idss.push(id);
- namess.push(name);
- pricess.push(price);
- imgss.push(img);
- }
- }
- }
- });
- });
- Ids = idss.join('/');
- Names = namess.join('/');
- Prices = pricess.join('/');
- Imgs = imgss.join('/');
- socket.emit('message', {
- type: 'jgetInventory',
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- });
- JinventoryUser[user] = {
- id: Ids,
- name: Names,
- price: Prices,
- img: Imgs
- }
- }
- else
- {
- }
- });
- }
- function loadStatistics(socket)
- {
- var totalAmount = 0;
- var totalItems = 0;
- var activeGames = 0;
- pool.query('SELECT SUM(`ctp`) AS `totalAmount`, SUM(`cskins`) AS `totalItems`, COUNT(`id`) AS `activeGames` FROM games WHERE `winner` = -1', function(error, res) {
- if(error) throw error;
- if(res.length == 0)
- {
- totalAmount = 0;
- totalItems = 0;
- activeGames = 0;
- if(!socket)
- {
- io.sockets.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- else
- {
- socket.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- }
- if(res.length > 0)
- {
- totalAmount = res[0].totalAmount;
- totalItems = res[0].totalItems;
- activeGames = res[0].activeGames;
- if(totalAmount == null)
- {
- totalAmount = 0;
- }
- if(totalItems == null)
- {
- totalItems = 0;
- }
- if(activeGames == null)
- {
- activeGames = 0;
- }
- if(!socket)
- {
- io.sockets.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- else
- {
- socket.emit('message', {
- type: 'loadStatistics',
- totalAmount: totalAmount,
- totalItems: totalItems,
- activeGames: activeGames
- });
- }
- }
- });
- }
- function sendGames(gameID)
- {
- setTimeout(function() {
- for(var i in loadGames)
- {
- if(loadGames[i].id == gameID)
- {
- timerGame[loadGames[i].id] = time()+90;
- io.sockets.emit('message', {
- type: 'editGame',
- games: {
- 'id': loadGames[i].id,
- 'csteamid': loadGames[i].csteamid,
- 'cname': loadGames[i].cname,
- 'cavatar': loadGames[i].cavatar,
- 'cskinsurl': loadGames[i].cskinsurl,
- 'cskinsnames': loadGames[i].cskinsnames,
- 'cskinsprices': loadGames[i].cskinsprices,
- 'cskins': loadGames[i].cskins,
- 'ctp': loadGames[i].ctp,
- 'psteamid': loadGames[i].psteamid,
- 'pname': loadGames[i].pname,
- 'pavatar': loadGames[i].pavatar,
- 'pskinsurl': loadGames[i].pskinsurl,
- 'pskinsnames': loadGames[i].pskinsnames,
- 'pskinsprices': loadGames[i].pskinsprices,
- 'pskins': loadGames[i].pskins,
- 'ptp': loadGames[i].ptp,
- 'hash': loadGames[i].hash,
- 'secret': loadGames[i].secret,
- 'winnerPercentage': loadGames[i].winnerPercentage,
- 'cpick': loadGames[i].cpick,
- 'ppick': loadGames[i].ppick,
- 'winner': loadGames[i].winner,
- 'timer': timerGame[loadGames[i].id]-time(),
- 'timer11': loadGames[i].timer11,
- 'ttimer11': timer11Game[loadGames[i].id]-time(),
- }
- });
- io.sockets.emit('message', {
- type: 'watchCF',
- id: loadGames[i].id,
- csteamid: loadGames[i].csteamid,
- cname: loadGames[i].cname,
- cavatar: loadGames[i].cavatar,
- cskinsurl: loadGames[i].cskinsurl,
- cskinsnames: loadGames[i].cskinsnames,
- cskinsprices: loadGames[i].cskinsprices,
- cskins: loadGames[i].cskins,
- ctp: loadGames[i].ctp,
- psteamid: loadGames[i].psteamid,
- pname: loadGames[i].pname,
- pavatar: loadGames[i].pavatar,
- pskinsurl: loadGames[i].pskinsurl,
- pskinsnames: loadGames[i].pskinsnames,
- pskinsprices: loadGames[i].pskinsprices,
- pskins: loadGames[i].pskins,
- ptp: loadGames[i].ptp,
- hash: loadGames[i].hash,
- secret: loadGames[i].secret,
- winner: loadGames[i].winner,
- cpick: loadGames[i].cpick,
- ppick: loadGames[i].ppick,
- timer: timerGame[loadGames[i].id]-time(),
- timer11: loadGames[i].timer11,
- ttimer11: timer11Game[loadGames[i].id]-time(),
- winnerPercentage: loadGames[i].winnerPercentage,
- gameNumber: loadGames[i].id
- });
- }
- }
- }, 1000);
- }
- function LevelCalculate(user)
- {
- pool.query('SELECT xp,level FROM users WHERE steamid = ' + pool.escape(user), function(err, row) {
- if(err) throw err;
- if(row.length == 0) return;
- var currentLevel = row[0].level;
- var currentXp = row[0].xp;
- var xpNeeded = 0;
- var xpMinus = 0;
- for(var i = 1; i < 500; i++)
- {
- xpNeeded += 40 * i;
- xpMinus = xpNeeded - (40 * i-1);
- if(currentXp >= xpMinus && currentXp <= xpNeeded)
- {
- pool.query('UPDATE users SET level = ' + pool.escape(i) + ' WHERE steamid = ' + pool.escape(user));
- }
- }
- });
- }
- for(var j in get_bots)
- {
- if(bots['clients'].hasOwnProperty(j))
- {
- checkBot(j);
- }
- }
- function checkBot(number)
- {
- bots['clients'][number].logOn({
- accountName: get_bots[number]['username'],
- password: get_bots[number]['password'],
- twoFactorCode: SteamTotp.generateAuthCode(get_bots[number]['sharedSecret'])
- });
- bots['managers'][number].on('sentOfferChanged', function(offer, oldState) {
- Oferte(number, offer, oldState);
- });
- bots['managers'][number].on('pollData', function(pollData) {
- fs.writeFile('polldata-bot' + number + '.json', JSON.stringify(pollData));
- });
- if (fs.existsSync('polldata-bot' + number + '.json')) {
- bots['managers'][number].pollData = JSON.parse(fs.readFileSync('polldata-bot' + j + '.json'));
- }
- bots['communities'][number].on('sessionExpired', function() {
- logger.info('Bot ' + number + ' -> session expired, logging again...');
- bots['clients'][number].webLogOn();
- });
- bots['clients'][number].on('webSession', function(sessionID, cookies) {
- bots['managers'][number].setCookies(cookies, function(err) {
- if (err) {
- logger.info('Bot ' + number + ' -> err: ' + err);
- process.exit(1);
- return;
- }
- logger.info('Bot ' + number + ' -> got api key: ' + bots['managers'][number].apiKey);
- });
- bots['communities'][number].setCookies(cookies);
- bots['communities'][number].startConfirmationChecker(config.options.confirmationInterval, get_bots[number]['identitySecret']);
- });
- bots['clients'][number].on('loggedOn', function(details) {
- bots['clients'][number].setPersona(SteamUser.Steam.EPersonaState.Online, get_bots[number]['botname']);
- bots['clients'][number].gamesPlayed(config.options['website_name']);
- });
- }
- function Oferte(bot, offer, oldState)
- {
- if(offer)
- {
- logger.info('Offer #' + offer.id + ' | oldState: ' + oldState + ' | newState: ' + offer.state);
- if(offer.isOurOffer && offer.itemsToReceive.length > 0)
- {
- if(oldState == 2 && (offer.state == 7 || offer.state == 10 || offer.state == 8) && tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
- {
- pool.query('SELECT id,winner,psteamid FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
- if(err) throw err;
- if(res[0].winner == -1)
- {
- if(socketBySteam.hasOwnProperty(res[0].psteamid))
- {
- if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
- {
- io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerDeclined'
- });
- }
- }
- pool.query('UPDATE games SET `psteamid` = "", `pname` = "", `pavatar` = "", `pskinsurl` = "", `pskinsnames` = "", `pskinsprices` = "", `pskins` = "", `ptp` = "", `trade_token` = "" WHERE `trade_token` = ' + pool.escape(offer.id), function(err2, res2) {
- if(err2) throw err2;
- loadAllGames();
- sendGames(res[0].id);
- logger.info('Game joining canceled because the second player cancelled tradeoffer #' + offer.id);
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- });
- }
- else if(oldState == 2 && offer.state == 3)
- {
- if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'newGame')
- {
- var receivedItems = [];
- var assetiddsss = [];
- offer.getReceivedItems(true, function(err, maca) {
- if(err) throw err;
- for(var i in maca)
- {
- receivedItems.push(maca[i]);
- assetiddsss.push(maca[i].assetid);
- }
- var pretul = require('./prices.json');
- var totalSkins = 0;
- var skinImages = [];
- var skinNames = [];
- var skinPrices = [];
- var totalPrice = 0;
- for(var i in receivedItems)
- {
- totalSkins++;
- totalPrice += pretul[receivedItems[i].market_hash_name];
- skinImages.push(receivedItems[i].icon_url);
- skinNames.push(receivedItems[i].market_hash_name);
- skinPrices.push(pretul[receivedItems[i].market_hash_name]);
- }
- //SMECHERIE
- var Skinimages = "";
- var Skinnames = "";
- var Skinprices = "";
- Skinimages = skinImages.join('/');
- Skinnames = skinNames.join('/');
- Skinprices = skinPrices.join('/');
- var timp = new Date();
- var timpCalc = timp.getTime()/1000;
- var name;
- var avatar;
- var steamid = tradingRequests[offer.id]['user'];
- pool.query('SELECT tradelink,name,avatar FROM users WHERE steamid = ' + pool.escape(steamid), function(error, results) {
- if(error) throw error;
- //GENERATE a SECRET
- var hashul = creatusHash('CSGO-' + time() + '-' + results[0].name);
- function creatusHash(datahere)
- {
- var data = datahere;
- var hashess = crypto.createHash('md5').update(data).digest("hex");
- return hashess;
- }
- if(socketBySteam.hasOwnProperty(tradingRequests[offer.id]['user']))
- {
- if(io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']])
- {
- io.sockets.connected[socketBySteam[tradingRequests[offer.id]['user']]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerAccepted'
- });
- }
- }
- pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
- if(haha) throw haha;
- if(huhu.length == 0) return;
- LevelCalculate(steamid);
- });
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
- var nume = results[0].name;
- var avatarul = results[0].avatar;
- pool.query('INSERT INTO games SET expire = ' + pool.escape((time() + tradingRequests[offer.id]['gameExpire']*60)) + ', cassetids = ' + pool.escape(assetiddsss.join('/')) + ', csteamid = ' + pool.escape(steamid) + ', cname = ' + pool.escape(nume) + ', cavatar = ' + pool.escape(avatarul) + ', cskinsurl = ' + pool.escape(Skinimages) + ', cskinsnames = ' + pool.escape(Skinnames) + ', cskinsprices = ' + pool.escape(Skinprices) + ', cskins = ' + pool.escape(totalSkins) + ', ctp = ' + pool.escape(totalPrice) + ', cpick = ' + pool.escape(tradingRequests[offer.id]['side']) + ', tcreated = ' + pool.escape(timpCalc) + ', hash = ' + pool.escape(hashul) + ', bot = ' + pool.escape(bot), function(arr, ass) {
- if(arr) throw arr;
- loadAllGames();
- loadStatistics();
- setTimeout(function() {
- loadGames.forEach(function(itm) {
- if(itm.id == ass.insertId)
- {
- io.sockets.emit('message', {
- type: 'addGame',
- games: {
- 'id': itm.id,
- 'csteamid': itm.csteamid,
- 'cname': itm.cname,
- 'cavatar': itm.cavatar,
- 'cskinsurl': itm.cskinsurl,
- 'cskinsnames': itm.cskinsnames,
- 'cskinsprices': itm.cskinsprices,
- 'cskins': itm.cskins,
- 'ctp': itm.ctp,
- 'psteamid': itm.psteamid,
- 'pname': itm.pname,
- 'pavatar': itm.pavatar,
- 'pskinsurl': itm.pskinsurl,
- 'pskinsnames': itm.pskinsnames,
- 'pskinsprices': itm.pskinsprices,
- 'pskins': itm.pskins,
- 'ptp': itm.ptp,
- 'hash': itm.hash,
- 'secret': itm.secret,
- 'winner': itm.winner,
- 'cpick': itm.cpick,
- 'ppick': itm.ppick,
- 'timer': timerGame[itm.id]-time(),
- 'timer11': itm.timer11,
- 'winnerPercentage': itm.winnerPercentage,
- 'ttimer11': timer11Game[itm.id]-time()
- }
- });
- }
- });
- }, 1200);
- });
- });
- });
- }
- else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joingame')
- {
- pool.query('SELECT pskinsnames,secret,hash,id,ctp,ptp,psteamid,csteamid,cpick,ppick FROM games WHERE trade_token = ' + pool.escape(offer.id), function(err, res) {
- if(err) throw err;
- var receivedItems = [];
- delete gameJoinedExpire[res[0].id];
- var skinsnames = [];
- var skinsids = [];
- var skinsprices = [];
- var pretul = require('./prices.json');
- offer.getReceivedItems(true, function(err, caca) {
- if(err) throw err;
- for(var i in caca)
- {
- receivedItems.push(caca[i].assetid);
- skinsnames.push(caca[i].market_hash_name);
- skinsids.push(caca[i].assetid);
- skinsprices.push(pretul[caca[i].market_hash_name]);
- }
- pool.query('UPDATE games SET passetids = ' + pool.escape(receivedItems.join('/')) + ' WHERE trade_token = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- //GENERATE a SECRET
- var TotalNumberOfTickets = (res[0].ctp+res[0].ptp)*100;
- var winner;
- var secret = createSecret();
- var winnerPercentage = Math.random() * (99.9999999999 - 0.0000000001) + 0.0000000001;
- var winnerTicket = 0;
- winnerTicket = Math.floor((TotalNumberOfTickets - 0.0000000001) * (winnerPercentage / 100));
- if(winnerTicket >= 0 && winnerTicket <= res[0].ctp*100)
- {
- winner = 'ct';
- logger.trace('Ticket #' + winnerTicket + ' - winner ct');
- }
- else if(winnerTicket >= (res[0].ctp+0.01)*100 && winnerTicket <= (res[0].ctp+res[0].ptp)*100)
- {
- winner = 't';
- logger.trace('Ticket #' + winnerTicket + ' - winner t');
- }
- var secret = createSecret();
- function createSecret() {
- var text = "";
- var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/()|";
- for(var i=0; i < 8; i++)
- text += possible.charAt(Math.floor(Math.random() * possible.length));
- return text;
- }
- var hashul = res[0].hash;
- var secretsihash = secret.concat(hashul);
- var steamid = res[0].psteamid;
- pool.query('UPDATE games SET timer11 = 1, secret = ' + pool.escape(secret) + ', ticketWon = ' + pool.escape(winnerTicket) + ', ticketsTotal = ' + pool.escape(parseFloat(res[0].ctp+res[0].ptp)*100) + ', winnerPercentage = ' + pool.escape(winnerPercentage) + ' WHERE trade_token = ' + pool.escape(offer.id), function(aaa, bbb) {
- if(aaa) throw aaa;
- pool.query('UPDATE users SET xp = xp + ' + pool.escape(res[0].ptp*100) + ' WHERE steamid = ' + pool.escape(steamid), function(haha, huhu) {
- if(haha) throw haha;
- if(huhu.length == 0) return;
- LevelCalculate(steamid);
- });
- loadAllGames();
- sendGames(res[0].id);
- });
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
- timer11Game[res[0].id] = time()+10;
- if(socketBySteam.hasOwnProperty(res[0].psteamid))
- {
- if(io.sockets.connected[socketBySteam[res[0].psteamid]['info']])
- {
- io.sockets.connected[socketBySteam[res[0].psteamid]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerAccepted'
- });
- }
- }
- setTimeout(function() {
- pool.query('UPDATE games SET winner = ' + pool.escape(winner) + ' WHERE trade_token = ' + pool.escape(offer.id), function(errr, ress) {
- if(errr) throw errr;
- sendItemsTrade(offer.id, receivedItems.join('/'), winner, skinsnames, skinsids, skinsprices);
- });
- }, 9500);
- });
- });
- });
- }
- else if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'joinJackpot')
- {
- var receivedItems = [];
- var items = [];
- offer.getReceivedItems(true, function(err, maca) {
- if(err) throw err;
- for(var i in maca)
- {
- items.push(maca[i]);
- receivedItems.push(maca[i].assetid);
- }
- var pretul = require('./prices.json');
- if(jackpotState == 'WAITING') jackpotState = 'BETTING';
- var itemsData = [];
- var totalSkins = 0;
- var skinImages = [];
- var skinNames = [];
- var skinPrices = [];
- var totalPrice = 0;
- for(var i in items)
- {
- totalSkins++;
- totalPrice += pretul[items[i].market_hash_name];
- skinImages.push(items[i].icon_url);
- skinNames.push(items[i].market_hash_name);
- skinPrices.push(pretul[items[i].market_hash_name]);
- itemsData.push({
- 'id': items[i].assetid,
- 'price': pretul[items[i].market_hash_name],
- 'name': items[i].market_hash_name,
- 'icon_url': items[i].icon_url
- });
- }
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
- if(jackpotState == 'BETTING')
- {
- var minTicket = parseInt(jackpotTickets+1);
- var maxTicket = parseInt(minTicket+(totalPrice*100)-1);
- for(var a = minTicket; a < maxTicket; a++)
- {
- jackpotTotalTickets.push({
- 'user': tradingRequests[offer.id]['user'],
- 'ticket': parseInt(a)
- });
- }
- jackpotTickets += parseInt(totalPrice*100);
- var assetidsSS = receivedItems.join('/');
- pool.query('INSERT INTO jbets SET user = ' + pool.escape(tradingRequests[offer.id]['user']) + ', assetids = ' + pool.escape(assetidsSS) + ', value = ' + pool.escape(totalPrice) + ', minTicket = ' + pool.escape(minTicket) + ', maxTicket = ' + pool.escape(maxTicket) + ', total = ' + pool.escape(totalSkins) + ', jid = ' + pool.escape(jackpotRound) + ', token = ' + pool.escape(offer.id));
- addJackpotBet(tradingRequests[offer.id]['user'], skinImages, skinNames, skinPrices, totalSkins, totalPrice, itemsData);
- }
- else
- {
- jackpotQueueBets.push({
- 'user': tradingRequests[offer.id]['user'],
- 'offerID': offer.id,
- 'skinImages': skinImages,
- 'skinNames': skinNames,
- 'skinPrices': skinPrices,
- 'totalSkins': totalSkins,
- 'totalPrice': totalPrice,
- 'itemsData': itemsData,
- 'receivedItems': receivedItems
- });
- logger.info('Jackpot round #' + jackpotRound + ' added to queue trade offer #' + offer.id);
- }
- });
- }
- }
- else if(oldState == 2 && offer.state == 7)
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
- if(socketBySteam.hasOwnProperty(maca[0].user))
- {
- if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerDeclined'
- });
- }
- }
- });
- }
- else if(oldState == 2 && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- }
- else if(offer.isOurOffer && offer.itemsToGive.length > 0)
- {
- if((oldState == 2 || oldState == 9) && offer.state == 3)
- {
- if(tradingRequests.hasOwnProperty(offer.id) && tradingRequests[offer.id]['action'] == 'winning')
- {
- pool.query('SELECT user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(socketBySteam.hasOwnProperty(maca[0].user))
- {
- if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerAccepted'
- });
- }
- }
- pool.query('UPDATE trades SET status = ' + pool.escape('Accepted') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- }
- else if((oldState == 2 || oldState == 9) && offer.state == 7)
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Declined') + ' WHERE tid = ' + pool.escape(offer.id));
- if(socketBySteam.hasOwnProperty(maca[0].user))
- {
- if(io.sockets.connected[socketBySteam[maca[0].user]['info']])
- {
- io.sockets.connected[socketBySteam[maca[0].user]['info']].emit('message', {
- type: 'modals',
- tip: 'trade',
- result: 'offerDeclined'
- });
- }
- }
- });
- }
- else if((oldState == 2 || oldState == 9) && (offer.state == 6 || offer.state == 8 || offer.state == 5 || offer.state == 4 || offer.state == 10))
- {
- pool.query('SELECT action,user FROM trades WHERE tid = ' + pool.escape(offer.id), function(caca, maca) {
- if(caca) throw caca;
- if(maca.length == 0) return;
- if(maca[0].action == 'winning') return;
- pool.query('UPDATE trades SET status = ' + pool.escape('Cancelled') + ' WHERE tid = ' + pool.escape(offer.id));
- });
- }
- }
- }
- }
- function addJackpotBet(userBet, skinImages, skinNames, skinPrices, totalSkins, totalPrice, itemsData)
- {
- //SMECHERIE
- var Skinimages = "";
- var Skinnames = "";
- var Skinprices = "";
- Skinimages = skinImages.join('/');
- Skinnames = skinNames.join('/');
- Skinprices = skinPrices.join('/');
- var timp = new Date();
- var timpCalc = timp.getTime()/1000;
- var name;
- var avatar;
- totalJackpotItems += totalSkins;
- totalJackpotValue += totalPrice;
- pool.query('SELECT tradelink,name,avatar,level FROM users WHERE steamid = ' + pool.escape(userBet), function(error, results) {
- if(error) throw error;
- JackpotUsers.push({
- 'userInfo': {
- 'avatar': results[0].avatar,
- 'name': results[0].name,
- 'steamid': userBet,
- 'level': results[0].level
- },
- 'itemsInfo': itemsData
- });
- pool.query('UPDATE users SET xp = xp + ' + pool.escape(totalPrice*100) + ' WHERE steamid = ' + pool.escape(userBet), function(haha, huhu) {
- if(haha) throw haha;
- if(huhu.length == 0) return;
- LevelCalculate(userBet);
- });
- if(JackpotUsers.length == 2)
- {
- totalSecondsJackpot = time()+60;
- checkJackpotEnd = setInterval(function() {
- if(totalSecondsJackpot-time() <= 0)
- {
- jackpotState = 'PICKING_WINNER';
- pickJackpotWinner();
- clearInterval(checkJackpotEnd);
- }
- }, 1000);
- }
- io.sockets.emit('message', {
- type: 'addJackpotBet',
- userInfo: {
- avatar: results[0].avatar,
- name: results[0].name,
- steamid: userBet,
- level: results[0].level
- },
- itemsInfo: itemsData
- });
- io.sockets.emit('message', {
- type: 'jackpotSet',
- totalUsers: JackpotUsers.length,
- potItemsValue: totalJackpotValue,
- potValue: totalJackpotItems,
- timpul: totalSecondsJackpot-time()
- });
- for(var c in JackpotUsers)
- {
- var value = 0;
- for(var z in JackpotUsers[c]['itemsInfo'])
- {
- value += parseFloat(JackpotUsers[c]['itemsInfo'][z]['price']);
- }
- var chance = 100 - ((totalJackpotValue-value)/totalJackpotValue)*100;
- usersPrices[JackpotUsers[c]['userInfo']['steamid']] = value;
- if(socketBySteam.hasOwnProperty(JackpotUsers[c]['userInfo']['steamid']))
- {
- if(io.sockets.connected[socketBySteam[JackpotUsers[c]['userInfo']['steamid']]['info']])
- {
- io.sockets.connected[socketBySteam[JackpotUsers[c]['userInfo']['steamid']]['info']].emit('message', {
- type: 'standingQueue',
- totalItems: JackpotUsers[c]['itemsInfo'].length,
- yourChance: chance
- });
- }
- }
- }
- if(totalJackpotItems >= 50)
- {
- jackpotState = 'PICKING_WINNER';
- pickJackpotWinner();
- }
- });
- }
- function getRandomFloat(min, max) {
- return (Math.random() * (max - min) + min).toFixed(10);
- }
- function handleDisconnect() {
- pool = mysql.createConnection(db_config);
- pool.connect(function(err) {
- if(err) {
- logger.trace('Error: Connecting to database: ', err);
- setTimeout(handleDisconnect, 2000);
- }
- });
- pool.on('error', function(err) {
- logger.trace('Error: Database error: ', err);
- if(err.code == 'PROTOCOL_CONNECTION_LOST') {
- handleDisconnect();
- logger.debug('[SERVER] Reconnected to database!');
- } else {
- throw err;
- }
- });
- }
- function escapeHtml(text) {
- var map = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": '''
- };
- return text.replace(/[&<>"']/g, function(m) { return map[m]; });
- }
- function prize_won_load(steamid, token, prize_won, callback) {
- var prize = prize_won;
- var prizes = bots['managers'][prize_won];
- var add_to_prize = prizes.createOffer(steamid, token);
- prizes.loadInventory(730, 2, true, function(eronata, amount, currency) {
- if(eronata) return callback(1, eronata.toString());
- if(amount.length == 0) return callback(1, 'No prize_won left!');
- for(var i in amount) {
- add_to_prize.addMyItem({'appid': 730, 'contextid': 2, 'assetid': amount[i].assetid});
- }
- add_to_prize.send(function(alt_eronata, statusul) {
- if(alt_eronata) return callback(1, 'Error ' + alt_eronata.toString());
- callback(0, 'Prize number ' + add_to_prize.id + ' was sent. Status: ' + statusul);
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement