Advertisement
cocaineee

example3

Jan 24th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 20.48 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use App\Bet;
  6. use App\Double;
  7. use App\Game;
  8. use App\Http\Controllers\Controller;
  9. use App\Http\Controllers\SteamItem;
  10. use App\Item;
  11. use App\Ticket;
  12. use App\Bots;
  13. use App\User;
  14. use App\Inventory;
  15. use App\DoubleBets;
  16. use App\WinnerTicket;
  17. use App\Http\Controllers\RandomOrgClient;
  18. use Carbon\Carbon;
  19. use App\Config;
  20. use Illuminate\Support\Facades\Redis;
  21. use Request;
  22.  
  23. class GameController extends Controller
  24. {
  25.  
  26.     const NEW_BET_CHANNEL = 'newDeposit';
  27.     const BET_DECLINE_CHANNEL = 'depositDecline';
  28.     const INFO_CHANNEL = 'msgChannel';
  29.     const SHOW_WINNERS = 'show.winners';
  30.     const color = ['rgb(178, 34, 39)', 'rgb(48, 216, 216)', 'rgb(179, 121, 44)'];
  31.     private static $chances_cache = [];
  32.     public $game;
  33.     public $config;
  34.     protected $lastTicket = 0;
  35.  
  36.     public function __construct()
  37.     {
  38.         parent::__construct();
  39.         $this->config = Config::find(1);
  40.         $this->game = $this->getLastGame();
  41.         $this->lastTicket = Redis::get('last.ticket.' . $this->game->id);
  42.         if (is_null($this->lastTicket)) $this->lastTicket = 0;
  43.     }
  44.  
  45.     public function getLastGame()
  46.     {
  47.         $game = Game::orderBy('id', 'desc')->first();
  48.         if (is_null($game)) $game = $this->newGame();
  49.         return $game;
  50.     }
  51.  
  52.     public function newGame()
  53.     {
  54.         $rand_number = "0." . mt_rand(100000000, 999999999) . mt_rand(100000000, 999999999);
  55.         $game = Game::create(['rand_number' => $rand_number]);
  56.         $game->hash = hash('SHA224', $game->rand_number);
  57.         $game->rand_number = 0;
  58.         Redis::set('stats', json_encode(['maxwin' => Game::where('status', 3)->max('price'), 'usertoday' => count(Game::join('bets', 'games.id', '=', 'bets.game_id')->join('users', 'bets.user_id', '=', 'users.id')->where('games.created_at', '>=', Carbon::today())->groupBy('users.username')->select('users.username')->get()), 'gametoday' => Game::where('status', 3)->where('created_at', '>=', Carbon::today())->count()]));
  59.         return $game;
  60.     }
  61.  
  62.     public static function getPreviousWinner()
  63.     {
  64.         $game = Game::with('winner')->where('status', Game::STATUS_FINISHED)->orderBy('created_at', 'desc')->first();
  65.         $winner = null;
  66.         if (!is_null($game)) {
  67.             $winner = [
  68.                 'user' => $game->winner,
  69.                 'price' => $game->price,
  70.                 'chance' => self::_getUserChanceOfGame($game->winner, $game)
  71.             ];
  72.         }
  73.         return $winner;
  74.     }
  75.  
  76.     public static function _getUserChanceOfGame($user, $game)
  77.     {
  78.         $chance = 0;
  79.         if (!is_null($user)) {
  80.             //if(isset(self::$chances_cache[$user->id])) return self::$chances_cache[$user->id];
  81.             $bet = Bet::where('game_id', $game->id)
  82.                 ->where('user_id', $user->id)
  83.                 ->sum('price');
  84.             if ($bet)
  85.                 $chance = round($bet / $game->price, 3) * 100;
  86.             //self::$chances_cache[$user->id] = $chance;
  87.         }
  88.         return $chance;
  89.     }
  90.  
  91.     public static function _getUserChanceOfGameByUser($user_id, $game_id, $game_price)
  92.     {
  93.         $chance = 0;
  94.         if (!is_null($user)) {
  95.             //if(isset(self::$chances_cache[$user->id])) return self::$chances_cache[$user->id];
  96.             $bet = Bet::where('game_id', $game_id)
  97.                 ->where('user_id', $user_id)
  98.                 ->sum('price');
  99.             if ($bet)
  100.                 $chance = round($bet / $game_price, 3) * 100;
  101.             //self::$chances_cache[$user->id] = $chance;
  102.         }
  103.         return $chance;
  104.     }
  105.  
  106.     public function deposit()
  107.     {
  108.         return redirect(self::BOT_TRADE_LINK);
  109.     }
  110.  
  111.  
  112.     public function currentGame()
  113.     {
  114.         /* CLASSICAL */
  115.         $game = Game::orderBy('id', 'desc')->first();
  116.         $percents = $this->_getChancesOfGame($game, true);
  117.         $bets = $game->bets()->with(['user', 'game'])->get()->sortByDesc('created_at');
  118.         $user_chance = $this->_getUserChanceOfGame($this->user, $game);
  119.         if (!is_null($this->user))
  120.             $user_items = $this->user->itemsCountByGame($game);
  121.         return view('pages.index', compact('game', 'double', 'bets', 'user_chance', 'user_items', 'percents'));
  122.     }
  123.  
  124.     private function _getChancesOfGame($game, $is_object = false)
  125.     {
  126.         $chances = [];
  127.         foreach ($game->users() as $user) {
  128.             if ($is_object) {
  129.                 $chances[] = (object)[
  130.                     'chance' => $this->_getUserChanceOfGame($user, $game),
  131.                     'avatar' => $user->avatar,
  132.                     'items' => User::find($user->id)->itemsCountByGame($game),
  133.                     'steamid64' => $user->steamid64
  134.                 ];
  135.             } else {
  136.                 $chances[] = [
  137.                     'chance' => $this->_getUserChanceOfGame($user, $game),
  138.                     'avatar' => $user->avatar,
  139.                     'items' => User::find($user->id)->itemsCountByGame($game),
  140.                     'steamid64' => $user->steamid64
  141.                 ];
  142.             }
  143.  
  144.         }
  145.         return $chances;
  146.     }
  147.  
  148.     public function lastwinner()
  149.     {
  150.         $last_winner = Game::where('status', '=', 3)->where('showwinner', 0)->orderBy('id', 'desc')->take(1)->first();
  151.         $last_winner->showwinner = 1;
  152.         $last_winner->save();
  153.         $user = User::find($last_winner->winner_id);
  154.         $returnValue = [
  155.             'username' => $user->username,
  156.             'avatar' => $user->avatar,
  157.             'steamid64' => $user->steamid64,
  158.             'percent' => $this->_getUserChanceOfGame($user, $last_winner),
  159.             'price' => $last_winner->price
  160.         ];
  161.         return response()->json($returnValue);
  162.     }
  163.  
  164.     public function getCurrentGame()
  165.     {
  166.         $this->game->winner;
  167.         return $this->game;
  168.     }
  169.  
  170.     public function getWinners()
  171.     {
  172.  
  173.         $us = $this->_getChancesOfGame($this->game, true);
  174.       //  $us = $this->game->users();
  175.         $lastBet = Bet::where('game_id', $this->game->id)->orderBy('to', 'desc')->first();
  176.         $random = new RandomOrgClient();
  177.         $arrRandomInt = $random->generateIntegers(1, 1, $lastBet->to, false, 10, true);
  178.         $winTicket = $arrRandomInt[0];
  179.  
  180.         /*
  181.          $winTicket = WinnerTicket::where('game_id', $this->game->id)->first();
  182.          if ($winTicket == null) {
  183.              $winTicket = ceil($this->game->rand_number * $lastBet->to);
  184.          } else {
  185.              $winTicket = $winTicket->winnerticket;
  186.              $this->game->rand_number = $winTicket / $lastBet->to;
  187.              if (strlen($this->game->rand_number) < 20) {
  188.                  $diff = 20 - strlen($this->game->rand_number);
  189.                  $min = "1";
  190.                  $max = "9";
  191.                  for ($i = 1; $i < $diff; $i++) {
  192.                      $min .= "0";
  193.                      $max .= "9";
  194.                  }
  195.                  $this->game->rand_number = $this->game->rand_number . "" . rand($min, $max);
  196.              }
  197.          }*/
  198.  
  199.         $winningBet = Bet::where('game_id', $this->game->id)->where('from', '<=', $winTicket)->where('to', '>=', $winTicket)->first();
  200.         $this->game->winitem = json_encode(json_decode($winningBet->items)[0]);
  201.         $this->game->winner_id = $winningBet->user_id;
  202.         $this->game->status = Game::STATUS_FINISHED;
  203.         $this->game->finished_at = Carbon::now();
  204.         $this->game->signature = $random->last_response['result']['signature'];
  205.         $this->game->random = json_encode($random->last_response['result']['random']);
  206.         $this->game->number = $winTicket;
  207.         $this->game->won_items = json_encode($this->sendItems($this->game->bets, $this->game->winner));
  208.         $this->game->percent = $this->_getUserChanceOfGame($this->game->winner, $this->game);
  209.         $this->game->save();
  210.  
  211.         $returnValue = [
  212.             'game' => $this->game,
  213.             'winner' => $this->game->winner,
  214.             'round_number' => $this->game->rand_number,
  215.             'ticket' => $winTicket,
  216.             'tickets' => $lastBet->to,
  217.             'number' => $winTicket,
  218.             'users' => $us,
  219.             'random' => json_encode($random->last_response['result']['random']),
  220.             'signature' => $random->last_response['result']['signature'],
  221.             'winitem' => $this->game->winitem,
  222.             'ticketwin' => json_encode(['from' => $winningBet->from, 'to' => $winningBet->to]),
  223.             'chance' => $this->_getUserChanceOfGame($this->game->winner, $this->game)
  224.         ];
  225.  
  226.         Redis::del('last.ticket.' . $this->game->id);
  227.  
  228.         return response()->json($returnValue);
  229.     }
  230.  
  231.     public function sendItems($bets, $user)
  232.     {
  233.  
  234.         $itemsInfo = [];
  235.         $items = [];
  236.         $commission = $this->config->COMMISSION;
  237.         $commissionItems = [];
  238.         $returnItems = [];
  239.         $tempPrice = 0;
  240.         $firstBet = Bet::where('game_id', $this->game->id)->orderBy('created_at', 'asc')->first();
  241.         if ($firstBet->user == $user) $commission = $this->config->COMMISSION_FOR_FIRST_PLAYER;
  242.         $commissionPrice = round(($this->game->price / 100) * $commission);
  243.         foreach ($bets as $bet) {
  244.             $betItems = json_decode($bet->items, true);
  245.             foreach ($betItems as $item) {
  246.                 //(Отдавать всю ставку игроку обратно)
  247.                 $item['userid'] = $bet->user_id;
  248.                 if ($bet->user == $user) {
  249.                     Inventory::find($item['id'])->update(['userid' => $bet->user_id, 'status' => 0]);
  250.                     $itemsInfo[] = $item;
  251.                 } else {
  252.                     if (($item['price'] <= $commissionPrice) && ($tempPrice < $commissionPrice)) {
  253.                         Inventory::find($item['id'])->delete();
  254.                         $commissionItems[] = $item;
  255.                         $tempPrice = $tempPrice + $item['price'];
  256.                     } else {
  257.                         Inventory::find($item['id'])->update(['userid' => $bet->user_id, 'status' => 0]);
  258.                         $itemsInfo[] = $item;
  259.                     }
  260.                 }
  261.             }
  262.         }
  263.  
  264.  
  265.         $value = [
  266.             'appId' => $this->config->APPID,
  267.             'steamid' => $user->steamid64,
  268.             'accessToken' => $user->accessToken,
  269.             'items' => $returnItems,
  270.             'game' => $this->game->id
  271.         ];
  272.  
  273.  
  274.         return $itemsInfo;
  275.     }
  276.  
  277.     public function newBet()
  278.     {
  279.         if (\Cache::has('bet.user.' . $this->user->id)) return 0;
  280.         \Cache::put('bet.user.' . $this->user->id, '', 0.02);
  281.  
  282.         if (is_null(Request::get('items')) || Request::get('items') == '[]' || is_numeric(Request::get('items'))) return response()->json(['errors' => 'Вы не выбрали вещей!']);
  283.         $user = $this->user;
  284.         $totalItems = $this->user->itemsCountByGame($this->game);
  285.         if ($this->game->status == Game::STATUS_PRE_FINISH || $this->game->status == Game::STATUS_FINISHED) {
  286.             return response()->json(['errors' => 'Дождитесь следующей игры!']);
  287.         }
  288.         if ($totalItems > $this->config->MAX_ITEMS || $totalItems + count(json_decode(Request::get('items'))) > $this->config->MAX_ITEMS || count(json_decode(Request::get('items'))) > $this->config->MAX_ITEMS) {
  289.             return response()->json(['errors' => 'Максимальное кол-во предметов для депозита - ' . $this->config->MAX_ITEMS]);
  290.         }
  291.         $newBet['price'] = 0;
  292.         $this->lastTicket = Redis::get('last.ticket.' . $this->game->id);
  293.         if (is_null($this->lastTicket)) $this->lastTicket = 0;
  294.  
  295.         $ticketFrom = 1;
  296.         if ($this->lastTicket != 0)
  297.             $ticketFrom = $this->lastTicket + 1;
  298.  
  299.         $tickbet = $ticketFrom;
  300.         $i = 0;
  301.         $newBet['items'] = [];
  302.         foreach (json_decode(Request::get('items')) as $itm) {
  303.             $item = Inventory::select('id', 'classid', 'userid', 'name', 'market_hash_name')->find($itm);
  304.             if (is_null($item) || $item->userid != $this->user->id || $item->stauts == 1) return response()->json(['errors' => 'В вашем инвентаре нету такой вещи!']);
  305.             $item->status = 1;
  306.             $item->save();
  307.             $info = Item::where('classid', $item->classid)->first();
  308.             if (is_null($info)) {
  309.                 $info = new SteamItem($item);
  310.                 if ($info->price != null) {
  311.                     Item::create((array)$info);
  312.                 }
  313.             }
  314.             $item->name = $item->name;
  315.             $item->market_hash_name = $info->market_hash_name;
  316.             $item->price = $info->price;
  317.             $item->rarity = $info->rarity;
  318.             $item->color = $info->color;
  319.             $item->backgroundcolor = $info->backgroundcolor;
  320.             $item->from = $tickbet;
  321.             $item->to = ceil($item->from + $info->price * 1.5) - 1;
  322.             $tickbet = ceil($item->from + $info->price * 1.5);
  323.             array_push($newBet['items'], $item);
  324.             $newBet['price'] += $info->price;
  325.  
  326.         }
  327.  
  328.         if (is_null($newBet['items'])) return response()->json(['errors' => 'В вашем инвентаре нет такой вещи!']);
  329.  
  330.  
  331.         $ticketTo = $ticketFrom + ceil($newBet['price'] * 1.5) - 1;
  332.         Redis::set('last.ticket.' . $this->game->id, $ticketTo);
  333.  
  334.         $bet = new Bet();
  335.         $bet->user()->associate($user);
  336.         $bet->items = json_encode(array_reverse($newBet['items']));
  337.         $bet->itemsCount = count($newBet['items']);
  338.         $bet->price = ceil($newBet['price']);
  339.         $bet->from = $ticketFrom;
  340.         $bet->to = $ticketTo;
  341.         $bet->game()->associate($this->game);
  342.         $bet->save();
  343.  
  344.         $bets = Bet::where('game_id', $this->game->id);
  345.         $this->game->items = $bets->sum('itemsCount');
  346.         $this->game->price = $bets->sum('price');
  347.  
  348.         if (count($this->game->users()) >= $this->config->MIN_USERS || $this->game->items >= $this->config->MAX_ITEMSALL) {
  349.             $this->game->status = Game::STATUS_PLAYING;
  350.             $this->game->started_at = Carbon::now();
  351.         }
  352.  
  353.         if ($this->game->items >= $this->config->MAX_ITEMSALL) {
  354.             $this->game->status = Game::STATUS_FINISHED;
  355.             Redis::publish(self::SHOW_WINNERS, true);
  356.         }
  357.  
  358.         $this->game->save();
  359.  
  360.         $chances = $this->_getChancesOfGame($this->game);
  361.         $returnValue = [
  362.             'betId' => $bet->id,
  363.             'userId' => $user->steam64,
  364.             'html' => view('includes.bet', compact('bet'))->render(),
  365.             'itemsCount' => $this->game->items,
  366.             'gamePrice' => $this->game->price,
  367.             'gameStatus' => $this->game->status,
  368.             'chances' => $chances
  369.         ];
  370.  
  371.         Redis::publish(self::NEW_BET_CHANNEL, json_encode($returnValue));
  372.         Redis::set('stats', json_encode(['maxwin' => Game::where('status', 3)->max('price'), 'usertoday' => count(Game::join('bets', 'games.id', '=', 'bets.game_id')->join('users', 'bets.user_id', '=', 'users.id')->where('games.created_at', '>=', Carbon::today())->groupBy('users.username')->select('users.username')->get()), 'gametoday' => Game::where('status', 3)->where('created_at', '>=', Carbon::today())->count()]));
  373.         return response()->json(['success' => 'Ставка принята']);
  374.  
  375.     }
  376.  
  377.     public function setGameStatus()
  378.     {
  379.         $this->game->status = Request::get('status');
  380.         $this->game->save();
  381.         return $this->game;
  382.     }
  383.  
  384.     public function setPrizeStatus()
  385.     {
  386.         $game = Game::find(Request::get('game'));
  387.         $game->status_prize = Request::get('status');
  388.         $game->save();
  389.         return $game;
  390.     }
  391.  
  392.     public function newdepositapi()
  393.     {
  394.  
  395.  
  396.         $data = Redis::lrange('checkTrade', 0, -1);
  397.         foreach ($data as $i) {
  398.             $info = json_decode($i);
  399.             $user = User::find($info->userid);
  400.             foreach ($info->items as $item) {
  401.                 $inventory = new Inventory();
  402.                 $inventory->userid = $info->userid;
  403.                 $inventory->inventoryId = $item->id;
  404.                 $inventory->bot = $info->bot;
  405.                 $inventory->market_hash_name = $item->market_hash_name;
  406.                 $inventory->name = $item->market_name;
  407.                 $inventory->classid = $item->classid;
  408.                 $inventory->type =  $item->type;
  409.                 $inventory->save();
  410.             }
  411.             Redis::lrem('checkTrade', 0, $i);
  412.             \Cache::forget('inventory_' . $user->steamid64);
  413.             return $this->_responseSuccess();
  414.         }
  415.     }
  416.  
  417.     private function _responseSuccess()
  418.     {
  419.         return response()->json(['success' => true]);
  420.     }
  421.  
  422.  
  423.     public function without()
  424.     {
  425.  
  426.         if (empty($this->user->trade_link)) return response()->json(["errors" => "Укажите ссылку на обмен!"]);
  427.         if (is_null(Request::get('items')) || Request::get('items') == '[]' || is_numeric(Request::get('items'))) return response()->json(['errors' => 'Вы не выбрали вещей!']);
  428.  
  429.  
  430.         $itemtotake = [];
  431.         $bot = 0;
  432.         foreach (json_decode(Request::get('items')) as $itm) {
  433.             $item = Inventory::select('id', 'classid','inventoryId','bot', 'userid', 'name', 'market_hash_name')->find($itm);
  434.             $bot = $item->bot;
  435.             if (is_null($item) || $item->userid != $this->user->id || $item->stauts == 1) return response()->json(['errors' => 'В вашем инвентаре нету такой вещи!']);
  436.             if($bot == $item->bot){
  437.                 array_push($itemtotake, ['id' => $item->inventoryId, 'classid' => $item->classid, 'market_name' => $item->market_name, 'type' => $item->type, 'market_hash_name' => $item->market_hash_name]);
  438.                 $item->delete();
  439.             }
  440.         }
  441.  
  442.         $value = [
  443.             'appId' => $this->config->APPID,
  444.             'trade' => $this->user->trade_link,
  445.             'items' => $itemtotake,
  446.             'userid' => $this->user->id,
  447.             'user' => $this->user->steamid64,
  448.             'bot' => $bot,
  449.             'code' => hash('adler32', $this->config->APPID . mt_rand(1, 99) . $this->user->id)
  450.         ];
  451.         Redis::rpush('send.items', json_encode($value));
  452.  
  453.         if(count($itemtotake) < count(json_decode(Request::get('items')))) return response()->json(['errors' => 'Трейд отправлен , но отправлены не все вещи , попробуйте ещё раз!']);
  454.         return response()->json(['success' => 'Запрос на трейд отправлен!']);
  455.  
  456.     }
  457.  
  458.  
  459.     public function newdeposit()
  460.     {
  461.  
  462.         if (empty($this->user->trade_link)) return response()->json(["errors" => "Укажите ссылку на обмен!"]);
  463.         if (is_null(Request::get('items')) || Request::get('items') == '[]' || is_numeric(Request::get('items'))) return response()->json(['errors' => 'Вы не выбрали вещей!']);
  464.         if (\Cache::has('dep.user.' . $this->user->id)) return response()->json(['errors' => 'Ожидайте трейд!']);
  465.         \Cache::put('dep.user.' . $this->user->id, '', 0.06);
  466.         $itemtotake = [];
  467.         $items = \Cache::get('inventory_' . $this->user->steamid64);
  468.         $deposit = json_decode(Request::get('items'));
  469.         foreach ($items as $item) {
  470.             for ($i = 0; $i < count($deposit); $i++) {
  471.                 if ($deposit[$i] == $item->id) {
  472.                     array_push($itemtotake, ['id' => $item->id, 'classid' => $item->classid, 'market_name' => $item->market_name, 'type' => $item->type, 'market_hash_name' => $item->market_hash_name]);
  473.                 }
  474.             }
  475.         }
  476.         $bot = Bots::select('id')->orderByRaw("RAND()")->take(1)->first();
  477.         $value = [
  478.             'appId' => $this->config->APPID,
  479.             'trade' => $this->user->trade_link,
  480.             'items' => $itemtotake,
  481.             'userid' => $this->user->id,
  482.             'user' => $this->user->steamid64,
  483.             'bot' => $bot->id,
  484.             'code' => hash('adler32', $this->config->APPID . mt_rand(1, 99) . $this->user->id)
  485.         ];
  486.         Redis::rpush('take.items', json_encode($value));
  487.     }
  488.  
  489.     public function getBalance()
  490.     {
  491.         return $this->user->money;
  492.     }
  493.  
  494.     private function _responseMessageToSite($message, $user)
  495.     {
  496.         return Redis::publish(self::INFO_CHANNEL, json_encode([
  497.             'user' => $user,
  498.             'msg' => $message
  499.         ]));
  500.     }
  501.  
  502. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement